Manifolds: TOP $\supseteq$ TRI $\supseteq$ PL $\supseteq$ DIFF?

Question: Let me denote the following

(TOP) topological manifolds
(PDIFF), for piecewise differentiable
(PL) piecewise-smooth manifolds
(DIFF) the smooth manifolds
(TRI) triangulable manifolds

Is it true that

(1) TOP $\supseteq$ TRI ?
Namely, every TRI must be TOP manifolds?
(2) TRI $\supseteq$ PL ?
Namely, every PL must be TRI manifolds?
(3) TRI $\supseteq$ DIFF ?
Namely, every DIFF must be TRI manifolds?
(4) PL $\supseteq$ DIFF ?
Namely, every DIFF must be PL manifolds?
(5) So in a short summary, is it true that
$$\text{ TOP $\supseteq$ TRI $\supseteq$ PL $\supseteq$ DIFF} ?$$
How to think these categories of manifolds in terms of categories (or sets with whose objects are manifolds)? What are their intersections, unions and complements?
Comment: @all, if you guys have an answer - it will be nice to answer directly. thanks!
Comment: I don't understand what you mean by thinking in terms of sets. The answer pretty much depend on your definition of manifolds.
Comment: i.e. categories of manifolds in terms of **categories** (or **sets** with whose objects are manifolds)?
Comment: What is your definition of manifolds?
Comment: I guessed annie heart she meant that https://en.wikipedia.org/wiki/Topological_manifold
Comment: @user170039 https://en.wikipedia.org/wiki/PDIFF
Comment: @wonderich: I thought so too. But note that there are variety of definitions that goes by the name "manifold" as noted [here](https://en.wikipedia.org/wiki/Manifold#Mathematical_definition).
Answer: Yes, these inclusions are all true.
1) is true because "manifold" and "topological manifold" are actually synonyms.
2) is true by an almost obvious construction: very roughly speaking, a locally finite covering by charts in the given PL atlas can be triangulated one chart at a time.
4) is true by a theorem of Whitney.
3) follows from 2) and 4).
Comment: thanks, vote up, a more advanced question is here: https://mathoverflow.net/questions/335386


Combinatorics: Amount of options for majority

Question: Say we have $2n$ people. Then the amount of options to form a majority (e.g. in a commission) are
$ \binom{2n}{n+1} + \binom{2n}{n+2} + \cdots + \binom{2n}{2n}$
I want to prove, that this is equal to $\frac{1}{2} \left[ 2^{2n} - \binom{2n}{n} \right]$
But I'm stuck. I have the this formula: $ \binom{n}{0} + \binom{n}{1} + \cdots + \binom{n}{n} = 2^n $
So I can say $ \binom{2n}{n+1} + \binom{2n}{n+2} + \cdots + \binom{2n}{n} = 2^{2n} - \left[ \binom{2n}{n} + \binom{2n}{n-1} + \cdots + \binom{2n}{n-n} \right] = 2^{2n} - \left[ \binom{2n}{0} + \binom{2n}{1} + \cdots + \binom{2n}{n} \right] $
But I can't see where to go from there, even when writing the binomial coefficients as $ \frac{n!}{k!(n-k)!} $
Can anyone help me with it?
Comment: You don't want the combinatorial proof?  Other that subsets with exactly half the elements, we can pair a subset with its complement and exactly one of those two will be a majority.  But of course you can mimic that argument with the binomial coefficients if you really want to.
Comment: @Hebol combinatorical proof means a proof based on logic not involving algebra...if you want a combinatorical proof too...you can ask that as a separate question:)
Comment: I sketched the combinatorial proof in my comments.  Divide the subsets in two collections...one collection consists of subsets with $n$ elements, the rest are the other cololection.  First has $\binom {2n}n$ elements.  The second has $2^n-\binom {2n}n$ elements.  Half of the second have more than $2n$ (since you can pair up the elements in the second collection, each with its complement, and exactly one member of each pair has more than $n$ element.s
Comment: $\sum\limits_{k=n+1}^{2n} = \sum\limits_{k=0}^{2n}-\sum\limits_{k=0}^{n}$
Comment: @lulu What do you mean with combinatorial proof? Can you explain more what you mean by that?
Answer: By symmetry $\binom{2n}{k}=\binom{2n}{2n-k}$ for $k=0,\ldots,n-1.$
So the sum, call is $S$, you have is also equal to
$$
\binom{2n}{0}+\binom{2n}{1}+\cdots+\binom{2n}{n-1}.
$$
Now $2S+\binom{2n}{n}=2^{2n},$ does it.
Comment: Thank you! This answered the question!
Answer:
There are $2^{2n}$ ways of selecting a subset to vote "Yes" and the rest "No".

Of these, ${2n \choose n}$ are the number of ways to have equal "Yes" and "No" votes,

leaving  $2^{2n}-{2n \choose n}$ possibilities with a decisive result,

half of which have a majority voting "Yes", getting your result

(the other half of the possibilities would have a majority voting "No"; a particular subset of individuals with the majority would be double counted, once when voting "Yes" against the rest and once when voting "No" against the rest).
Comment: Thanks, that really explains the formulas shape very well!
Answer: By the property of binomial coefficients $$\binom{n}{r}=\binom{n}{n-r}$$
$\implies \binom{2n}{n+1}=\binom{2n}{n-1}$
$\implies\binom{2n}{n+2}=\binom{2n}{n-2}$ and so on

Let $$A=\binom{2n}{n+1}+\cdots+\binom{2n}{2n}$$ Also
$$A=\binom{2n}{0}+\cdots+\binom{2n}{n-1}$$
So $$2A=2^{2n}-\binom{2n}{n}$$
Comment: Thank you for you help!


função de pesquisa em Laravel retorna erro TokenMismatchException in VerifyCsrfToken.php

Question: Boa noite amigos, sou novato no laravel e estou precisando construir uma função para pesquisa de dados de uma tabela, fiz algo baseado no que entendi até este momento, mas esta me retornando a seguinte mensagem de erro **TokenMismatchException in VerifyCsrfToken.php line 67:**quando é solicitado a rota. abaixo segue o código:
routes.php
Route::post('clientes/pesquisa', 'ClientesController@pesquisa');

ClientesController.php
public function pesquisa(){
        $pesq = Input::get('pesq');
        $resultado = Tb_clientes::where('idempresa', 1)->where('nome', '=',$pesq)->get();
        return view('clientes.index')->with('tb_clientes', $resultado);
    }

O local de chamada da rota
<form class="form-inline" method="post" role="form" action="/clientes/pesquisa">

                            Pesquisar:
                            <input type="text" class="form-control input-sm" id="pesq">

                          <button type="submit" class="btn btn-default"></button>
                        </form>

Estou fazendo certo ou tem uma maneira mais fácil?
Comment: Editado. Obrigado
Comment: Bem vindo ao SOpt. Acesse a Ajuda e faça o Tour. Aqui no caso desta questão você precisa apresentar parte do teu código. Edite a pergunta e insira o código abaixo dela. Será mais fácil te ajudar.
Comment: Perfeito! Bom trabalho! Não deixe de marcar a resposta que te atendeu de alguma forma (ou a melhor entre elas) e votar nas perguntas e respostas que forem importantes parta você.
Answer: Seu primeiro e mais importante passo é ler a maior parte possível da documentação oficial (se não a documentação inteira), acredite, a documentação é e sempre sera sua melhor companhia.
Antes de realizar uma pesquisa você deve aprender a construir uma nova aplicação do zero, definir as configurações iniciais da sua aplicação e configurar seu ambiente de desenvolvimento. Posso adiantar que você vai precisar definir e configurar o seu banco de dados, suas rotas básicas, seus modelos, e, só então, criar, ler, atualizar e deletar estes dados.
Em relação a nossa comunidade, gostaria de te dar as boas vindas e reforçar uma parte do texto de introdução que diz o seguinte:

Concentre sua atenção em perguntas sobre um problema real que você
  enfrentou. Inclua detalhes sobre o que você tentou e exatamente o que
  você está tentando fazer.

Sua questão está muito simples e incompleta, procure nos informar o que você já tentou e em quais pontos você está com maiores dificuldades. Não se esqueça de utilizar a pesquisa ali em cima para procurar perguntas relacionadas e que talvez também funcione para você (tente também o nosso bom e velho amigo Google).
Se por final você ainda estiver com problemas, tente editar sua pergunta e acrescentar mais detalhes.
Espero que isso tenha te ajudado de alguma forma, vou deixar alguns links interessantes que encontrei com uma simples pesquisa no Google, relacionados a Laravel.

Laravel Brasil
Webschool
Learning Laravel

E não poderia deixar de te indicar o Laracasts.
Comment: Ok, muito obrigado Rafael, vou primeiro dar uma olhada na documentação conforme indicado, já configurei banco rotas e etc, só preciso implementar a pesquisa em uma página, mas primeiro vou dar mais uma olhada e caso não consiga colocarei aqui o que tentei. Obrigado
Comment: Combinado @FilipeGuedes, mais uma vez bem vindo a nossa comunidade. Uma sugestão a mais, veja se consegue seguir o tutorial da documentação oficial onde você constrói uma simples (ou avançada) [lista de tarefas](https://laravel.com/docs/5.2/quickstart).
Answer: Galera já está resolvido só coloquei  input
<input type="hidden" name="_token" value="{{ csrf_token() }}">

deu certo!
Comment: Fico feliz que tenha conseguido, sua questão ficou melhor após as alterações.


Logical Equivalences not using a truth table

Question: I am tasked by using logical equivalences to show $[q \land \neg(p \implies q)]$  is tautology or a contradiction. I know that by setting up a truth table that it is false. I did a truth table and confirmed it on wolfram! I am having a hard time showing the logical equivalences without a truth table. Can someone help?
Answer: For $[q\text{ and }\sim(p\text{ implies }q)]$ to be true, we need $q$ to be true and $p$ implies $q$ to be false. Under what circumstances is $p$ implies $q$ false?
Edit: The statement $p$ implies $q$ is false only if $p$ is true and $q$ is false. Therefore for $[q\text{ and }\sim(p\text{ implies }q)]$ to be true, we need $[q\text{ and }(p\text{ and }\sim q)]$ to be true. Thus it is never true.
Comment: are you asking what law it would be?
Comment: Will edit with more details
Answer: \begin{align}
q\land \sim(p\implies q)&\equiv q\land(p\land\sim q)\\&\equiv(q\land\sim q)\land p\equiv\color{red}{\text{Contradiction}}
\end{align}
Comment: @Jkoz Yes, Implication equivalence, De Morgan's negation, and Disjunctive syllogism, are all you need.  (Suhail combined the first two into one step.)
Comment: is this the only law that would be used? Like i said before i know from the truth table that it is a contradiction. Is this the only logical equivalence?
Comment: oh ok thank you so much


What can I use to layout the content type form input when creating content?

Question: I have created a content type with about 15 fields.
I'd like to improve the layout of the form for creating content of this content type.
Currently all the input fields are listed one after the other which means a lot of vertical scrolling and not everything can be seen on one page.
I looked at the Display Suite module ( http://drupal.org/project/ds ) but I could only see how to layout the resulting content not the input form used to create it. (UPDATED: answer below from Елин Й. says that display suite can actually layout the input form)
Another option would be to create a theme with form layout (good question - and answers here: How to a use a template file to theme a form? ). That's fine, but before I do that I wanted to look at other options available (don't wish to re-invent the wheel.)
Or should I use entities and EntityForm instead if that provides better layout options.
Finally, I'd prefer not to use webform module as EntityForms and ContentTypes provide better integration with built in Drupal features, so I've read.
Answer: Display Suite is capable of formating form layout, as well.

Modules included:
Display Suite: The main module to rearrange your fields.
Search: extend the search results for Drupal core or Apache Solr.
Extras: extra functionality like semantic fields, region to block, hide page title etc.
Forms: style the layout of forms.
Format: provides a PHP filter with entity context (only 7.x-2.x and higher)
UI: Manage custom fields, classes and view modes through UI (only 7.x-2.x and higher)

You should enable the Display Suite Forms module, which is shipped with DS.
Under the 'manage fields' tab of your content type
admin/structure/types/manage/your_content_type/fields

At the bottom, you have an option to select a layout for the form.
Comment: +1 thanks @Елин Й. I am glad I was wrong and that you can format form fields! (Likely to accept this answer - I will follow up and let you know how I get on.)
Answer: You can make use of the Field group Module

Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

There are also other modules you can use with it such as the Multistep module

Multistep adds multiple-step functionality to content type editing
  forms. It does so by assigning a step number to each fieldgroup within
  the content type and hiding all the groups that do not belong to the
  current step. The user can then use different submitting buttons that
  will redirect to the previous, next, or current step.
Comment: +1 thanks @4life good to know (could it be used in conjunction with displaysuite or is there no benefit?) By the way, just for info, there are a few modules similar to multistep module for certain scenarios perhaps: https://drupal.org/project/field-conditional-state and https://drupal.org/project/conditional_fields
Answer: There is also another way to theme the node form, that you can do it completely with code in your theme folder without using any other module.
First, in your theme folder, edit template.php file, and implement hook_theme() to tell about your template file.
function YOURTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'your_content_type_node_form' => array(
      'render element' => 'form',
      'template' => 'your-content-type-node-form',
      'path' => drupal_get_path('theme', 'YOURTHEME') . '/templates/forms',
    ),
  );
}

The above code assumes that your theme name is YOURTHEME, and you want to use a template file named your-content-type-node-form.tpl.php, and you want to put this template file in your theme folder under YOURTHEME/templates/forms.
Then, you can create the specified file under the specified folder and you can build your custom template file from scratch, which will be a very painstaking job, but at the end you will have a layout that you have a full control over it.
You can print individual fields in this template file like:
<?php print render($form['field_yourfield']);?>

You will have also many other variables and functions available.
After building the form completely, printing all the fields you set in your content type, you should always print the rest of the form, which includes all the hidden fields and tokens that Drupal adds to you form.
<?php print drupal_render_children($form); ?>

If you don't include that, your form will probably not work. That line does also make sure that no fields are missing in the form that you would forget to print.
If you want to apply also some logic or another functionalities to your form or form elements, you can use hook_form_FORM_ID_alter() in your template.php file, which requires a good knowledge about Form API.
An example implementation of hook_form_FORM_ID_alter() for this post would be:
function YOURTHEME_form_your_content_type_node_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#size'] = 30;
}

This would set the size of the title field to 30, which is not possible using the Fields UI.
Comment: Just read this again - this is a useful answer as well as the accepted answer, also a related answer is here: http://drupal.stackexchange.com/questions/312/how-to-a-use-a-template-file-to-theme-a-form and thank you for the detail about what to put in the theme code. A question I have is outputting the fields - one would want to loop through an array rather than hard code field output in case fields are added or removed. Using an array means that we get whatever happens to be in it rather than having to know exactly what is in it as with the hard coding.


Browser automatically adding attribute value to tag

Question: I have this tag with an attribute without its value

But when I inspect this element in the browser it adds this value to it as if it is a default value

This creates an issue when using Angular as this directive expects an expression there but if not supplied any expression it uses its default options. But I will never have scroll-glue defined as an expression.
For the time being I have edited the directive code itself to check if the attribute value is scroll-glue and treat it as if the value has not been specified. But I dont understand why this behaviour is occurring. Is there any flags I need to set in order to disable this *behaviour?
Browser details :
Google Chrome Version 55.0.2883.87 m
Comment: Which browser are you using?
Comment: Hey @EduardMalakhov I have updated my answer with the browser details
Comment: I suspect that this might be a third-party script that modifies  the attribute, not chrome itself. With chrome you can try the following to do some additional research:
1. Open developer tools (F12)
2. Select your div in the Elements view
3. Right-click it and set Break on... -> Attribute modifications
4. Reload the page to see which script really does the modification
Comment: I can't reproduce that, in the exact same Chrome version. When I create a document with a DIV element with the attribute as you have shown, then in DOM inspector I still see it that way - it has not been "expanded" to a name="value" pair. Are you delivering your document as HTML or XML? XML does not allow stand-alone attributes, so it might be that in _that_ case it indeed gets transformed to the result you're seeing.
Comment: I am actually using JADE as the templating language.
Answer: In Jade use doctype html. See this related issue on GitHub.


hide() jquery doesn't work

Question: I want to make an alarm which starts and stop after some time. So I put setInterval in code. Also I want to show a message when the alarm rings. For this, I make a text in my last div and make it hide by jQuery hide(). Here in my code, p.show doesn't hide by jQuery hide() .

<!DOCTYPE html>

  <title>My Rest Alarm</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <form class="form-inline">

        Alarm will ring after :
        <input type="text" class="form-control" id="minute"> minute

    </form>

    <button class="btn btn-success start"> Start </button>
    <button class="btn btn-danger stop"> Stop </button>

It's time to rest

Why doesn't it hide?
Comment: Clicked "Run code snippet" -> clicked "Start" without filling in value for munutes, out of curiosity -> nearly got scared to death. Bug report: does not work well if you're in a quiet room with headphones on.
Comment: @adeneo so, resolution is "Can't reproduce: no QA team left after following the steps"
Comment: How do you load the html above the JS block, is it with an ajax call or some sort of dynamic loading?
Comment: @vlaz - not a bug, the intended use case is to scare users to death, all though not a very good business decision ?
Answer: It doesn't work because Bootstrap also uses the class .show and sets the style
display : block!important;

on it, and !important styles override inline styles.
To fix the issue, just use a className other than .show

hide() jquery doesn't work


What is the isomorphism class of the kernel of a homomorphism of cyclic groups?

Question:
Consider the homomorphism $\phi:(\mathbb{Z}/27\mathbb{Z})\times(\mathbb{Z}/9\mathbb{Z})\to\mathbb{Z}/3\mathbb{Z}$ defined by $(a,b)\mapsto a+b$. What is the isomorphism class of $\ker\phi$?

The elements of $\ker\phi$ consist of ordered pairs $(a,b)$ where $a+b=3n$ for a positive integer $n\leq9$. There are $27\times 3=9\times 9=81$ elements of $\ker\phi$, since given the first coordinate, there are 3 options for the second coordinate (e.g., choosing 1 for the first coordinate of an element of $\ker\phi$, we can have 2, 5, or 8 in the second coordinate). However, I'm not sure how to find the group structure on this set, except to say that $\ker\phi$ is a normal subgroup of $(\mathbb{Z}/27\mathbb{Z})\times(\mathbb{Z}/9\mathbb{Z})$. (But in this case we have normality anyway because the groups are abelian.)
A hint would be very appreciated.
Comment: One element in the kenel is $(1,-1)$.  What is its order in $\mathbf Z/27\mathbf Z \times \mathbf Z/9\mathbf Z$?  Use the classification of finite abelian groups to show every subgroup of $\mathbf Z/p^a\mathbf Z \times \mathbf Z/p^b\mathbf Z$ is *isomorphic* to $\mathbf Z/p^i\mathbf Z \times \mathbf Z/p^j\mathbf Z$ where $i \leq a$ and $j \leq b$.
Comment: Could I make sure I understand the strategy you're suggesting? We use the fact that the group has the form $\mathbb{Z}/p^i\mathbb{Z}\times\mathbb{Z}/p^j\mathbb{Z}$, then consider an element of the kernel of the greatest possible order to find $p^i$. Then we're left to find $p^j$ by looking at the order of $\text{ker}\phi$.
Comment: The kernel has size $81$ and the maximal possible order an element of the kernel can have is $27$.  What's the order of $(1,-1)$ in the kernel? Making all that information consistent will reveal the abstract group structure of the kernel
Comment: By the way, if you look up the classification of finite abelian groups you'll find that when $a$ is an element of maximal order in a finite abelian group $A$, there is a direct product decomposition $A \cong \langle a\rangle \times B$ for some subgroup $B$.
Answer: Lets call G the group. A good way of narrowing down is using a consecuense of the first theorem of isomorphism as the cardinalities are finite and the morphism is surjective, we have:
$$|\ker(\phi)|\cdot |img(\phi)| = |G|$$
Where we get $|\ker(\phi)|= 3^4$
Then if we take $a$ and $b$ module 3, you can see that if $a\equiv 0 \implies b\equiv 0$ as $a+b\equiv 0$ analogously $a\equiv 1 \implies b\equiv 2$ and $a\equiv 2 \implies b\equiv 1$ and this cover all cases and more over the cardinalities argument will prove that this are all cases.
The preivuos analisis gives the elements in the kernel $$\{(3k,3l),(3k+1,3l+2),(3k+2,3l+1)|k,l \in \mathbb{Z}\}$$
And for each form is a simple count that are $3^3$ elements, and three (disjoint) forms, having $3^4$ elements ie all the elements in the kernel.
Finally by the way we find the elements in the kernel is isomorphic to:
$\mathbb{Z}/27\mathbb{Z}\times\mathbb{Z}/3\mathbb{Z}$.
That if beacuse of each $a \in \mathbb{Z}$ there are three elements in the kernel $(a,-a),(a,3-a),(a,6-a)$.
Answer: Let $u,v$ be the classes of $(1,-1)$ and $(0,3)$ in $\Bbb Z/27\Bbb Z\times\Bbb Z/9\Bbb Z$. Their orders are respectively $27$ and $3$, and every element of $\ker\phi$ writes uniquely
$$au+cv,\quad 0\le a<27,\quad0\le c<3,$$
hence
$$\ker\phi=\langle u\rangle\oplus\langle v\rangle\simeq\Bbb Z/27\Bbb Z\times\Bbb Z/3\Bbb Z.$$
Edit: proof (upon request by two comments) that every element in $\ker\phi$ writes uniquely
$$au+cv,\quad 0\le a<27,\quad0\le c<3.$$ Let
$x\in[0,27),y\in[0,9)$ be integers such that $3\mid x+y$. Then, the class of $(x,y)$ in
$\Bbb Z/27\Bbb Z\times\Bbb Z/9\Bbb Z$ writes as above iff
$$a\in[0,27),\quad c\in[0,3),\quad x\equiv a\bmod{27},\text{ and }y\equiv-a+3c\bmod9,$$
i.e. iff
$$a=x,\quad c\in[0,3),\text{ and }x+y\equiv3c\bmod9,$$
i.e. $a=x$ and $c$ is the unique integer in $[0,3)$ such that $c\equiv\frac{x+y}3\bmod3$.


Diversas tabelas que deveriam representar uma única entidade

Question: Estou atualizando um sistema que possui onze tabelas que representam uma única entidade, acredito que por erro de implementação, conforme exemplo abaixo:
Entidade: Foo

Tabela Foo1 - Campo1, Campo2, Campo3
Tabela Foo2 - Campo1, Campo2, Campo3
Tabela Foo3 - Campo1, Campo2, Campo3, Campo4
[...]

Por causa desta implementação, existem onze entidades no sistema que herdam de Foo, com seus respectivos repositórios e serviços. Esta implementação causou impacto direto no código, que possui n switchs que definem qual entidade deva ser utilizada. Os cases possuem o mesmo código, com exceção dos repositórios e serviços utilizados.
O refactor do banco de dados e das entidades atualmente não é uma opção.
Diante deste cenário, qual seria a melhor abordagem para lidar com esta situação? O código realizado até o momento não deverá ser alterado, mas existe um esforço muito grande para criar novas funcionalidades que dependam dessa arquitetura de N tabelas e N entidades que deveriam representar apenas uma. Existe algum design pattern que possa facilitar este trabalho?
A arquitetura do projeto está em Onion com camada de apresentação MVC.
A camada MVC acessa os services que por sua vez encapsulam a regra de negócio do sistema. Um problema comum dessa implementação é que sempre que algo envolve essas entidades e tabelas, um switch precisa ser feito para definir-se qual serviço será chamado para comunicar-se com o banco de dados.
public class FooService{
    private service1;
    private service2;
    //demais services das entidades

    //construtor

    public void Inserir(Entidade foo)
    {
        switch(bar.TipoItem)
        {
            case(TipoItemEnum.Tabela1):
                service1.RealizarAlgumProcesso(foo);
                break;
            case(TipoItemEnum.Tabela2):
                service2.RealizarAlgumProcesso(foo);
                break;
            //demais cases para os demais services.
        }
    }
}

Comment: Todos os Services também também implementam uma mesma interface?
Comment: Te aconselho a deixar este fato bem explicito na sua questão, e dê nomes diferentes ao método de cada service, acredito que outros tiveram este mesmo intendimento, pois as respostas estão seguindo esta linha de raciocinio.
Comment: @Vinícius, tudo bem, as interfaces são diferentes, mas, os atributos e metodos possuem diferentes assinaturas? Ou poderia ser encapsulados em um subsistema e deixar o polimorfismo fazer o resto através de uma fachada (facade)?
Comment: @Vinicius, pra escolher pense no longo prazo. Sugeri isso (facade) porque você falou que não é possivel refatorar, mas, o trabalho de concentrar a complexidade de criação de objetos no seu cenário acho que deveria ser feito com uma Factory. Se os metodos e atributos são claramente similares, é muito provavel que seja fácil a refatoração incluindo um interface e fazendo com que os serviços herdem dela, dependendo da similaridade, você fazia apenas uma limpeza nos switchs espalhados e a factory faz o resto. Fazer o service vai ter o mesmo efeito da Fachada, mas, a fachada é um padrão de projeto.
Comment: Qual versão do .Net está o projeto?
Comment: A primeira vista, me parece um caso para uma Factory, poderia nos dar mais informações?
Comment: está utilizando MVC 4. @Intruso, poderia especificar quais informações você gostaria de saber?
Comment: Cada service implementa uma interface diferente, @TobyMosque
Comment: O services implementam uma interface comum?
Comment: Conforme dito a @TobyMosque, os services implementam interfaces diferentes.
Comment: Estes serviços estão em uma biblioteca local ou são web Services (eg: WCF)? Existe a possibilidade de todos os serviços implementarem uma interface em.comum? Ou realmente são procedimentos muito distintos para cada entidade?
Comment: @TobyMosque, os procedimentos são semelhantes sim, com poucas mudanças na regra de negócio, contudo, devido ao fato de existir 12 tabelas e 12 entidades, todo o sistema foi projetado como se estas funcionalidades fossem separadas.
Comment: Concordo com o @Intruso que isso pode ter cara de **Facade**, apesar de ter um _Bad Smell_ pedindo refatoração... :) Segue um link legal sobre o padrão: http://www.dofactory.com/net/facade-design-pattern
Comment: @Intruso, os atributos variam pouco e os métodos poderiam ser comum. Infelizmente, hoje não está assim, mas para as funcionalidades que virão pode ser feito. A fachada parece ser uma boa ideia, embora essa abordagem fuja da arquitetura Onion. Criar uma fachada não seria semelhante a criar um service em comum para todas estas tabelas?
Answer: Sim. O nome dela é Helper, que é uma variação do Utility.
Como os métodos são muito parecidos, você pode centralizar a lógica comum de negócios dentro do Helper e chamar apenas um método só que faz tudo.
Coloque por favor exemplos de lógica de negócios na pergunta que eu coloco na resposta como refatorar sua lógica para um Helper.

Camada de Serviços
Supondo seu exemplo, posso reimplementar um Service usando uma abordagem genérica. Por exemplo:
public class ClasseService<T>
    where T: Foo
{
    public void RealizarAlgumProcesso(T objeto)
    {
        ...
    }
}

Verificações específicas do tipo derivado podem ser feitas da seguinte forma:
if (obj.GetType() == typeof(Foo1)) { ... }

Sei que ainda não é o adequado, mas é um ponto de partida.
Comment: Pergunta editada, cigano.
Answer: No .Net 4.0 temos a opção do dynamic, eu não recomendaria o uso levianamente, mas na sua situação pode vir a calhar.
Crie uma factory que receba como parâmetro o tipo de tabela e devolva o serviço correspondente, para evitar refatorar o código e criar uma(s) interfaces e programar polimorficamente você pode usar o dynamic e invocar em runtime o método. O contraponto é performance e perda do intellisense.
Isso só vai funcionar se todos os serviços tem o mesmo nome de métodos.
Ex:
    public static class MyFactory
    {
        public static dynamic GetService(TableType type)
        {
            switch (type)
            {
                case TableType.Table1:
                    return new Service1();
                case TableType.Table2:
                    return new Service2();
                case TableType.Table3:
                    return new Service3();
                default:
                    return null;
            }
        }
    }

    public enum TableType
    {
        Table1,
        Table2,
        Table3,
    }

public class Service1 { public int Xpto(int i) { return i; } }
public class Service2 { public double Xpto(double d) { return d; } }
public class Service3 { public string Xpto(string s) { return s; } }

Uso com retorno e parametros distintos:
var service = MyFactory.GetService(TableType.Table1);
Console.WriteLine(service.Xpto(1));

service = MyFactory.GetService(TableType.Table2);
Console.WriteLine(service.Xpto(4.0));

service = MyFactory.GetService(TableType.Table3);
Console.WriteLine(service.Xpto("Xpto"));

Answer: A arquitetura dos serviços deve seguir a mesma arquitetura das entidades e para isso você deve utilizar o polimorfismo dos seus objetos de serviço e encapsular somente aquilo que cada um precisa. No exemplo dado, uma implementação mais flexível seria criar uma interface genérica que contenha o método a ser utilizado e criar um serviço para cada tipo de entidade que implemente essa interface. Será necessário para isso uma classe seletora, que é aquela que terá somente a lógica do que está no switch. Dessa forma todo código estará com o encapsulamento devido. Segue a refatoração do exemplo que você postou:
public class FooService
{
    public void Inserir(object foo)
    {
        IService insertService = InsertServiceSelector.GetService(foo);
        insertService.RealizarAlgumProcesso(foo);
    }
}

interface IService
{
    void RealizarAlgumProcesso(object foo);
}

class StringService : IService
{
    public void RealizarAlgumProcesso(object foo)
    {
        string bar = (string) foo;
        /* ...Serviço para Strings... */
    }
}

class IntegerService : IService
{
    public void RealizarAlgumProcesso(object foo)
    {
        int bar = (int) foo;
        /* ...Serviço para inteiros.. */
    }
}

class InsertServiceSelector
{
    public static IService GetService(object foo)
    {
        if(foo is string)
            return new StringService();

        if (foo is int)
            return new IntegerService();

        /*... A lógica de seleção fica encapsulada...*/

    }
}


preventing Rails hitting database so many times

Question: This below method hits the database when saving an account, when saving a user, when updating the unit with the account id, when create a new unit_users record (associating unit with a user). So that's at least 4 times it hits the database:
def activate_new_account(assign_units = [])
    account = Account.new(
                          :name             => self.name,
                          :email            => self.email,
                          :phone            => self.phone,
                          :street_address   => self.street_address,
                          :city             => self.city,
                          :state            => self.state,
                          :postal_code      => self.postal_code,
                          :country          => self.country)
    errors.clear

    error_msgs = []

    transaction do
      if account.valid?
        account.save

        user  = User.new(:name                  => self.name,
                         :email                 => self.email,
                         :password              => self.password,
                         :password_confirmation => self.password_confirmation,
                         :phone                 => self.phone,
                         :address               => formatted_address,
                         :role_id               => self.user_role_id,
                         :account_id            => account.id)

        if user.valid?
          user.save

          if units_for_account
            begin
              units = Unit.find(units_for_account.split(" "))
              units.each do |unit|
                #hitting database twice
                unit.update_attributes account_id: account.id
                unit.users << user
              end

            rescue ActiveRecord::RecordNotFound
              error_msgs << "Couldn't find all Units with serial numbers: #{units_for_account.split(' ')}"
            rescue ActiveRecord::RecordInvalid => invalid
              error_msgs << invalid.record.errors
            end
          end

        else
          account.destroy
          error_msgs << user.errors.full_messages
        end
      else
        error_msgs << account.errors.full_messages
      end
    end

    if error_msgs.size > 0
      error_msgs.each do |error|
        errors.add :base, error
      end
      return false
    end

    return true
end

Is there a more Railsy way to do this without hitting database so much?
Answer: There is a much more Rails way to accomplish the activation, by using validates_associated.
But it does'n access the database less. You have four tables to update or add rows, so you need four DB statements.


Create a grouped bar chart from a list of lists in Python

Question: When I pass a simple list to ax.bar(), it plots it just fine.  But I have a several lists within a list.  This is greatly simplified, but something like:
data = [[5,10], [7,11], [3,9]]

What I would like to do is plot a grouped bar graph so that at 0 on the x-axis I have two vertical bars, one going to 5, the other to 10. At x=1 I'd have two bars going to 7 and 11, x=2 has two bars going to 3 and 9.
My question is, is there any simple way to pass in just data?  Or do I need to extract out two new lists from the master and then plot those as follows:
data_a = [5,7,3]
data_b = [10,11,9]

ax.bar(3, data_a, tick_label=range(3))
ax.bar(3, data_b, tick_label=range(3))

Answer: There's no built-in function for that. If you are open to other packages, you can use Pandas:
import pandas as pd
pd.DataFrame(data).plot.bar()

Output:

Or you need to draw them separately as you pointed out.


How do I efficiently map transformations over a pandas DataFrame

Question: a bit of a funny ask.
I have a (big) table that looks like:

transaction_date (index)
store_id
department_id
gross_revenue

'2020-01-01'
Store1
Fruit
$7.50

'2020-01-01'
Store2
Fruit
$2.75

'2020-01-01'
Store1
Veg
$47.50

'2020-01-01'
Store2
Veg
$8.25

...
...
...
...

And I want to transform the gross_revenue column depending on the value of store_id and department_id.
For argument sake, let's say I want to increase all Store1 sales by 25%, increase Veg sales by 10%, and Fruit sales by 75% (let's not worry about the order just yet).
I'd like the user to be able to write:
modifiers = {
    'store_id': {
        'Store1': lambda x: x*1.25
     },
    'department_id: {
        'Veg' : lambda x: x*1.10,
        'Fruit': lambda x: x*1.75
    }
}

Is there a performant way to execute this in Pandas?
As a baseline, this code works:
from functools import reduce

ans = (table
 .assign(gross_revenue = lambda x: x
     .apply(lambda row: reduce(lambda x, f: f(x), [row['gross_revenue'],
                                                   modifiers.get(row['business_id'], lambda x: x),
                                                   modifiers.get(row['department_description'], lambda x: x)
                                                  ]), axis=1)
    )
)

However, it takes close to 2min (table is 5-10m rows).
Does anyone know a faster approach?
Thanks in advance.
Comment: How many transformations do you have?
Answer: Use map:
store_adjust = {'Store1': 1.25, 'Store10':1.3}
dep_adjust = {'Veg': 1.10, 'Fruit':1.75}

df['gross_revenue'] *= ( df['store_id'].map(store_adjust).fillna(1) *
                         df['department_id'].map(dep_adjust).fillna(1) )


Making taxonomy dropdown on the basis of previously selected dropdown of two different taxonomies?

Question: I have two different taxonomies
Taxonomy 1:
Category
-music
-football

Taxonomy 2:
Sub-category
-Jazz
-Rock
-Fifa
-Russian Open

I have linked Jazz, Rock to music and
Fifa, Russian Open to football by term-reference field.
I have content type event, having term-reference to both Category and Sub-category. I want drop-down for sub-category should be populated after selection of Category.
Eg. if we select music as category then in sub-category only jazz and rock should be shown.
Answer: I think you will have to go for some custom code if you want to use seperate taxonomy vocabularies.
An easier way would be to have all terms in the same hierarchical vocabulary and use Hierarchical Select to create the "populate dropdown"-feature.
Answer: Use Hierarchical Select, where you can display category and subcategory in a tree structure. Then use JavaScript to handle the drop down menu. You can get the taxonomy id of parent from the first drop down using jQuery. Then create an Ajax request to get all the child terms. taxonomy_get_children(); function can be used to find all child terms.
You can refer the following code to get better understanding.
(function ($) {
 Drupal.behaviors.custom_filter = {
  attach: function (context) {
    $('#selelctid1').change(function() {
      var id = $(this).val();
        $.ajax({ url: Drupal.settings.basePath + 'yourmenu/' + id,
          async:false,
          success : function(msg) {
            $('#selelctid2').html(msg);
          }
        });
    });
  }
 };
})(jQuery);

Then create a new menu under hook_menu
function mymodule_menu() {
  $items = array();
  $items['yourmenu/%'] = array(
    'page callback' => 'mymodule_get_child_terms',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );
return $items;
}

Create callback function
function mymodule_get_child_terms() {
  $tid = arg(1);
  $taxonomy = taxonomy_term_load($tid);
  $vid = $taxonomy->vid;
  $children = taxonomy_get_children($tid, $vid);
  print '<option value="All">- Any -</option>';
  foreach ($children as $key => $value) {
    print '<option value="' . $value->tid . '">' . $value->name . '</option>';
  }
}


PyInstaller stops working when I import something from PySide

Question: When I build a simple hello world application with PyInstaller, it works as expected. But as soon as I import something from PySide it stops working. Here is the main.py:
from PySide.QtGui import QApplication
print "Hello World"

The build process goes smoothly, but the resulting binary doesn't work:
(pyside) C:\Test\pyinstaller>main\dist\main\main.exe
Traceback (most recent call last):
  File "<string>", line 5, in <module>
  File "C:\Test\pyinstaller\PyInstaller\loader\iu.py", line 386, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "C:\Test\pyinstaller\PyInstaller\loader\iu.py", line 480, in doimport
    exec co in mod.__dict__
  File "C:\Test\pyinstaller\main\build\pyi.win32\main\out00-PYZ.pyz\PySide", lin
e 55, in <module>
  File "C:\Test\pyinstaller\main\build\pyi.win32\main\out00-PYZ.pyz\PySide", lin
e 11, in _setupQtDirectories
  File "C:\Test\pyinstaller\main\build\pyi.win32\main\out00-PYZ.pyz\PySide._util
s", line 87, in get_pyside_dir
  File "C:\Test\pyinstaller\main\build\pyi.win32\main\out00-PYZ.pyz\PySide._util
s", line 83, in _get_win32_case_sensitive_name
  File "C:\Test\pyinstaller\main\build\pyi.win32\main\out00-PYZ.pyz\PySide._util
s", line 58, in _get_win32_short_name
WindowsError: [Error 123] The filename, directory name, or volume label syntax i
s incorrect.

Notice that this happens even though I'm just importing a PySide module, not actually using it. What should I do?
I am using PyInstaller 2.0 to package an app with PySide 1.2 on 64-bit windows 7. My Python installation is 32-bit:
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
>pip freeze
pyside==1.2.0
pywin32==218

And here is the build message:
(pyside) C:\Test\pyinstaller>python pyinstaller.py ..\main.py
90 INFO: wrote C:\Test\pyinstaller\main\main.spec
113 INFO: Testing for ability to set icons, version resources...
162 INFO: ... resource update available
204 INFO: UPX is available.
1237 INFO: checking Analysis
1237 INFO: building Analysis because out00-Analysis.toc non existent
1238 INFO: running Analysis out00-Analysis.toc
1240 INFO: Adding Microsoft.VC90.CRT to dependent assemblies of final executable

1313 INFO: Searching for assembly x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21
022.8_none ...
1314 INFO: Found manifest C:\Windows\WinSxS\Manifests\x86_microsoft.vc90.crt_1fc
8b3b9a1e18e3b_9.0.21022.8_none_bcb86ed6ac711f91.manifest
1316 INFO: Searching for file msvcr90.dll
1317 INFO: Found file C:\Windows\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_
9.0.21022.8_none_bcb86ed6ac711f91\msvcr90.dll
1317 INFO: Searching for file msvcp90.dll
1319 INFO: Found file C:\Windows\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_
9.0.21022.8_none_bcb86ed6ac711f91\msvcp90.dll
1319 INFO: Searching for file msvcm90.dll
1319 INFO: Found file C:\Windows\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_
9.0.21022.8_none_bcb86ed6ac711f91\msvcm90.dll
1447 INFO: Analyzing C:\Test\pyinstaller\support\_pyi_bootstrap.py
2601 INFO: Analyzing C:\Test\pyinstaller\PyInstaller\loader\archive.py
2687 INFO: Analyzing C:\Test\pyinstaller\PyInstaller\loader\carchive.py
2776 INFO: Analyzing C:\Test\pyinstaller\PyInstaller\loader\iu.py
2800 INFO: Analyzing ..\main.py
2893 INFO: Hidden import 'encodings' has been found otherwise
2894 INFO: Looking for run-time hooks
2895 INFO: Analyzing rthook C:\Test\pyinstaller\support/rthooks/pyi_rth_encoding
s.py
7438 INFO: Warnings written to C:\Test\pyinstaller\main\build\pyi.win32\main\war
nmain.txt
7444 INFO: checking PYZ
7445 INFO: rebuilding out00-PYZ.toc because out00-PYZ.pyz is missing
7445 INFO: building PYZ out00-PYZ.toc
8059 INFO: checking PKG
8060 INFO: rebuilding out00-PKG.toc because out00-PKG.pkg is missing
8061 INFO: building PKG out00-PKG.pkg
8072 INFO: checking EXE
8073 INFO: rebuilding out00-EXE.toc because main.exe missing
8073 INFO: building EXE from out00-EXE.toc
8075 INFO: Appending archive to EXE C:\Test\pyinstaller\main\build\pyi.win32\mai
n\main.exe
8151 INFO: checking COLLECT
8151 INFO: building COLLECT out00-COLLECT.toc

EDIT: This happens even if I call from PySide import QtGui as it suggests in this answer.
Answer: Encountering same question, solved by using PyInstaller 1.5.


Multiple graphs with different color lines and markers

Question: I need to plot multiple graphs with different line colors and markers.
I want number of graphs to be flexible and plot those automatically.
When I give and array of values to matplotlib.pyplot.plot to plot, it plots them with different colors. However, I couldn't find a way to also add markers on those plots.
import matplotlib.pyplot as plt

x_axis = [[252.7, 252.7, 252.7, 252.7, 252.7, 252.7],
       [224.2, 224.2, 224.2, 224.2, 224.2, 224.2],
       [198. , 198. , 198. , 198. , 198. , 198. ],
       [179.2, 179.2, 179.2, 179.2, 179.2, 179.2],
       [148.2, 148.2, 148.2, 148.2, 148.2, 148.2],
       [124.7, 124.7, 124.7, 124.7, 124.7, 124.7],
       [ 97.4,  97.4,  97.4,  97.4,  97.4,  97.4],
       [ 81.3,  81.3,  81.3,  81.3,  81.3,  81.3],
       [ 62.4,  62.4,  62.4,  62.4,  62.4,  62.4]]
y_axis = [[ 98.986099 , 100.165872 ,  99.8226189, 100.563172 , 100.074811 ,
        100.603689 ],
       [ 99.9345974,  99.634039 , 100.126533 ,  99.99223  , 100.264707 ,
        100.165244 ],
       [ 99.97628  , 100.174231 ,  99.991863 ,  99.9305726, 100.114646 ,
        100.006637 ],
       [ 99.8629142, 100.068743 ,  99.7361936, 100.34242  ,  99.9061321,
        100.146376 ],
       [ 99.9580146,  99.9585485, 100.064912 ,  99.9304251, 100.135072 ,
        100.044364 ],
       [ 99.9656089, 100.022012 ,  99.910529 , 100.054065 , 100.194655 ,
         99.9474796],
       [ 99.916351 , 100.05248  , 100.045002 ,  99.8500087, 100.146954 ,
        100.097336 ],
       [ 99.8399431,  99.9708453, 100.040011 ,  99.9784648, 100.05224  ,
        100.262108 ],
       [ 99.9390728, 100.003478 , 100.062155 ,  99.9212035, 100.12125  ,
        100.09437  ]]

plt.plot(x_axis,y_axis)
plt.show()

Plot I get
plt.plot assigns different color to each graph, but the markers are not shown.
I would like to see the markers too, and I want to have different marker styles with the same color as the graphs line
I am new to python, please help!
Comment: Currently your question is highly vague and unclear. To have round markers, you use `plt.plot(x_axis,y_axis, '-bo')`. There is **no data** in your question so no one can run your code. You wrote "I want number of graphs to be flexible" but there is only one graph in your code. Yo haven't included how the final figure should look like. Try including a hand drawn sketch. In short, please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Comment: Found the solution ( plt.plot(x,y,'-o') ), thanks for the tip.
Answer: plt.plot(x, y, '-o')

did the job
Edit:
in the argument '-o', '-' stands for solid line, 'o' stands for circle marker.
Since x and y are arrays, and since there is no specification of color for markers and lines, python plots each graph in different color with solid line and circle marker.


portability of htobe64 and endian.h

Question: I need to put 8 bytes, that I received on an arbitrary machine that my code runs on, in to big endian order. I believe that I can use the htobe64 function for that, but I'm not sure about the portability of that - i.e. the availability of endian.h - across different machines architectures and operating systems when compiling my code. Is this a safe i.e portable method to use or is it better to use a different approach?
Answer: Please use the following, portable approach:
#include <stdint.h>

void write64be(unsigned char out[8], uint64_t in)
{
    out[0] = in >> 56 & 0xff;
    out[1] = in >> 48 & 0xff;
    out[2] = in >> 40 & 0xff;
    out[3] = in >> 32 & 0xff;
    out[4] = in >> 24 & 0xff;
    out[5] = in >> 16 & 0xff;
    out[6] = in >>  8 & 0xff;
    out[7] = in >>  0 & 0xff;
}

Comment: @user4416936 `endian.h` is not portable and it's generally a bad idea to keep "endianed" numbers in numeric variables. Use a bunch of functions like the function above.
Comment: Ok thanks, that solves my issue; yet, what if I need to swap different byte sequences in the future? Would I end up including several functions like this? I guess my question is essentially about the portability of `endian.h` itself.

portability of htobe64 and endian.h


store payment gateway response on quote and persist to order

Question: I am writing a magento module for a gateway that authorizes loans as a payment system.
Since there is a relatively high probability the customer will get declined, I chose to implement this using getCheckoutRedirectURL() (placing the loan steps before 'place order' in the checkout flow) so that in the failure case, I can easily return the customer to the payment choice page.
I then do the gateway API call in my redirectAction in my controller.
As a result, I get a URL to open in a lightbox to take the customer through the loan process, as well as some id's from the loan gateway.
I would like to store these additional id's as part of the quote and later copy them to the order when I convert the quote to an order (I did the conversion similar to google checkout - based on a callback from the loan gateway).
However, I cannot figure out how to persist data on the quote.
The obvious way:
$quote->setCustId($custId);
$quote->save();

doesn't work; the additional data does not get stored in the database and hence is not available in the postback handler to convert quote to order.
The same happens for
$quote->setData('custId', $custId);
$quote->save();

(and I assume this is just a more explicit form of the first in the sense that it doesn't use the magic setter/getter)
I've seen references to setAdditionalData (for example, here) but that looks to be available only on payment objects, which I don't think I have yet on the quote (although I could be wrong ?)
Is there any way to store some fields on an order in the database without having to actually add database fields for them ?
Answer: You will need to add actual columns to sales_flat_quote table to store extra variables in quote object.
Since the stuff you are making is related to payment method instead I'd suggest you to store those variables in additional_information dataset that is stored to sales_flat_quote_payment table as serialised php array and payment methods can set data to this variable as follows:
$quote->getPayment()->getInfoInstance()->setAdditionalInformation($key, $value);
$order->getPayment()->getInfoInstance()->setAdditionalInformation($key, $value);

see more from app/code/core/Mage/Payment/Model/Info.php
the only downside for this is that it is stored as serialised array at the end which means no direct sql access later if you somehow need to depend on this data, offer filters and such.


Comportamento Blameable não funciona no Symfony2

Question: Estou a implementar em Symfony2 o comportamento Blameable utilizando o Gedmo\Mapping\Annotation. Consegui implementar satisfatoriamente o Timestampable, mas não consigo implementar o Blameable. O problema em questão é que não consigo obter o utilizador. Tentei reescrever o método do listener que traz o Gedmo, mas ele não consegue aceder ao user.
Em relação a minha config:
extension.listener:
    class: Basepoint\SruBundle\Listener\DoctrineExtensionListener
    calls:
        - [ setContainer, [ @service_container ] ]
    tags:
        # translatable sets locale after router processing
        - { name: kernel.event_listener, event: kernel.request, method: onLateKernelRequest, priority: -10 }
        # loggable hooks user username if one is in security context
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

gedmo.listener.tree:
    class: Gedmo\Tree\TreeListener
    tags:
        - { name: doctrine.event_subscriber, connection: default }
    calls:
        - [ setAnnotationReader, [ @annotation_reader ] ]

gedmo.listener.translatable:
    class: Gedmo\Translatable\TranslatableListener
    tags:
        - { name: doctrine.event_subscriber, connection: default }
    calls:
        - [ setAnnotationReader, [ @annotation_reader ] ]
        - [ setDefaultLocale, [ %locale% ] ]
        - [ setTranslationFallback, [ false ] ]

gedmo.listener.timestampable:
    class: Gedmo\Timestampable\TimestampableListener
    tags:
        - { name: doctrine.event_subscriber, connection: default }
    calls:
        - [ setAnnotationReader, [ @annotation_reader ] ]

gedmo.listener.sluggable:
    class: Gedmo\Sluggable\SluggableListener
    tags:
        - { name: doctrine.event_subscriber, connection: default }
    calls:
        - [ setAnnotationReader, [ @annotation_reader ] ]

gedmo.listener.sortable:
    class: Gedmo\Sortable\SortableListener
    tags:
        - { name: doctrine.event_subscriber, connection: default }
    calls:
        - [ setAnnotationReader, [ @annotation_reader ] ]

gedmo.listener.loggable:
    class: Gedmo\Loggable\LoggableListener
    tags:
        - { name: doctrine.event_subscriber, connection: default }
    calls:
        - [ setAnnotationReader, [ @annotation_reader ] ]
gedmo.listener.blameable:
    class: Gedmo\Blameable\BlameableListener
    tags:
        - { name: doctrine.event_subscriber, connection: default }
    calls:
        - [ setAnnotationReader, [ @annotation_reader ] ]

Classe:
use Gedmo\Mapping\Annotation as Gedmo; // gedmo annotations
use Doctrine\ORM\Mapping as ORM;

// ...

    /**
     * @var string $createdBy
     *
     * @Gedmo\Blameable(on="create")
     * @ORM\Column(type="string")
     */
    private $createdBy;

    /**
     * @var string $updatedBy
     *
     * @Gedmo\Blameable(on="update")
     * @ORM\Column(type="string")
     */
    private $updatedBy;

// ...

O Timestampable está a funcionar corretamente.
Qual pode ser o meu problema?
Comment: Você está com um usuário logado no momento? Pelo que eu vi na documentação, o próprio Doctrine já tenta, automaticamente, atribuir um usuário aos atributos $createdBy e $updatedBy, independente do atributo ser uma string ou uma referência.
Answer: Descripción: DoctrineExtensions Listener
Agregar en DoctrineExtensionListener:
file: src/Xxxx/XxxBundle/Listener/DoctrineExtensionListener.php
namespace Xxxx\XxxBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class DoctrineExtensionListener implements ContainerAwareInterface
{
...
   public function onLateKernelRequest(GetResponseEvent $event)
   {
...
   }

   public function onKernelRequest(GetResponseEvent $event)
   {
        $securityContext = $this->container->get('security.context', ContainerInterface::NULL_ON_INVALID_REFERENCE);
        if (null !== $securityContext && null !== $securityContext->getToken() && $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
            $blameable = $this->container->get('gedmo.listener.blameable');
            $blameable->setUserValue($securityContext->getToken()->getUser());
        }
    ...
    }
}

Comment: Oi Javier! Bemvindo ao Stackoverflow em Portugês. Pode traduzir a pergunta para PT por favor? Espanhol é off-topic aqui.


How to integrate DexieJs in Angular2

Question: I got this error when I try to run and code related to Dexie.
Unhandled Promise rejection: ReferenceError: require is not defined
        at eval (http://localhost:3001/vendor/traceur/dist/commonjs/traceur.js:5:92)
    Evaluating http://localhost:3001/vendor/traceur/dist/commonjs/traceur.js
    Error loading http://localhost:3001/vendor/traceur/dist/commonjs/traceur.js
    Error loading http://localhost:3001/vendor/dexie/dist/dexie.js as "dexie" from http://localhost:3001/app/pages/portal/portal.js ; Zone: <root> ; Task: Promise.then ; Value: Error: ReferenceError: require is not defined(…)

Just by declaring a Database, I already have the above errors.
// Declare Database

class FriendDatabase extends Dexie {
    friends: Dexie.Table<IFriend,number>;

    constructor() {
        super("FriendDatabase");
        this.version(1).stores({
            friends: "++id,name,age"
        });
    }
}

The convention way of me adding Dexie is in systemjs.config.js(in my case I've used Typescipt)
/** Map relative paths to URLs. */
const map: any = {
  'dexie': 'vendor/dexie/dist',
  'traceur': 'vendor/traceur/dist/commonjs'

};

/** User packages configuration. */
const packages: any = {
  'dexie': { main: 'dexie.js', defaultExtension: 'js'},
  'traceur': { main: 'traceur.js', defaultExtension: 'js'}
};

Edited
My src code can be found here
Edited
Just to be clear. I'm not saying it is dexie's library issue. It could be that I'm not implementing in the right way. Hence, looking for a guide to implement dexie correctly in angular2.
Edited
I found this link, but the solution of adding the below code doesn't work for me
System.register("dexie", [], true, function(require, exports, module) {
  var global = System.global,
      __define = global.define;
 global.define = undefined;
(function (global, factory) {
....

(Work around)
Not what, I'm able to barely get it working is by add dexie via script tag

and then I can work with dexie straightaway.
But the problem to this is that I cannot import dexie and all the typings for dexie is missing.
I try to manual copy dexie.d.ts and reference it, but typescript does not acknowledge, so I would have compilation errors.
Comment: You're telling that you use TS, but both config and error message tell that you use Traceur. Please, elaborate on that. Any way, it seems to do nothing with Dexie library itself, just with SystemJS configuration (which was truncated, by the way).
Comment: The only reason why my config has tracecur is that if I do not include it in my systemjs configuration, it would still request for tracecur anyways and resulted in a 404, as long as I import dexie and define a database as shown in my example. By including tracecur, it resulted to the above error. So hence, I looking for a guide how to integrate Dexie correctly into angular2
Comment: If you use Typescript, you don't need Traceur (unless you absolutely certain that you do). I guess that SystemJS uses Traceur by default, and you haven't configured it properly. The problem isn't related to the library, please, update the question with all the relevant information on how you use SystemJS.
Comment: I've include my [src code](https://github.com/maclarensg/angular2-rails5/tree/master/angular2/src)
Answer: Finally after some googling.
In order to configure Dexie with SystemJS is found in this github link.
Copy the summary here
Install dexie via npm
npm install dexie --save

Update systemjs.config.js as follows:
Add 'dexie': 'node_modules/dexie/dist/dexie.js' to map.
Add 'dexie': { format: 'amd' } to packages.

Also: Make sure your tsconfig file has "moduleResolution": "node".

How to integrate DexieJs in Angular2


estimating confidence interval for same value in a variable

Question: I have data frame named df. I want to calculate confidence interval 0.95  for the variable gp based on res and gender. my expected form of data would be like df1.
df<- data.frame(res = c(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4),
                gender = c(1,1,1,1,2,2,2,2,1,1,1,1,2,2,2,2),
                gp=c(10.1,10.5,11.2,9.8,9.7,8.9,7.6,8.8,6.6,5.5,4.4,4.9,3.2,2.3,4.9,6.8))

expected data=
df1<-

res   gender    upper    lower
1       1
2       1
3       1
4       1
1       2
2       2
3       2
4       2

Answer: Here is a way with aggregate.
ci <- function(x, conf = 0.95){
  lo <- (1 - conf)/2
  up <- 1 - lo
  qq <- qnorm(c(lo, up), mean(x), sd(x))
  c(lower = qq[1], upper = qq[2])
}
agg <- aggregate(gp ~ res + gender, df, ci)
agg <- cbind(agg[-ncol(agg)], agg[[ncol(agg)]])

agg
#  res gender      lower    upper
#1   1      1  3.4993366 13.20066
#2   2      1  1.0704809 14.92952
#3   3      1 -1.6241460 17.22415
#4   4      1  0.5590713 14.14093
#5   1      2 -2.5583749 15.45837
#6   2      2 -3.5469652 14.74697
#7   3      2  2.5080597  9.99194
#8   4      2  5.0281924 10.57181

Edit
Here is a way to call the function ci multiple time, with several confidence levels.
confLevels <- c(0.80, 0.90, 0.95)
lst <- lapply(confLevels, function(x){
  agg <- aggregate(gp ~ res + gender, df, ci, conf = x)
  agg <- cbind(agg[-ncol(agg)], agg[[ncol(agg)]])
  names(agg)[3:4] <- paste(names(agg)[3:4], x, sep = ".")
  agg

})
Reduce(function(x, y) merge(x, y), lst)

Comment: thanks @ Rui Barradas it works. is there any way to add another level of confidence interval such as 0.80 and 0.90 ?


Munin not creating html files in Ubuntu

Question: I installed Munin in a Ubuntu Server 14.04 with Apache 2.4.7
But after all configuration, Munin isn't creating the html files in the html dir. This are my files:
munin.conf
dbdir     /var/lib/munin
htmldir   /var/www/www/munin
logdir    /var/log/munin
rundir    /var/run/munin

# Where to look for the HTML templates
#
tmpldir /etc/munin/templates

[MuninMaster]
    address 127.0.0.1
    use_node_name yes

And my apache.conf
    Alias /munin /var/www/www/munin
<Directory /var/www/www/munin>
        #Order allow,deny
        #Allow from localhost 127.0.0.0/8 ::1
        #Options None
    Require all granted
        Options FollowSymLinks SymLinksIfOwnerMatch
    # This file can be used as a .htaccess file, or a part of your apache
    # config file.
    #
    # For the .htaccess file option to work the munin www directory
    # (/var/cache/munin/www) must have "AllowOverride all" or something
    # close to that set.
    #

    # AuthUserFile /etc/munin/munin-htpasswd
    # AuthName "Munin"
    # AuthType Basic
    # require valid-user

    # This next part requires mod_expires to be enabled.
    #

    # Set the default expiration time for files to 5 minutes 10 seconds from
    # their creation (modification) time.  There are probably new files by
    # that time.
    #

    <IfModule mod_expires.c>
        ExpiresActive On
        ExpiresDefault M310
    </IfModule>

</Directory>

But when i go to myip/munin i have a 403 Forbidden. And looking into /var/www/www/munin theres no files in it. (Before that, i had /var/www/munin but doesn't work anyway).
Any hints?
Comment: Does its user have write access to that location?
Comment: @ceejayoz Yeah. User is the owner. And the permissions of the dir are: drwxr-xr-x
Answer: First, is this a typo: htmldir   /var/www/www/munin
If it is, let's make sure the munin user has access to the directory. To test it:

Make /var/www/munin owned by munin:
$ sudo chown munin: /var/www/munin

Run a job manually and check the output for errors:
$ sudo sudo -u munin /usr/bin/munin-cron --debug 2>&1 | less

Comment: It's not a typo. I found here: http://serverfault.com/a/632633/304356 that he change de htmldir and Munin start to work. So, I change htmldir from /var/www/munin to /var/www/www/munin but still don't work.
Comment: Have you tried changing the owner of `/var/www/munin` and seeing that helps?
Comment: To what user? I tried to delete and create munin user again, but nothing happen.
Comment: Try running the command listed under #2 above. Look for the part where it's generating HTML pages and check for errors.
Comment: Well. Looking to that file i found that de html files are in /opt/munin/www/docs. I don't have any idea why.

Munin not creating html files in Ubuntu


Add custom classes to node links

Question: How can I add custom classes to node links in Drupal 8?
I want to add some classes to the Read more and Add new comment links in article teasers.
Answer: In your theme open file THEMENAME.theme, example in my case THEMENAME is bartik and file is bartik.theme add code below:
<code>/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
  if (isset($variables['links']['node-readmore'])) {
    $variables['links']['node-readmore']['link']['#options']['attributes']['class'][] = 'css-readmore';
  }

  if (isset($variables['links']['comment-add'])) {
    $variables['links']['comment-add']['link']['#options']['attributes']['class'][] = 'css-comment';
  }

}
</code>
Update:
Code above will add css class to any readmore link, to add for article only you can add preprocess and check type is article.
<code>/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function bartik_preprocess_node(&$variables) {
  ...

  if ($variables['teaser'] && $variables['node']->getType() == 'article') {
    $node_type_is_article = &drupal_static('node_type_is_article');
    $node_type_is_article = TRUE;
  }
}

/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
  if ($node_type_is_article = &drupal_static('node_type_is_article')) {
    if (isset($variables['links']['node-readmore'])) {
      $variables['links']['node-readmore']['link']['#options']['attributes']['class'][] = 'css-readmore';
    }

    if (isset($variables['links']['comment-add'])) {
      $variables['links']['comment-add']['link']['#options']['attributes']['class'][] = 'css-comment';
    }
  }
}
</code>
Clear all cache and see result. Here is my result:
Comment: Would this not cause issues for when there are multiple nodes being displayed on a page? You're setting a boolean value into the statics, but that'll apply for every node that gets preprocessed.
Comment: OP referred only to article teasers. This will ad it to all content.
Comment: Hi J. Reynolds, i just update code to add css for node type article only, please check is it ok.
Comment: Bravo, grateful.

Add custom classes to node links


How to check overdispersion of binomial GLMMs, lme4 package

Question: I have the following model
fit1 <- glmer(Res~FA+FB+FC+(1|fsite), family=binomial(), data=DATA)

the result of summary() is:
summary(fit1)
Generalized linear mixed model fit by maximum likelihood
 (Laplace Approximation) ['glmerMod']
 Family: binomial  ( logit )
Formula: Res ~ FA + FB + FC + (1 | fsite)
   Data: DATA

     AIC      BIC   logLik deviance df.resid
   202.3    229.9    -92.1    184.3      150

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.1768 -0.6167 -0.4967  0.6815  2.0132

Random effects:
 Groups Name        Variance Std.Dev.
 fsite  (Intercept) 0        0
Number of obs: 159, groups:  fsite, 28

Fixed effects:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  1.55573    0.55830   2.787 0.005327 **
FA2         -0.11914    0.37344  -0.319 0.749692
FB2         -1.38652    0.39967  -3.469 0.000522 ***
FC2         -0.14976    0.61984  -0.242 0.809076
FC3         -0.06794    0.63171  -0.108 0.914350
FC4         -1.20114    0.61670  -1.948 0.051452 .
FC5         -1.44951    0.62817  -2.308 0.021025 *
FC6         -1.13590    0.65427  -1.736 0.082538 .
---
Signif. codes:  0 ?**?0.001 ?*?0.01 ??0.05 ??0.1 ??1

Correlation of Fixed Effects:
        (Intr) fspcs2    FB2    FC2    FC3    FC4    FC5
FA2     -0.466
FB2     -0.456  0.169
FC2     -0.572 -0.021  0.017
FC3     -0.596  0.050  0.036  0.506
FC4     -0.582 -0.005  0.020  0.519  0.509
FC5     -0.558  0.019 -0.038  0.508  0.500  0.511
FC6     -0.391 -0.101 -0.288  0.485  0.467  0.486  0.492

Why are the variance and Std.Dev of the random effects zero?
How do I check for overdispersion in this model?
What should do if there is overdispersion?
Comment: What kind of numbers are there in `res`? Is it a vector of `1`a & `0`s, or is each entry a count of 'successes' out of multiple trials?
Comment: @RobertLong, note that the `[r]` tag provides syntax highlighting. That's 1 of the reasons I added it. I'm not sure if `[mixed-model]` adds much, given `[lme4]` & `[glmer]`. Maybe I'll try `[glmm]` for both `[mixed-model]` & `[glmer]`, & put `[r]` back for the syntax highlighting.
Comment: @gung ahh - OK I didn't know that, sorry. Personally I'd like to see a search of the [mixed-model] tag find a question like this so maybe one of [glmm] and [lme4] is redundant ? Hmmm
Comment: @RobertLong, I think Ben might prefer the [lme4] tag. I just switched [mm] for [glmm]. Hopefully, that will do it.
Answer:
Why are the variance and Std.Dev of the random effects zero?

Because the marginal variance among sites in your data is less than would be expected from a binomial variable; the variance can't be negative, so it's estimated as zero. The GLMM FAQ discusses this.

How do I check for overdispersion in this model?

This looks like a binary (not just binomial) regression, i.e. your responses are 0/1 (if you had "m out of N" responses where N>1, you either need a two-column response variable of (successes,failures), or you need to specify the weights argument). Therefore, overdispersion is not identifiable (e.g., see here or here). tl;dr, you don't need to worry about it.  If you did have N>1, the previously linked GLMM FAQ gives some guidance ... the overdisp_fun from there can be used; depending on your philosophy of model-building you can use a hypothesis test (e.g. $p<0.05$?) or a rule of thumb (e.g. overdispersion factor > 1.1) to decide whether you should worry about it.

What should do if there is overdispersion?

See previous answer (i.e., don't worry about if you have Bernoulli responses; otherwise, see the FAQ or elsewhere for strategies).

What do I do if the data are unbalanced? (asked in comments)

Unless you have data that are severely unbalanced, or unless the data are structured that you have complete separation (all zeros or all ones for some combinations of predictor variables), GLMMs will handle unbalanced data fine; there's no need for manual adjustment.
Comment: @cww none of that has anything to do with over dispersion.
Comment: Many tanks for the answer.

I am a little confused. In this example, the response variable is 0-1 data. Therefore, the overdispersion doesn't apply here. However, how do I deal with data with unequal number of zeors and ones? How can I evaluate the unequal? If the 80% vs 20% is unequal, how about 60% vs 40?

For proportional data, can I use the 'overdisp_fun' to test overdispersion? Can I say that there is overdispersion when 'p' value is smaller than 0.05?


How can I make JWT more secure?

Question: I am creating JWT based authentication in my application deployed on Wildfly server.

For any request arriving at my server, the request is validated to be having a Basic Auth header. In cases, where I don't get the header, I get the POST request payload with Username and Password. I wrap the request with  HttpServletRequestWrapper and add Basic auth header to it and call another application which returns 200 OK after authenticating with Login module automatically. Also, I have a singleton with a ConcurrentHashMap<String, MyUser> in which I store user logging in and the User object with other user details.

On receiving 200 OK, I create a JWT and return it to the client. The client then sends JWT with each request to the EJB services. I get the Authorization header as Bearer *******. I decode the user from the JWT token, then using the map, I again create Basic Auth header and send request to another application which exposes the services only when the Basic Auth header is found.

My doubts:
a) In 1) above, I am sending POST payload, which I can see in Browser network logs. And, I can plainly see the username and password being sent. Is there something extra that needs to be done to prevent this. Or, this wont be visible to other users? Or, https is the solution?
b) In 2) above, anybody can get my token if they are doing MITM attack or know my credentials as in a).
Then, they can seamlessly get access the services. Can, I add IP address of the requested user and store in the map and while validating JWT, validate the IP as well so I can prevent MITM attacks?
There are other posts on SFO and Okta Developer I visited, and they answered about why and how JWT is insecure. But, I am curious, if I can do anything extra in my case which I am missing?
Comment: SSL should already protect you well from MITM attacks.  As for the JWT, if you _don't_ want anyone to see its contents, then encrypt it on the server.  If you don't mind people seeing it, then don't encrypt.  In either case, the JWT should be tamper-proof.
Comment: If you encrypt the JWT, then theoretically even without SSL no one can read it.  With SSL, an encrypted JWT should be virtually non readable.  And even if they change something, it would fail the checksum check on the server anyway.
Comment: Ok, so I have signed it with a secret key already. I am also unauthorizing changed JWT tokens, but, what if someone gets hold of the correct token, SSL should come into picture there, right?
Comment: TLS will protect you from MITM attacks, and prevent your token from getting stolen in transit. But usually tokens are stolen using XSS. Tokens should never be stored in local storage, instead they should be sent as secured cookies, out of the browsers reach. Thats why other security measures should be implemented as CORS, CSRF, Content Security Policies (CSP). Its the combination of all these implemented security features that prevent all types of attacks that can lead to stolen tokens. And also ofc, always use short lived tokens.
Comment: So, is the SSL the solution for both of my doubts?
Comment: Please review how JWT work.  They are tamper proof.
Comment: I agree and have verified it to be tamper-proof, but I read this link at Okta Developer:

https://developer.okta.com/blog/2018/06/20/what-happens-if-your-jwt-is-stolen

It says that yes JWT being stolen can be a problem. That, anyone can use that JWT (not tampering it), to access the services. What should I do then? Will SSL help?
Comment: SSL only provides encryption across the network.  Once it reaches your browser, the JWT will be decrypted.  In that case, you would need to additionally encrypt the JWT on the server before you send it over SSL.
Comment: Thanks for your replies. I am still in some doubts but some are resolved. I will take it up in my team now. Cheers!
Answer: 1 -> Yes HTTPS is the only solution no matter how much secure you make your APIs without
HTTPS MITM attacks are easy.
2-> With multiple benefits come some tradeoffs, JWT leak or stealing is a real problem, and it is not easy to solve, adding an IP address to JWT is not a good idea as they get to change a lot and you user have to authenticate again.
What you try is a quick JWT expiration in this case user has to authenticate every time the token is expired, now for solving this problem you can use a refresh token, it is not so hard to implement.
wanna get deeper here you go --> https://www.youtube.com/watch?v=DPrhem174Ws&t=1089s
Comment: Yes, Agree. Valid point to mention the variability of IP address. And, I missed that. Silly.
Answer: There are several levers you can pull here to vary the amount of security in your JWT setup.  Consider the following options:

No SSL and no encryption of your JWT.  In this case, your JWT would be visible not only to the user, but also to any man in the middle who is listening (either legitimately or maliciously).  This means that any sensitive information contained within the JWT might be visible to others.  However, the JWT still cannot be hacked, even in this maximally unsecure setup.  The reason for this is that every JWT contains a checksum, which is a hash of the token's content, signed using a key which only the server has.  So even if a MITM or user messes around with your JWT, the server would immediately recognize that the token has been hacked when the checksum fails.
SSL is enabled, but the JWT is not encrypted.  This offers the same protection as above plus it also makes it very unlikely that a MITM could ever get a hold of any JWT going to or fro in transit.  Therefore, sensitive information inside the JWT would only be visible to the recipient.
SSL is enabled, and the token is encrypted.  In this maximally secure setup, no MITM can see the JWT in transit.  Also, once received, the user must decrypt the JWT using some key.  Therefore, even if the JWT ends up in a cookie, in theory it is not a security risk, provided that it can't be decrypted by anyone other than the intended recipient.

Most of the time, we will tend to lean towards option #2, but we will not put sensitive information into the JWT.  There is no need for storing a login password in a JWT, as the token itself can prove authentication.  The JWT is tamper proof, and if someone malicious finds a way to see claims such as the expiry date or username, we generally don't care.
Comment: Thanks for your comments yesterday. I revisited the possibility of SSL in addition to @Toerktumlare comment of having CSRF,CORS and CSP policies as well. However, since it is a servlet application and not spring, it will take some effort to implement.
Comment: Where would the user get the key to decrypt the JWT from?

How can I make JWT more secure?


Lilypond: \transpose syntax for an entire song

Question: I am trying to transpose an entire song from B Flat Major to A Major. There is only one part for a "C" instrument. I have it tagged as "flute", but it could just as easily function with a C Melody saxophone, the melody line for a piano, etc. I have tried placing the command in my song in a number of places, but unless the syntax needs to be changed, there is only one place that I can get this to work:
    }

  \transpose bf a { \flute }

  \score {
  \new Staff \with {
    instrumentName = "Flute"
    midiInstrument = "flute"
  } \flute
  \layout { }
  \midi {
    \tempo 4=80
  }

The code above the first "}" is the music score.
My problem is that the music score gets transposed, but there is also an original non-transposed score that appears below the transposed score. What am I doing wrong? I am using Frescobaldi for entering most of the code.
Comment: I'm a little bit confused with your question. `\transpose bf a { c4 d e f }` should work fine, so I'm assuming this isn't what you're looking for. Are you just trying to transpose a single line and only print that single line?
Answer: Your example produces two scores because that's what it contains.
The first \transpose command is a music expression, so it creates a score with the default clef, time signature, etc.
And the \score creates another score, (of course!) which doesn't specify any transposition, so you don't get any.
Presumably you didn't try the option which does work (I turned it into a complete working input file):
\version "2.18.2"
\include "english.ly"

flute = \relative c'' { bf c d ef f g a bf }

\score {
  \new Staff \with {
    instrumentName = "Flute"
    midiInstrument = "flute"
  }
  \transpose bf a { \flute }
  \layout { }
  \midi {
     \tempo 4=80
  }
}

I don't use Frescobaldi, so I don't know if that won't let you create the correct input for some reason.
Comment: Works fine on Frescobaldi for me!
Comment: Errors:

``Processing `/tmp/frescobaldi-kbdlnaun/tmpufygf22v/my_immortal.ly'
Parsing...
/tmp/frescobaldi-kbdlnaun/tmpufygf22v/my_immortal.ly:66:3: error: syntax error, unexpected MUSIC_FUNCTION

  \transpose bf a { \flute }
/tmp/frescobaldi-kbdlnaun/tmpufygf22v/my_immortal.ly:71:1: error: syntax error, unexpected '}'

}
fatal error: failed files: "/tmp/frescobaldi-kbdlnaun/tmpufygf22v/my_immortal.ly"
Exited with return code 1.``
Comment: The entire score is at http://lilybin.com/sj1qh2/2
Answer: The solution that I found was the following:
    }

flutePart = \new Staff \with {
  instrumentName = "Flute"
  midiInstrument = "flute"
} \flute

\score {
  <<
    \transpose bf a \flutePart
  >>
  \layout { }
  \midi {
    \tempo 4=80
  }
}

I am not sure why that works and other solutions don't, but this solution certainly works for me with Frescobaldi.
Answer: Here's another example:
\score {
  <<
    \new ChordNames {
      \set chordChanges = ##t
      \transpose e c { \harmonies }
    }
    \new PianoStaff {
    <<
        \new Voice = "voice" { \transpose e c { \melody } }
        \new Lyrics \lyricsto "words" \text
        \new Voice = "accordion" { \transpose e c { \harmony } }
    >>
    }
  >>

  \layout {
   #(layout-set-staff-size 16)
   }
  \midi {
    \tempo 4 = 125
  }

}


MongoDB sub-document query limit/skip results?

Question: I have an aggregate query that extracts sub-documents from a database in mongodb:
    [
      {
        $match: {
          username: query.username,
        },
      },
      {
        $project: {
          connections: {
            $filter: {
              input: '$connections',
              as: 'connections',
              cond: {
                $eq: ['$$connections.state', query.state],
              },
            },
          },
        },
      }
    ]

The document schema looks as the following (from typegoose, but fairly self explanatory):
export class Connection {
  @prop({ default: () => new Date() })
  public updated?: Date;

  @prop({ required: true, enum: ConnectionStateEnum })
  public state: ConnectionStateEnum;

  @prop({ required: true })
  public username: string;

  @prop()
  public requestIP?: string;

  @prop()
  public requestBrowserString?: string;
}

@modelOptions({
  schemaOptions: {
    collection: 'connections',
    timestamps: true,
  },
})
export class UserConnections {
  @prop({ default: v1 })
    /* tslint:disable */
  _id: string;
  /* tslint: enable */

  @prop({ unique: true })
  username: string;

  @prop({ required: true })
  lastConnectionActivityWithUsername: string;

  @arrayProp({ items: Connection })
  connections: Connection[];
}

The idea is a user has 1 doc containing their connections, thus the connections attribute is an array of connection objects.
If i add a $skip or $limit to the aggregate query this will not change the result of the query as this limits the qty of docs returned, but as there is a macth on a unique field the doc count will always be 1.
Is it possible to limit/skip the number of connection objects to return from a single doc within the query, or can this only be done post query?
(eg a user has 20 connections, but i only want to return 10 connections from the doc)

Based on the answer below I arrived at mixin slice and filter into a $let aggregation pipeline operator as using slice next $filter failed with an error of:

MongoError: Invalid $project :: caused by :: an expression specification must contain exactly one field, the name of the expression. Found 2 fields in { $filter: { input: "$connections", as: "connections", cond: { $eq: [ "$$connections.state", "requestSentAccepted" ] } }, $slice: [ "$$connections", 0, 20 ] }, while parsing object { connections: { $filter: { input: "$connections", as: "connections", cond: { $eq: [ "$$connections.state", "requestSentAccepted" ] } }, $slice: [ "$$connections", 0, 20 ] }

This worked though:
{
        $project: {
          connections: {
            $let: {
              vars: {
                connections: {
                  $filter: {
                    input: '$connections',
                    as: 'connections',
                    cond: {
                      $eq: ['$$connections.state', query.state],
                    },
                  },
                },
              },
              in: {
                $slice: ['$$connections', offset, limit],
              },
            },
          },
        },
      },

Answer: You could use $slice for that:
...
{
  $project: {
    connections: {
      $slice: [ "$connections", skip, limit ]
    }
  }
}

Comment: This does not seem to work, and complains i cannot add multiple: `      {
        $project: {
          connections: {
            $filter: {
              input: '$connections',
              as: 'connections',
              cond: {
                $eq: ['$$connections.state', query.state],
              },
            },
            $slice: ['$connections', offset, limit],
          },
        },
      },`
Comment: MongoError: Invalid $project :: caused by :: an expression specification must contain exactly one field, the name of the expression. Found 2 fields in { $filter: { input: "$connections", as: "connections", cond: { $eq: [ "$$connections.state", "requestSentAccepted" ] } }, $slice: [ "$$connections", 0, 20 ] }, while parsing object { connections: { $filter: { input: "$connections", as: "connections", cond: { $eq: [ "$$connections.state", "requestSentAccepted" ] } }, $slice: [ "$$connections", 0, 20 ] } }


How to Read data from 2 different Firebase database which are from 2 different projects

Question: Basically i want to access two different databases form two different projects in firebase from one flutter app,
For more info ,
I have build a single Flutter app in which ,
 some time i want to refer to one database of (Project name "A" ) and some time i need to refer another database of (Project name "B") ,
is there a way to refer to 2 different database at a time in single app.
Thanks in advance.
Answer: Yes, it is possible to read data from 2 different Firebase databases through a single app. Simply go to your Home page on your Firebase console and app your app (both iOS and Android, I assume, since you are developing with Flutter) for both databases.


Custom Block Twig: File field how to get direct link to file?

Question: How can I get the direct URL to a file field in twig? I am able to do this for images, but with a file field, it comes up blank.
WORKS
<code>{% set media_img_url = file_url(content.field_background_image.0['#item'].entity.uri.value) %}
</code>
DOESN't WORK
<code>{% set media_file_url = file_url(content.field_cta_file.0['#item'].entity.uri.value) %}
</code>
Comment: Are you sure both structures are the same like that? And is the second field set to display in the given view mode of the content type? It has to not be hidden from display.
Answer: <code>#item</code> is as far as I know only added by the image field formatter, so it's unlikely you'll find it in other field types.
Instead you can use the block content entity to get field values, for example:
<code>{{ elements.content['#block_content'].field_file.0.entity.uri.value }}
</code>
This works independently of field formatters and as commented by @Kevin also when a field is hidden.
Comment: Thanks that did the trick, {% set media_file_url = file_url(elements.content['#block_content'].field_cta_file.0.entity.uri.value) %}   You are a lifesaver!!!
Comment: So this works, but I get a file path of:

public://2018-11/myfile.pdf

where does that folder go off of?
Comment: This is the raw field value of the uri field, use file_url() to transform it to a URL, like you already did successfully in your question.


Heat equation with initial values $U(0,t)=U_1$, $U(L,t)=U_2$,$\forall t$.

Question: My problem is given as
Arbitrary temperatures at ends . If the ends $x=0$
and $x=L$ of the bar in the text are kept at constant
temperatures $U_1$ and $U_2$ respectively, what is the temperature
$u_1(x)$ in the bar after a long time (theoretically,
as $t \to \infty$)? First guess, then calculate.
My guess is that the temperature after a very long time is given as the meadian temperature. Etc
$$u(x,t) \approx (U_2-U_1)/L, \quad \text{as} \quad t\to \infty$$
Now one does assume that the temperature reaches a limit, which is not
unlikely, then the solution will satisfy the laplacian $\nabla^2u=0$.
Which leads to the heat equation in one variable
$$ \frac{\mathrm{d}u}{\mathrm{d}t} = c^2 \frac{\mathrm{d}^2u}{\mathrm{d}x^2} $$
The standard way of assuming the solution is on the form $u(x,t)=X(x)T(t)$ fails for me.Begin with assuimg that the differential equation is equal to some arbitary constant $\lambda$ that is not dependant on $x$ nor $t$. Then I end up with the set of equations
$$\begin{array}{lcr}
T' & = & \lambda c^2 T\\
\ddot{X} & = & \lambda X
\end{array}$$
If we assume for a minute that $\lambda=0$, we end up with
$$X(x) = Ax + B, \qquad T(t)=C$$
Which does not satifsy the initial values. So, what do I do to solve this bugger?
Comment: Please clarify the conditions. The conditions described between in the title and in the question are contradictive.
Comment: How are they wrong in the title? My english is not that good, they are correct in the cursive. Please help me clearify the title =)
Answer: Let $u(x,t)=X(x)T(t)$ ,
Then $X(x)T'(t)=c^2X''(x)T(t)$
$\dfrac{T'(t)}{c^2T(t)}=\dfrac{X''(x)}{X(x)}=-\dfrac{\pi^2s^2}{L^2}$
$\begin{cases}\dfrac{T'(t)}{T(t)}=-\dfrac{\pi^2c^2s^2}{L^2}\\X''(x)+\dfrac{\pi^2s^2}{L^2}X(x)=0\end{cases}$
$\begin{cases}T(t)=c_3(s)e^{-\frac{\pi^2c^2ts^2}{L^2}}\\X(x)=\begin{cases}c_1(s)\sin\dfrac{\pi xs}{L}+c_2(s)\cos\dfrac{\pi xs}{L}&\text{when}~s\neq0\\c_1x+c_2&\text{when}~s=0\end{cases}\end{cases}$
$\therefore u(x,t)=C_1x+C_2+\sum\limits_{s=0}^\infty C_3(s)e^{-\frac{\pi^2c^2ts^2}{L^2}}\sin\dfrac{\pi xs}{L}+\sum\limits_{s=0}^\infty C_4(s)e^{-\frac{\pi^2c^2ts^2}{L^2}}\cos\dfrac{\pi xs}{L}$
$u(0,t)=U_1$ :
$C_2+\sum\limits_{s=0}^\infty C_4(s)e^{-\frac{\pi^2c^2ts^2}{L^2}}=U_1$
$\sum\limits_{s=0}^\infty C_4(s)e^{-\frac{\pi^2c^2ts^2}{L^2}}=U_1-C_2$
$C_4(s)=\begin{cases}U_1-C_2&\text{when}~s=0\\0&\text{when}~s\neq0\end{cases}$
$\therefore u(x,t)=C_1x+C_2+\sum\limits_{s=0}^\infty C_3(s)e^{-\frac{\pi^2c^2ts^2}{L^2}}\sin\dfrac{\pi xs}{L}+U_1-C_2=C_1x+U_1+\sum\limits_{s=1}^\infty C_3(s)e^{-\frac{\pi^2c^2ts^2}{L^2}}\sin\dfrac{\pi xs}{L}$
$u(L,t)=U_2$ :
$C_1L+U_1=U_2$
$C_1=\dfrac{U_2-U_1}{L}$
$\therefore u(x,t)=\dfrac{(U_2-U_1)x}{L}+U_1+\sum\limits_{s=1}^\infty C_3(s)e^{-\frac{\pi^2c^2ts^2}{L^2}}\sin\dfrac{\pi xs}{L}$
Hence $u(x,\infty)=\dfrac{(U_2-U_1)x}{L}+U_1$


What does the MySQL 5.6 error "InnoDB presently supports one FULLTEXT index creation at a time. Try LOCK=SHARED" mean?

Question: In MySQL 5.6.22 (specifically running on Amazon RDS) I once had a fulltext index on a table. I have since dropped that index in favor of using sphinxsearch. There are no more fulltext indexes on any of the tables on the database.
When I try to now perform an online DDL such as adding a tinyint column to a table with LOCK=NONE I get this error:

InnoDB presently supports one FULLTEXT index creation at a time. Try LOCK=SHARED.

But, there are no fulltext indexes anywhere. I've even tried creating a read-replica in Amazon in hopes that the rebuilding of the database would fix that and I get the same error there.
Am I missing something obvious?
SHOW CREATE TABLE:
CREATE TABLE `pages` (
  `ID` char(64) CHARACTER SET latin1 NOT NULL,
  `auto_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `siteID` bigint(20) unsigned NOT NULL,
  `recordingID` char(64) DEFAULT NULL,
  `dateCreated` datetime DEFAULT NULL,
  `ip` char(46) CHARACTER SET latin1 DEFAULT NULL,
  `referrer` text CHARACTER SET latin1,
  `referrer_client` char(50) DEFAULT NULL,
  `referrer_from` char(255) DEFAULT NULL,
  `referrer_type` char(50) DEFAULT NULL,
  `referrer_network` char(50) DEFAULT NULL,
  `referrer_link` char(255) DEFAULT NULL,
  `campaign_source` char(50) DEFAULT NULL,
  `campaign_medium` char(32) DEFAULT NULL,
  `campaign_campaign` char(75) DEFAULT NULL,
  `url` char(255) CHARACTER SET latin1 DEFAULT NULL,
  `keywords` char(100) CHARACTER SET latin1 DEFAULT NULL,
  `source` char(128) CHARACTER SET latin1 DEFAULT NULL,
  `os` char(30) CHARACTER SET latin1 DEFAULT NULL,
  `browser` char(30) CHARACTER SET latin1 DEFAULT NULL,
  `user_agent` char(255) CHARACTER SET latin1 DEFAULT NULL,
  `agentFamily` char(50) DEFAULT NULL,
  `is_phone` tinyint(1) DEFAULT '0',
  `is_tablet` tinyint(1) DEFAULT '0',
  `is_desktop` tinyint(1) DEFAULT '0',
  `tags` char(255) CHARACTER SET latin1 DEFAULT NULL,
  `device` char(65) DEFAULT NULL,
  `last_event_time` datetime DEFAULT NULL,
  `view_width` int(11) DEFAULT NULL,
  `view_height` int(11) DEFAULT NULL,
  `browser_width` int(11) DEFAULT NULL,
  `browser_height` int(11) DEFAULT NULL,
  `optimizely_experiments` char(255) CHARACTER SET latin1 DEFAULT NULL,
  `optimizely_variations` char(255) CHARACTER SET latin1 DEFAULT NULL,
  `is_paid` tinyint(1) DEFAULT '0',
  `typed` tinyint(1) DEFAULT '0',
  `organization` char(255) CHARACTER SET latin1 DEFAULT NULL,
  `country` char(75) CHARACTER SET latin1 DEFAULT NULL,
  `city` char(128) CHARACTER SET latin1 DEFAULT NULL,
  `region` char(10) DEFAULT NULL,
  `regionName` char(64) DEFAULT NULL,
  `country_code2` char(2) CHARACTER SET latin1 DEFAULT NULL,
  `postal` char(32) CHARACTER SET latin1 DEFAULT NULL,
  `latitude` char(30) DEFAULT NULL,
  `longitude` char(30) DEFAULT NULL,
  `custom_data` text CHARACTER SET latin1,
  `notes` text CHARACTER SET latin1,
  `title` char(255) DEFAULT NULL,
  `has_dom_tree` tinyint(1) DEFAULT '0',
  `time` int(11) DEFAULT NULL,
  PRIMARY KEY (`auto_id`),
  UNIQUE KEY `pageid` (`ID`),
  KEY `siteID` (`siteID`),
  KEY `dateCreated` (`dateCreated`),
  KEY `recordingID` (`recordingID`),
  KEY `siteID_url` (`siteID`,`url`)
) ENGINE=InnoDB AUTO_INCREMENT=90042803 DEFAULT CHARSET=utf8

Simple Alter
ALTER TABLE `pages`
  ADD COLUMN `is_ppc` TINYINT(1) , LOCK=NONE

Error
Error Code: 1846
LOCK=NONE is not supported. Reason: InnoDB presently supports one FULLTEXT index creation at a time. Try LOCK=SHARED.

Comment: Please provide SHOW CREATE TABLE.  Please provide the ALTER that is causing the error message.
Comment: I added them above...
Answer: Found better workaround (solution),
I changed the table engine from InnoDB to MyISAM i.e.
ALTER TABLE `tablename` ENGINE='MyISAM';

and then I ran alter table to add fulltext column index:
ALTER TABLE `tablename` ADD FULLTEXT `asset_number` (`asset_number`);

After that, I changed back the table engine to InnoDB.
ALTER TABLE `tablename` ENGINE='InnoDB';

Answer: Here's what I did,
In my case I had 5 full text indexes in the table. And I wanted to run an ALTER query on few of the columns in the table.
First,
Remove the full text indexes from the table.
Second,
Run your ALTER query.
Third,
Just add the full text indexes back again.
Example:
/*FIRST QUERY*/
DROP INDEX fulltext_index1 ON table_name;
DROP INDEX fulltext_index2 ON table_name;

/*SECOND QUERY*/
ALTER TABLE table_name
 CHANGE `price` `price` DECIMAL(10,2) DEFAULT 0.00  NOT NULL;

/*THIRD QUERY*/
ALTER TABLE table_name ADD FULLTEXT fulltext_index1(column_name1);
ALTER TABLE table_name ADD FULLTEXT fulltext_index2(column_name2);

So this way you don't have to remove column or do any extra work to retain data.
But remember, this is only a one time job per table. In my case I never had to drop and add the indexes back again to the table. Thereafter the ALTER queries were running without errors.
Answer: There is no fix.  The two workarounds include:

rebuild the table, or
LOCK = SHARED

-- neither of which meet the criterion of "no locks".
I would recommend filing a report at the MySQL bug tracker. In the meantime, here is a test case that fails for me too:
drop table IF EXISTS so28666643a;
CREATE TABLE so28666643a (ai INT AUTO_INCREMENT PRIMARY KEY,
    txt TEXT NOT NULL ) ENGINE=InnoDB;
ALTER TABLE so28666643a ADD COLUMN x TINYINT, LOCK=NONE;  -- works OK

drop table so28666643a;
CREATE TABLE so28666643a (ai INT AUTO_INCREMENT PRIMARY KEY,
    txt TEXT NOT NULL ) ENGINE=InnoDB; -- same
ALTER TABLE so28666643a ADD FULLTEXT(txt);
ALTER TABLE so28666643a DROP INDEX txt;
ALTER TABLE so28666643a ADD COLUMN x TINYINT, LOCK=NONE;  -- fails with strange message:

ERROR 1846 (0A000): LOCK=NONE is not supported.
Reason: InnoDB presently supports one FULLTEXT index creation at a time.
Try LOCK=SHARED.

Edit: thanks for the bug report.
Comment: That bug report says "Fixed as of .. 5.6.26, 5.7.8".


are dot net exceptions dependent on computer's locale

Question: this is a bit of newbie question.  if i'm running my dot net application on a server configured for english location, the dot net exceptions have english text.  what happens when the server is configured for a different locale: such as french or russian?
Answer: The text is localized.
Don't depend on the text. If you find a situation where you want to, it's probably an IOException, and using reflection to get the HResult is reliable.


Spline terminology

Question: I am reading up on splines and as a beginner I have a basic question -
Does it make sense to say - "I will fit a cubic b-spline to the data". As b-spline is just a representation of spline in terms of its bases. I think, a more accurate statement will be - "I will fit a natural/not-a-knot/clamped/etc. cubic spline to the data and present results in terms of its basis."
My question arises out of my limited understanding of relevant concepts. Could someone please confirm this. Many thanks!
Comment: People talk about Newton interpolating polynomial and Lagrange interpolating polynomial, even though they are the same. When the focus is on algorithm, a different representation of the same mathematical object can make enough difference to be emphasized like that.
Answer: You are correct in thinking that the statement "fit a cubic b-spline" is pretty vague.
A spline is just a piecewise polynomial. As you said, "b-spline" is just a way of representing a spline, using a particular basis. In fact every polynomial spline is a b-spline, because b-spline basis functions can be used to construct a basis for any spline space (i.e. any space of piecewise polynomials).
Instead of just saying "fit a b-spline" it would be more informative to say what type of spline will be used, what properties it has, and what type of algorithm will be used to construct it.
The answers to this question have a bit more information on this topic, and it's all explained very clearly in the book "A Practical Guide to Splines" by Carl deBoor.
Comment: Thank you. I have read a lot of your answers on related topics on this website, you are obviously an expert. Thanks for sharing the knowledge.
Comment: I am not sure I agree with the statement that "every spline is a b-spline". A spline is not necessarily polynomial either. Try to goggle "exponential spline" and you will find that there are other splines that are simply non-polynomial.
Comment: @fang: My guess was that the OP was only considering polynomial splines, since these are the ones used 99% of the time, and cubic splines are certainly polynomial. But, I added the word "polynomial" to further clarify.

Spline terminology