HTML Title is not centered

Question: I am working on HTML code. I need the title of code be in center of page. The title of page (heading) contain 10 words.
The options i am using start the sentence from middle and then move to right. I need the whole .
<!DOCTYPE html>

  <meta charset="utf-8">

      You are one step closer to
the experience of a life time

You see the sentence start at center but moves to right.
can this be fixed somehow.
Comment: Use a validator. Write valid HTML. Don't use tables for layout. Treat absolute positioning as a last resort.
Answer: Your HTML is invalid. There are two reasons:

 tag is deprecated. (Some browsers do support them).
 cannot be a direct descendant to
, it should be . Use the class for the td instead.

Better code would be something like:

.Titleline {
  /* position: absolute;
  left: 50%;
  width: 546px;
  height: 74px;
  */
  font-family: TimesNewRomanPSMT;
  font-size: 35px;
  line-height: 1.06;
  text-align: center;
}

table {
  width: 100%;
}

    You are one step closer to
the experience of a life time

See the updated code in the snippet. Use the class for the  instead and make the
, full width. Also, don't use position unnecessarily.
Comment: Thanks work, this help me fix it. Thanks a lot
Answer: There are a number of problems:

 is deprecated; don't use it.
You have invalid markup;  is not a valid child of
.  and  are the only valid children of
.
You're using position: absolute with left: 50%, which makes your text start with an offset of 50%; it does not centralise it.

I'd recommend adding switching  to , and adding text-align: center to .Titleline in order to centralise it. Keep in mind you've also got a fixed width on your .Titleline, which will need removing. You'll also need to add width: 100% to table so that it takes up the full available width (so that the text can centralise). This can be seen in the following example:

.Titleline {
  font-family: TimesNewRomanPSMT;
  font-size: 35px;
  line-height: 1.06;
  color: #222222;
  text-align: center;
}

table {
  width: 100%;
}

      You are one step closer to
the experience of a life time

The above shows how you can centralise your text in a table, but I'd also recommend not using tables for layouts due to their poor support for smaller screens. I'd recommend making use of something like the
 element to divide up your content instead. For pure text (like your example), you should also make use of the
 tag:

.Titleline {
  font-family: TimesNewRomanPSMT;
  font-size: 35px;
  line-height: 1.06;
  color: #222222;
  text-align: center;
}

You are one step closer to
the experience of a life time

Hope this helps! :)
Comment: *`` is the only valid child of ``* — There's `` as well.
Comment: @Quentin -- Correct. I did know that, so I'm not sure why I didn't mention it. I probably meant that `` is an invalid child, and then got lost in a train of thought. Anyway, I've updated the answer now to correct that :)
Answer:

<!DOCTYPE html>

    <meta charset="utf-8">

                      You are one step closer to
the experience of a life time

Comment: Copied from mine?
Comment: And no explanation. `:)` Great...

HTML Title is not centered


Qual a diferenças entre esses dois modos de salvar informações do formulário?

Question: Estou aprendendo a usar os formulários do django e me foi apresentado duas maneiras de salvar informações de um formulário em um banco de dados. Testei as duas e ambas funcionam com validações, mas não entendi qual a diferença entre uma e outra.
A primeira utiliza funções herdadas da classe models.Model, usando a função "objects.create(**form.cleaned_data)" e passando como parâmetro os campos do formulário.
No exemplo abaixo, instancio a classe ProductForm que herda de 'forms.ModelForm' e utilizo a função 'cleaned_data' para passar como parâmetro.
def product_create_view(request):

    form = ProductForm()

    if request.method == 'POST':
        form = ProductForm(request.POST or None)

        if form.is_valid():
            Product.objects.create(**form.cleaned_data)
            form = ProductForm()

    data = {}
    data['form'] = form

    return render(request, 'products/product_create.html', data)

A segunda maneira invés de usar a funla 'objects.create(**dict)' utiliza o form.save() diretamente.
def product_create_view(request):

    form = ProductForm()

    if request.method == 'POST':
        form = ProductForm(request.POST or None)

        if form.is_valid():
            form.save()
            form = ProductForm()

    data = {}
    data['form'] = form

    return render(request, 'products/product_create.html', data)

Resumidamente, eu gostaria de saber há diferenças entre usar form.save() e usar Product.objects.create(**dict).
Answer: Eu consegui uma resposta no stackoverflow em ingles que sanou a dúvida. A tradução que fiz ficou assim.
Você somente pode usar o form.save() quando a classe do formulário herda de ModelForm. No geral essa é a maneira mais fácil de criar e atualizar dados de um  Model. Note que nesse casos form.save() retorna uma instância salva do objeto, assim você pode escrever product = form.save() e fazer outras operações com o objeto salvo.
Se você criar um formulário que herde somente da classe Form, esse formulário não terá link com nenhum model específico e logo não será possível salvar com form.save(). Deste modo você terá que criar um objeto usando como parâmetros os dados do formulário com a função cleaned_data. Você terá que definir todos os campos do formulário com os mesmos nomes dos campos do Model, o que é bem mais trabalhoso do que usar o ModelForm, onde você pode só listar os parâmetros do Model.
No final não há diferença nos resultados, mas geralmente é preferível usar form.save() herdando de ModelForm, pois é mais legível e mais simples de entender o que está sendo feito.
Comment: Sua resposta não está errada mas não é suficiente, ha muitas situacoes em que `form.save()` não é adequada, exemplos: Imagine que de acordo com a escolha do usuário, antes persistir os dados vc tenha que realizar um calculo ou consultar uma api para atualizar um campo não presente no form.


How do I use CKEditor 5?

Question: It has been told that Drupal 9 comes with CKEditor 5.
How do I use it?
Answer: Drupal core will provide an upgrade path of switching from CKEditor 4 to 5 without data loss. You should be able to switch the editor from 4 to 5 in your text format with an action as simple as changing the editor and saving the text format.
Check for the updates provided in DrupalCon Portland in this video - https://www.youtube.com/watch?v=YwDFCLaQVbY
Comment: thanks for the help, I went inside `/admin/modules` and enabled CkEditor 5 and went inside `/admin/config/content/formats` and re configured, it started working
Comment: is it possible to share the exact documentation provided by drupal, when I type `php c:\MyFiles\composer\composer.phar show -i | find "ckeditor"` I see `drupal/ckeditor                             1.0.1` I don't know how to use it
Comment: @DickensAS - I have added the video link by the company responsible for writing the CKEditor.

How do I use CKEditor 5?


willDisplayCell won't change background color consistent with logic

Question: I've tried just about everything I can think of, googled lots, searched SO, and still can't find the solution. Here's the issue:
I have a custom UITableViewCell with several labels in it. The text varies dynamically, and the background color (of the cell, not the labels) should vary as well. The text changes in the labels work fine. However, the BG color won't change no matter what I do. The only upside is that I don't feel that lonely. This is apparently a mystery even to a few high-rep people. I'm hoping someone here has found a solution (or can point out my mistake).
Here's what I have done:
Put the logic inside cellForRowAtIndexPath. Disappointment.
Googled and SO'd some more, then:
Put the logic inside a willDisplayCell call. Nothing.
Googled more, then:
Put the logic back into cellForRowAtIndexPath. Nada.
Put the logic inside the willDisplayCell call again. No go.
Found a post on SO that suggested putting another view in the custom cell to cover the original background and set it to change with logic. It didn't.
Tried putting the logic back into cellForRowAtIndexPath.
Tried using a switch statement in the logic.
Tried using if, else if, else in the logic.
Several other things I can't remember. Still doesn't work.
Yes, the UItableViewdelegate is set.
Here's the current code, which also doesn't work:
EDIT: Made a slight change in the top if statement to reflect the suggestion by @Adrian below. Unfortunately, it didn't cure the problem.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id<NSFetchedResultsSectionInfo> sectionInfo = [[detailFRC sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
    NSLog(@"There are %lu objects in the frc",(unsigned long)[sectionInfo numberOfObjects]);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell * cell = [tableView dequeueReusableCellWithIdentifier:@"myCustomCell"];
    if (!cell)
    {
        [tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"myCustomCell"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"myCustomCell"];
    }

    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(CustomCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    thisActivity = [detailFRC objectAtIndexPath:indexPath];

    if (self.activityOrCategory == 0)
    {

            if (thisActivity.name == self.detailFocusItem)
            {
            [cell.myBGView setBackgroundColor:Rgb2UIColor(255, 215, 215)]; // Light red
            cell.backgroundView = cell.myBGView;
            }
            else if (thisActivity.name == self.detailBenchmarkItem)
            {
                [cell.myBGView setBackgroundColor:Rgb2UIColor(215, 220, 255)]; // Light blue
            }
            else
            {
                cell.myBGView.backgroundColor = [UIColor whiteColor];
            }
    }

    else if (self.activityOrCategory == 1)

    {
            if (thisActivity.category == self.detailFocusItem)
            {
                cell.myBGView.backgroundColor = Rgb2UIColor(255, 235, 200);
            }
            else if (thisActivity.category == self.detailBenchmarkItem)
            {
                cell.myBGView.backgroundColor = Rgb2UIColor(200, 255, 200);
            }
            else
            {
                cell.myBGView.backgroundColor = [UIColor whiteColor];
            }
    }

    NSLog(@"cell.backgroundColor is %@",cell.backgroundColor);
    NSLog(@"This row says %@",thisActivity.name);
    cell.activityLabel.text = thisActivity.name;
    cell.categoryLabel.text = thisActivity.category;

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat: @"MM/dd/yyyy hh:mm:ss"];

    cell.fromDateLabel.text = [dateFormat stringFromDate:thisActivity.startTime];
    cell.toDateLabel.text = [dateFormat stringFromDate:thisActivity.stopTime];
    }

Many thanks for taking the time to look! All help appreciated, even if it's my stupid mistake.
Answer: I was under the impression that a UITableViewCell has an actual property of backgroundView, I can see you have something called BGView, but I can't see anywhere from your example where the cell property gets set.
So all I can say is that for my examples where I have done this, I always create a UIView and set it's colour, then assign it to the backgroundView property.
I hope  this might be of some help and that I didn't miss you doing that in your example earlier!
//   Effectively draws the cell with a red background
UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 44)];
backView.backgroundColor = [UIColor redColor];
cell.backgroundView = backView;

Thanks
Adrian_H
Comment: I already had a UIView as a property on the custom cell, but you're right in that I hadn't set the cell.backgroundView to it. I just did, but the result is still no change in the bg color.
Comment: Thanks for the feedback, i'm guessing it would then be a tableview property.  My question would be, does it work in the simulator when using iOS 6.1?  My reasoning behind this is that they changed a lot of the styling properties with iOS 7 and I wonder if your efforts are getting un-done by an overall property.
Comment: Haven't ever tried it in iOS 6, so don't know. Maybe someone else here can chime in with an answer on that. Thanx, @adrian!
Comment: Try creating a new view as opposed to setting one already in existence on the generated cell,  I think that might be it
Answer: I never use Rgb2UIColor before, I don't know how it works.
Try the below code, it works on my app:-
inside willDisplayCell
CGFloat nRed=255/255.f;
CGFloat nGreen= 215/255.f;
CGFloat nBlue = 215/255.f;
UIColor * myColor = [UIColor colorWithRed:nRed green:nGreen blue:nBlue alpha:1]; //Light Red

cell.textLabel.backgroundColor = myColor;
cell.detailTextLabel.backgroundColor = myColor;
cell.backgroundColor =myColor;
[cell.backgroundView setBackgroundColor:myColor];

Answer: I hope those who looked at and especially those who took the time to answer this question can have a sense of humor about this:
It turns out that both of the answers graciously contributed above will work (with minor mods). I feel like a bit of a dummy, but the problem I was encountering wasn't with the setting of the background color, it was with the logic itself. Namely, I was using this code in my if statement:
 if (thisActivity.name == self.detailFocusItem)

when, since both the objects in question are NSStrings, it should have been:
 if ([thisActivity.name isEqualToString:self.detailFocusItem])

Thus, control was simply skipping the color-setting code. :/
I really do apologize for taking your time.
OTOH, had it not been for having been forced to take a new look at it as I implemented your suggestions, I don't know how long it might have taken me to see the forest instead of the trees.
You both get upvotes, and I hope you'll be gentle and chalk it up to the inexperience of a nooby enthusiast.
Many thanks for helping!


How to interpret categorical variable in logistic regression with contrast coding

Question: I'm currently having the following regression that I found a bit tricky to explain:
# glm(formula = mask_got_20 ~ Sex + Amount + mask_wearing, family = "binomial",
#    data = clean_data_third)

# Coefficients:
#               Estimate Std. Error z value Pr(>|z|)
# (Intercept)    1.50966    0.27831   5.424 5.82e-08 ***
# Sex1           0.13040    0.17904   0.728 0.466395
# Amount1        0.07623    0.17914   0.426 0.670433
# mask_wearing1  1.02371    0.27780   3.685 0.000229 ***
#  ---
#  Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

exp(coef(r5))
# (Intercept)          Sex1       Amount1 mask_wearing1
#   4.525197      1.139287      1.079214      2.783507

In this regression, I would like to explain the last variable -- mask_wearing, which is a categorical variable recording whether my participants are still wearing a facemask. The DV in this regression is whether the masked confederate receives £20 (1 = yes, 0 = no).
Since my main interest is the intercept, I used contrast coding where the intercept represents the mean of group means, and the parameter represents the difference from the intercept.
How should I compare if I would like to interpret the last variable as: "participants who reported they still wear a facemask regularly are about X times more likely to offer £20 to the masked confederate than participants who no longer wear facemasks."
Should I use the difference of intercept estimate +- the estimate of mask_wearing and then exponentiate it?
Thank you for your help.
Answer: It's best to choose variable coding on arbitrary convenience, then to get any contrast of interest by subtracting predicted log odds (and possibly anti-logging the difference to get an odds ratio).  This readily generalizes to more complex cases where the categorical predictor interacts with a complex function of another predictor such as a spline function to allow nonlinearity.  In the R rms package contrast function you'd do something like this:
f <- lrm(y ~ sex + mask + x, data=d)
contrast(f, list(mask = 'y'), list(mask = 'n'))

Since in this model mask doesn't interact with anything, it doesn't matter what values are assigned to sex and x.  rms sets them to the mode and median, respectively.


If $\lambda, v$ are two measures, is $\{A:v(A)=\lambda(A)\}$ a $\sigma-$algebra?

Question: I was trying to prove that if $\lambda, v:M\to\mathbb{R}$ are two measures where $M$ is the Lebesgue $\sigma-$algebra and $\lambda$ is the Lebesgue measure and $v(I)=\lambda(I)$ for every open interval $I$, then $v=\lambda$.
I think I almost have it If I could prove they're equal on every Borel set.
It is clear that $v(U)=\lambda(U)$ for every open set $U$. In order to conclude that they're equal in Borel sets, I'd like to answer the following question:

Is it true that $\Sigma=\{A\in M:v(A)=\lambda(A)\}$ is a $\sigma-$algebra?

I can't prove that $\Sigma$ is closed under countable unions (well, not even finite unions). If $A_1,A_2\in \Sigma$, should it be $A_1\cup A_2\in\Sigma$?
Comment: The result is false in the generality stated in the title. However, with some modifications, this line of reasoning can be fruitful. You may want to have a look at the $\pi\text{-}\lambda$ theorem and the monotone class theorem.
Comment: Even if $v$ and $\lambda$ are finite measures, $\Sigma=\{A\in M:v(A)=\lambda(A)\}$ is NOT closed under intersection, so it is NOT a $\sigma$-algebra.
Comment: @Ramiro I think you're right when you say $\Sigma$ is not a $\sigma$-algebra always, but in this case it must be true. If the problem states correctly, $v$ must be equal to $\lambda$ and in the end $\Sigma = M$.
Comment: In this particular case, we will prove that $\Sigma=M$  and then conclude that $\Sigma$ is a $\sigma$-algebra, not the other way round.
Answer: Hints:
Note that this is equivalent to asking if the null sets of a measure form a sigma algebra (Consider $v - \lambda$).  The measure of a countable union of null sets is zero.
Comment: Humm... assuming $v$ or $\lambda $ are finite, then we have that $v(A)=\lambda(A)$ iff $(v - \lambda)(A)=0$.  However, it does not mean that for any $E$ measurable, if $E\subseteq A$   then $(v - \lambda)(E)=0$.  So $A$ may not be a null set of $v-\lambda$.

In fact, $\{A \in M : v(A)=\lambda(A)\}$ may not be closed under intersections.
Comment: Even if $v$ and $\lambda$ are POSITIVE finite measures, we have that $v-\lambda$ is just a signed measure. So the question is NOT equivalent to asking if the null sets of (positive) measure form a $\sigma$-algebra.

In fact,  in general, even if $v$ and $\lambda$ are positive finite measures, $\Sigma=\{A\in M:v(A)=\lambda(A)\}$ is NOT a $\sigma-$algebra.
Comment: Oh, to me a measure is always a positive measure.  Of course it may not be true for a signed measure.


FireBase Google

Question: Atualmente eu utilizo o Firebase database da Google, ( e outros componentes como, auth, FCM, etc) para o meu projeto. Gostaria de saber se há como criar rotinas no lado do servidor. Por exemplo: depois de um período de dias a rotina busca pelos usuários de acordo com uma regra de negócio e envia notificações, tudo feito através da rotina. Há algo assim disponibilizado pelo Firebase ?
Comment: Este fórum é em português, você pode perguntar em português ou usar o Stack Overflow em inglês. Leia isso: http://pt.stackoverflow.com/help/how-to-ask
Comment: Pergunta corrigida, obrigado !
Comment: -1 removido, após a correção.
Comment: Acredito que não, já tentei uma época atrás e não tinha como, só se implementaram isto agora.
Answer: Se a dúvida ainda persistir para alguém, a Google disponibiliza criação de crons utilizando o Cloud Functions (Firebase).
Alguns links que explicam o funcionamento do mesmo:
http://firebase.googleblog.com/2017/03/how-to-schedule-cron-jobs-with-cloud.html
https://github.com/firebase/functions-cron
Answer: Você pode criar suas rotinas no lado servidor usando Firebase Database REST API e mandar suas notificações via curl também. Basta criar de acordo com sua regra de negocio
Firebase Database REST API
Comment: Eu li sobre, você sabe se tem como eu deixar um "motor sempre ligado" do lado do servidor que realiza rotinas sozinhas ? Acho que esse era o ponto em que queria chegar.
Comment: Tem sim. você pode usar um cron para agendar sua tarefa e executar seu script no servidor da uma olhada: http://www.infowester.com/linuxcron.php
Comment: De qualquer forma eu teria que ter o meu próprio servidor para fazer os agendamentos das tarefas ? **Firebase** não oferece tal serviço ?
Comment: Sim eu pelo menos faço assim. Nesse caso não sei se o Database do firebase possui esse serviço, mas o Notification sim você pode agendar quando mandar a notificação

FireBase Google


Three.js - Editing faces

Question: I thought I'd ask this here because I can't find any information anywhere (SO or the three.js documentation) - How do you get the average x,y,z coordinates of a specific face? Or at the very least, is there a way to get the x,y,z coordinates of the three vertices that make up a face? And then use those to calculate the average?
So far I have
var fLength = plane.geometry.faces.length;
for (var i = 0; i < fLength; i++) {
    var f = plane.geometry.faces[i];
    //How do I get the x,y,z of the current/i face?
    //Is there a way to move this face?
    //Is there a way to extrude this face? Or do -anything- with it for that matter?
}

Additionally, are there any methods for moving a face apart from moving the vertices? What about extruding faces? I realize it's quite a few questions however the process for all of this seems a little unclear to me...
Answer: Each Three.js Face3 contains properties a, b and c. Those are the indices into the vertex array of the same geometry object. For example, use
v1 = plane.geometry.vertices[f.a];

to get the Vector3 representing the position of the first vertex in the face.
Three.js doesn't offer much convenience methods for modifying the geometry of an existing object. Like the underlying graphics API's, its focus is on quickly composing and displaying a scene of mostly static objects (vertex shader operations aside).
You'll have to manually adjust the individual vertice that make up the faces (and set the correct dirty flags), or even rebuild faces if your modifications effectively modify edges. Depending on your use case, your operation might be simpler to perform using a vertex shader.
The point is, the topic of building and modifying geometry quickly gets pretty hairy. If you need any help there, make sure to ask a specific question, outlining your desired operation on the geometry.
Comment: Thanks a lot! I didn't realize that three.js was mostly intended for static objects - I guess I assumed you could modify geometry like you would in a typical 3d modelling program. I still haven't explored animation in three.js... I'm assuming you can't readily animate geometry without exporting it from blender or another such program?
Comment: Well, depends on what you mean by animating geometry. If you want traditional keyframe/skeleton based animation, a 3d modeller will always be your tool of choice (see http://blog.romanliutikov.com/post/60461559240/rigging-and-skeletal-animation-in-threejs). If you want procedural animation, there is a lot you can do with modifying vertices (http://mrdoob.github.io/three.js/examples/webgl_geometry_dynamic.html) and/or vertex shaders (http://mrdoob.github.io/three.js/examples/#webgl_shaders_ocean2). The best approach depends very much on what you want to do, exactly.

Three.js - Editing faces


Prove that the maximal entries of a positive definite, symmetric, real matrix are on the diagonal

Question:
Prove that the maximal entries of a positive definite, symmetric, real matrix are on the diagonal.
  (Algebra by Artin, Edition 2, chapter 8, problem 2.1)

This is an assignment problem so I don't want a complete solution. I'm not really sure what "maximal" means. Can anyone tell me that?
Comment: Yes, exactly. For example, every nonzero entry in the identity matrix is maximal.
Comment: I presume maximal means largest in absolute value. Can you do it for $2\times2$ matrices?
Comment: @LordSharktheUnknown Why maximal entries? Why plural? Is it because there might be more than one?
Answer: Since the matrix entries are real, "maximal" here just means largest.
I would interpret the question to mean: given a positive definite real matrix $M$, let $m = \max_{i,j} M_{ij}.$ Prove that whenever $M_{ij} = m$, $i=j$.
Comment: Alright. If that's the real problem, I've solved it. Thanks.
Answer: Here is a different proof.
We know that the quadratic form associated with such a matrix is
$$Q(X)=X^TMX=\sum m_{ii}x_i^2+2\sum_{i<j} m_{ij}x_ix_j\tag{1}$$
(where $X$ is the column vector $(x_1,x_2,\cdots x_n)^T$).
Let us assume the contrary, i.e., that there is an absolute maximum occurring off diagonal for a certain  $m_{ij}$ ($i<j$).
Consider the particular $X=(0...0,1,0,...0,-1,0,...)$
where the 'one' occurs at position $i$ and the 'minus one' occurs at position $j$.
Then expression (1) becomes $m_{ii}+m_{jj}-2m_{ij}<0$.
Contradiction with the definite positiveness.


How to create bridge for KVM without link on eth* and give access to internet

Question: i have a task, where i should create br1 without link to eth* and give to this br1 access to internet.
I have CentOS7. I have created the interface br1:
DEVICE=br1
TYPE=Bridge
ONBOOT=yes
BOOTPROTO=static
IPADDR=192.168.1.1
NETMASK=255.255.255.0
NM_CONTROLLED=no

In iptables i have written this:
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -j SNAT --to-source 192.168.122.1

192.168.122.1 for example my main interface, that has access to internet.
My question: it is enough for get access to internet from my virtual machine on KVM, or i need do something else.
Maybe i need some FORWARD rules. Because virbr0 interface working, but my br1 no.
Comment: Please show FORWARD iptables rules.
Comment: No rule. What in the "FORWARD" i should add ?
Comment: Why not just use libvirt's nat network
Comment: because, i have a task, do not use default network of virbr0. i should create bridge
Answer: Use masquerading to assign NAT on Linux server instead SNAT:
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

To allow forwarding packets to the Internet:
iptables -A FORWARD -i br1 -o eth0 -j ACCEPT
iptables -A FORWARD -i virbr0 -o eth0 -j ACCEPT

To allow forwarding packets from the Internet:
iptables -A FORWARD -i eth0 -o br1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth0 -o virbr0 -m state --state RELATED,ESTABLISHED -j ACCEPT

To allow forwarding packets between two virtual networks:
iptables -A FORWARD -i br1 -o virbr0 -j ACCEPT
iptables -A FORWARD -i virbr0 -o br1 -j ACCEPT

Add default deny rule for forwarding other packets. It drops all unwanted connections from internet to your local networks:
iptables -P FORWARD DROP

Don't forget enable forwarding by command:
sysctl -w net.ipv4.conf.all.forwarding=1


Erro ao executar um trigger

Question: Estou com um problema num trigger qué quando eu faço um insert de um registo quero que automaticamente passe um valor que vem por default está 1 para 0 só que está sempre a dar este erro.
Can't update table 'recibos' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Trigger
CREATE TRIGGER actrecibo AFTER INSERT on Recibos
FOR EACH ROW
BEGIN
        UPDATE recibos set is_new = 0 WHERE id = NEW.id;
END

Alguém sabe o procurar de isto acontecer e como posso resolver ?
Comment: De acordo com essa resposta não é permitido fazer isso.

http://stackoverflow.com/questions/11247590/mysql-trigger-set-values-for-new-row-and-update-another-in-the-same-table
Answer: Não entendi o contexto da utilização da Trigger, porém analisando apenas o código percebi o seguinte.
Após o INSERT você está atualizando o campo is_new = 0 do registro que acabou de inserir.
Se for isso você pode tentar assim:
CREATE TRIGGER actrecibo BEFORE INSERT on Recibos
FOR EACH ROW
BEGIN
      SET NEW.is_new = 0;
END

Answer: Creio que com BEFORE você consegue isso.
CREATE TRIGGER actrecibo BEFORE INSERT on Recibos
FOR EACH ROW
BEGIN
      SET NEW.id = ( SELECT MAX(id) FROM Recibos ) + 1
END

Erro ao executar um trigger


Unable to stream video over a websocket to Firefox

Question: I have written some code stream video over a websocket so a sourcebuffer which works in Chrome and Edge.
However, when I run this in Firefox, the video never plays back, just a spinning wheel animation is displayed. When I check the <video> statistics, It reads HAVE_METADATA as the ready state and NETWORK_LOADING as the network state.
The code looks follows:
<!DOCTYPE html>

    <meta charset="utf-8"/>

    <video controls></video>

Comment: do you get error event on video element or source buffer ? what happens when you directly use the video URL as "src" (without media source)
Comment: i don't see the part wheere you call `.endOfStream()` or `.play()`, so it won't start playing.
Comment: No error event. The data is generated on the fly by the server (from an IP stream for example), so there is no URL I can point the video element to.
Comment: Can you create a plnkr http://plnkr.co to demonstrate?
Comment: No, the video is fed from a custom c# server application. All the code (except for the bit that parses the MP4 container) is up there.
Comment: _"No, the video is fed from a custom c# server application"_ You could use an alternative, open source, video source to demonstrate issue , see https://creativecommons.org/about/videos/
Comment: @dandavis It is a continuous stream of video, so there is no end of stream. I am aware there is no play call. I am triggering the playback manually using the video element controls.
Comment: @guest271314, I don't think I understand how that will help me create a plunkr? That page lists media files which I know can be viewed in a  element in Firefox. I am trying to read the video content from a websocket.
Comment: You can create a mock websocket stream response at plnkr to reproduce issue at firefox
Comment: What does `parseMP4` function return? Not certain how to possibly resolve issue if issue cannot be reproduced
Comment: Check this documentation: https://developer.mozilla.org/es/docs/Web/API/MediaSource
Answer: Could not reproduce <video> element not playing at firefox 47.
Merged approaches at Mocking Websocket Message Events to create mock WebSocket events; bufferAll.html demo at Let's Make a Netflix
An Intro to Streaming Media on the Web for MediaSource usage pattern.
Included <progress> and progress event to notify user of media loading status.

<!DOCTYPE html>

    <meta charset="utf-8"/>

    <progress min="0" value="0"></progress>

    <video controls></video>

plnkr http://plnkr.co/edit/RCIqDXTB2BL3lec9bhfz
Comment: After a minute on Firefox 47, I get a spinning circle and nothing happens after that.
Comment: @ManoDestra _"After a minute on Firefox 47, I get a spinning circle and nothing happens after that."_ Did you press play at video controls? Cannot reproduce that effect, here, at firefox 47. `alert()` is called; video plays for full `1:00` length. Are any errors logged at `console`?  Do not believe chrome supports the specific codec at Question `var mime = 'video/mp4; codecs="avc1.4D401E,mp4a.40.2"';`; did you check `console` at plnkr at chrome? Not certain about ie. Note, actual Question is specifically addressing issue at firefox _"Unable to stream video over a websocket to Firefox"_
Comment: On Firefox, it worked after pressing play for a minute, but got a spinner thereafter. Nothing after the first minute. On IE and Chrome, neither worked at all upon pressing play. So, this may well make sense here.
Comment: @ManoDestra Yes, total video duration is one minute `1:00`. See also https://hacks.mozilla.org/2015/07/streaming-media-on-demand-with-media-source-extensions/ , https://w3c.github.io/media-source/ , https://gist.github.com/granoeste/8727308
Comment: And doesn't work at all for me on IE or Chrome. Odd.
Answer: <!DOCTYPE html>

    <meta charset="utf-8"/>

    <progress min="0" value="0"></progress>

    <video controls></video>

Comment: Did you literally copy the code from the earlier answer?


iText DITO - How can I use a fields Data name as a reference in a calculation?

Question: In iText's DITO template designer product, I have one field which has a fairly complex calculation. In another field, I want to use the result of that calculation.
The tooltip says "Identifier used for referencing fields in calculation expressions". So I assumed if I named it blah I can use it in a calculation in another field like this: sum({{blah}},42) (e.g. add 42 to the value of blah). But if I do that I get the error
Unable to resolve reference: "{{blah}}" in node with tag:  and text:

The iText DITO documentation does not elaborate on this feature at all. I'm evaluating iText DITO and there does not seem to be any way to get support while evaluating the product.
Answer: Suppose I have a field with a very complex calculation. In order to reuse the calculation result, I can do the following:

Give a name to this field (in the image below I've chosen name "total")

Insert a calculation to another field (where I want to reuse "total")

Add "total" as the calculation's body:

That's it, now the total value is reused:
Comment: Thank you! I've been in meetings all day and just tried this out before reading your response and could not believe it worked. I assumed I had to use the curly brace syntax because the docs don't explicitly show an example of this. Appreciate the response!
Comment: Strangely, my UI looks slightly different. I do not have a "Name" field at the same level as the calculation. I do have a "Name" field at the whole element level (e.g. at the Rich Text component level). In your example you're getting the numeric value 114399. I can only attach a Name to the Rich Text component which has the *formatted* value $114399. I cannot do any math on it like sum(total,42). My UI looks like the image israelgarcia posted below.
Comment: For more context, I'm using likely the latest version:

iText DITO Editor 2.5.3
Built on January 9, 2023

I believe I can make it work by doing all calculations with the data type number instead of currency in hidden fields and then formatting as currency where needed. I also have to make sure I uncheck "Use thousand separator"!!  It does make it a bit more cumbersome. And I worry now upgrading may break templates if a feature in earlier versions behaves differently.
Answer: I think the documentation you are looking for is at https://kb.itextpdf.com/home/ditokb/latest/manuals/itext-dito-editor/calculations
You have to give the rich text element a name in the properties to be able to reference it on other rich text element and/or calculations.
See image example at https://kb.itextpdf.com/home/ditokb/files/latest/68620314/68620309/1/1660291029000/image2020-5-27_17-56-41.png
Comment: Thanks your exactly right. I missed the blurb at the bottom: "Note that you don't use double curly braces to refer to this named field. the double curly braces are only used to refer to elements in the data sample. "


YouTube link does not give video id

Question: I have tried this but its failing:
$whereIsMyCake = '';

//
// put all the links here
//
$url =  "http://www.youtube.com/embed/more_yougooglelink";

$url =  "http://www.youtube.com/v/..." // works
$url =  "http://www.youtube.com/watch?v=ue1mLnyEd90"; // WORKS
$url =  "http://youtu.be/we_youGoogle_u"; // WORKS

parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
if($my_array_of_vars['v']=='') {
  preg_match(
    "#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#",
    $url,
    $matches);

  $whereIsMyCake = $matches[0];
} else {
  $whereIsMyCake = $my_array_of_vars['v'];
}

echo $whereIsMyCake;

Question: Now youtube.com/embed/videoid is here seems not working, and what if youtube makes new links we have to keep changing our algorithms? for youtube.com/embed/embed.weareruling/embed/embed/googleisboss/findmenow/video id is here ?
Comment: "Gimme teh codes"... What have you tried so far? Because simple `strstr` and `substr` should give you correct result pretty fast, what's the problem?
Answer: You could use a more complete regex, as addressed in this answer: https://stackoverflow.com/a/6556662/921739. That answer also talks about YouTube's oembed service, which you might find useful.
Also, you could use the YouTube API https://developers.google.com/youtube/2.0/developers_guide_php. That way, if the format changes, you're still golden.
As a note to alleviate your concerns about YouTube's URLs changing: Think of all the blogs, websites, and emails that have links to YouTube videos. If the URL format was to change without support for the old format, all of those links would get broken. Google has good reason to change their URLs infrequently. (That's not to say they won't...)

EDIT
Using the code from the SO link I provided, the ID is pulled from the URL in all of the formats you need:
function youtube_id_from_url($url) {
    $pattern =
        '%^# Match any youtube URL
        (?:https?://)?  # Optional scheme. Either http or https
        (?:www\.)?      # Optional www subdomain
        (?:             # Group host alternatives
          youtu\.be/    # Either youtu.be,
        | youtube\.com  # or youtube.com
          (?:           # Group path alternatives
            /embed/     # Either /embed/
          | /v/         # or /v/
          | /watch\?v=  # or /watch\?v=
          )             # End path alternatives.
        )               # End host alternatives.
        ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
        $%x'
        ;
    $result = preg_match($pattern, $url, $matches);
    if (false !== $result) {
        return $matches[1];
    }
    return false;
}

$urls[] = "http://www.youtube.com/embed/ue1mLnyEd90";
$urls[] = "http://www.youtube.com/v/ue1mLnyEd90";
$urls[] = "http://www.youtube.com/watch?v=ue1mLnyEd90";
$urls[] = "http://youtu.be/ue1mLnyEd90";

foreach ($urls as $url) {
    assert(youtube_id_from_url($url) === 'ue1mLnyEd90'); # Passes
}

Comment: Thank you, i was confused which direction to take, i thought i would do it in python, but your logic is fine thank you.

YouTube link does not give video id


Are there any sonatas with only two sections?

Question: In a classical sense, the Sonata is a structure composed of three sections:

exposition,
development, and
recapitulation.

Are there any examples of a Sonata with only two sections?
Comment: It should be noted that the meaning of "sonata" has changed over time.  You do acknowledge this by starting off "in the classical sense," but the actual statement of the question is not limited only to classical sonatas.  Was that an oversight, or would you in fact be satisfied by examples from before or after the classical period (e.g., from the 16th or 21st centuries)?
Answer: Two leading music scholars of our generation, Jim Hepokoski and Warren Darcy, formulated what they call Sonata Theory (note the capital S and T!) to better understand the sonata process.
They list five types of sonatas. The Type 3 Sonata is the sonata that you describe, with exposition, development, and recapitulation. The Type 1 Sonata, however, is a sonata without development, which therefore only includes two of your three sections.
In my experience, the development is the only one of these three sections that is optional. It seems to me the exposition is mandatory, because without it nothing can be developed. And the recapitulation seems mandatory because without it the music will not return to tonic.
Lastly, the term "sonatina" is also used to discuss a sonata without a development, but the term isn't used consistently; sometimes a composer uses "sonatina" to just mean "easy sonata."
Comment: @Klangen - The overture to Mozart's *The Marriage of Figaro* and the overture to Tchaikovsky's *The Nutcracker* are both Type 1 sonatas.
Comment: @Klangen Type 1 sonatas are common in works by early sonata composers like Sammartini, but I can't think of any of their specific examples off the top of my head. In terms of works by later composers, check out Brahms' *Tragic Overture* or the finales to his first and third symphonies. Note that all of these include expanded recapitulations, but none has a *bona fide* development section.
Comment: Excellent answer. Can you list any works that are in the form of a Type 1 Sonata?
Answer: The term Sonata can be used for any instrumental piece.
The Sonata that you're thinking of is the classical Sonatensatz and needs to have these 3 section to be called as such.
The classical Sonata includes apart of the Sonata-Satz form a Menuet or Scherzo and other forms like Adagio-Satz, Lied-Satz, (AB: a form made up of two contrasting sections, each of which may or may not be repeated) and a Rondo.
A smaller Sonata that also may fit to what your meaning (only 2 sections) is called Sonatina.
The Sonataform (1. or 4. section in a "Sonata") includes the 3:
exposition,
development, and
recapitulation.
Comment: Sorry, if I was not precisely (but I wrote that I mean the 3  sections. The confusing thing that   Sonatensatz could also mean  "ein einzelner Satz einer Sonate" (which could also be a rondo or a scherzo) but to be more precisely I mean the Sonaten - Hauptsatz - Form. https://de.wikipedia.org/wiki/Sonatensatzform ... the Englis version of this wiki paragraph tells me that also  it's called the *sonata allegro form* Sonata form (also sonata-allegro form or first movement form) is a musical structure consisting of three main sections ... the term of sonata OP is referring to.
Comment: What do you mean by *Sonatensatz?*  This term isn't in common use in English.
Comment: that's the term for the typical Sonataform *exposition, development, and recapitulation.*
Comment: But you also use *Sonataform,* with German spelling.  Is that a German word?  If so, what is the difference between *Sonataform* and *Sonatensatz?*  Which one corresponds to the English term "sonata form"?
Comment: @phoog actually Albrecht Hügli did not use the German spelling in the word Sonataform since the German spelling would be Sonatenform. So he used the English spelling "sonata form" just made it into one word "Sonataform" but he used capital S. Anyway, the German "Sonatensatz" really means "sonata movement", so that could be any movement in a sonata while the German "Sonatenform" means "sonata form" and this refers to the form of the 1st movement in a sonata, although it can sometimes happen that another movement also has this form but the other movements usually have other forms.
Comment: @LarsPeterSchultz By "German spelling" I meant only that it was written as a single word with a capital letter.  Perhaps I should have said "German-style spelling."  That along with the use of italics led me to assume that it was a German word with a different meaning from *Sonatensatz.*  In English "sonata form" is a shorter if less precise way of denoting sonata-allegro form, and indeed English Wikipedia redirects from *sonata-allegro form* to *sonata form,* with the latter article beginning "Sonata form (also *sonata-allegro form* or *first movement form)"*
Answer: A sonata that has only the exposition and the recapitulation or only a very short development section can be called a sonatina.
Early sonata forms from the transition between the Baroque and Classical periods can be based on a two part form. Essentially the material of the first half will move from the tonic key to the dominant key. Then the second half restates the material but with the key areas reversed, the second half starts in the dominant key and transitions to the tonic key. These movements may not necessarily be titled "sonata." In a suite of movements an  allemande, courante, gigue, etc. may use the early sonata form. You could also look for examples in Scarlatti's shorter sonatas for harpsichord.
Examples of simple two part sonatinas can be found in many sources. They often are titled "sonatina" which makes them easy to find. You can also find examples in the Mozart Nannerl Notebook, but none of those are titled as "sonata" or "sonatina."
In these sonata forms the order of thematic material change between the initial presentation in the exposition and its second appearance in the recapitulation. The placement of the thematic material isn't what determines the form but instead the movement form tonic to dominant and back to the tonic. You could abstract the essential harmonic aspect of the form to...
<code>||: I (V7/V) V :||: V(7) I :||</code>
Very important is the sense that the dominant becomes a new tonic at the close of the first half. Then in the second half the dominant returns to its original function as the dominant of the opening tonic.
As a side note: you may want to read up on the distinction of sonata as a two part or three part form. The three part idea of course is: exposition, development, and recapitulation. But in terms of form and harmony it's more of a two part form. The traditional division of a sonata movement into two halves with a double bar repeat underscores the two part, binary aspect.
The ideas aren't mutually exclusive. Think about both when you assess any particular sonata. You can think of the third section as the development which may be optionally omitted, just a brief segue into the recapitulation which doesn't really constitute a formal section, or a long excursion to various keys which can be considered a bona-fide, formal section.
Comment: So the question would be: is a Sonatina also a Sonata?
Comment: I say yes. I think of it more like a principle, a sonata principle to recapitulate material in the tonic. It can be on a small or grande scale. In that sense the development's appearance is more a matter of how grand the scale is, but certainly not a requirement to define the music as displaying the sonata principle.


PDOException: SQLSTATE[HY000] [2003] Can't connect to MySQL server

Question: I recently tried to setup a dev environment for my production site and replicated the same architecture.
I've a server hosting Drupal, a second server for mysql and a memcached server. All the setup was good.

Exported the Prod DB
Installed Drush
Made sure the latest code is pulled
run Drush status
Drupal version         :  7.37
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  ip address
 Database port          :  3306
 Database username      :  username
 Database name          :  dbname
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.9
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /path/to/root/folder
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

The issue is when trying to load the website I get :
PDOException: SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'ip-address' (13) in lock_may_be_available() (line 167 of /var/www/cw/html/includes/lock.inc).
Any idea why this is happening ? If I run drush sqlc I'm able to connect to the remote database.
Any help will be much appreciated.
Answer: For anyone having the SAME error code, please check if you have SELinux enable by typing sestatus. If that's the case then your firewall is most likely blocking the connection to the db.
To allow it you can use the following command line :
setsebool httpd_can_network_connect_db=1

Answer: Have you created user with APP Server IP in your database. If not please create the user first.
CREATE USER 'username'@'APP_SERVER_IP' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON . TO 'username'@'APP_SERVER_IP';
FLUSH PRIVILEGES;
and then use this user in your drupal site to connect with database.
If it is not working then please check the MySQL Database port on DB Server. If it is not open then open it first.
Comment: It didn't work. fyi I'm able to connect using drush, so the port is not the issue. I also used the root on my settings.php and it's not working either.


How to hide some issue link types in the Issue Link pop up window for Jira 5.1.8 using javascript?

Question: I wanted to hide some issue link outward & inwards strings of Link type from the Link Issues Popup Window using java script.
I have tried using java script but I am not getting the popup screen from the java script.
Please see the screenshot below :

Can anyone tell me how can I get this popup screen in the java script?
Is there any other method to hide this?
Thanks & Regards,
Renuka.
Comment: answer updated , have a look :)
Answer: To hide the clone issue link every page:
edit the file system-webresources-plugin.xml (should be at /atlassian-jira/WEB-INF/classes/), and add to <web-resource key="jira-fields"> this code:
    <resource type="download" name="myScript.js" location="/includes/jira/field/script.js">
        <param name="source" value="webContextStatic"/>
    </resource>

than, on /includes/jira/field/myScript.js write this:
AJS.$(document).ready(function() {
    if (AJS.$("#link-type option[value*='clon']").size() > 0) {
        // will work even when right clicking on More
        // Actions->Link & open it into a new window
        AJS.$("#link-type option[value*='clon']").remove()
    } else if (AJS.$("#link-issue").size() > 0) {
        // will work in case the link menu showing via popup
        AJS.$("#link-issue").click(function(){
            // wait for the popup to show, and remove the clone options
            setTimeout(function (){
                AJS.$("#link-type option[value*='clon']").remove();
             }, 300);
        });
    }
});

restart Jira and it that it!
The script attaches a function to the link-menu opening, than gives the menu 0.3 seconds to load, and removes the unwanted items. If it doesn't work well for you, try to raise the timeout from 300 to 500-1000.
On jira 4, run instead:
    AJS.$("#issue-link-link-type option[value*='clon']").remove();

Comment: I thought that 5.x used code like
Comment: Hi Kuf,    Thanks for replying. I tried your script but still no luck!! :(  I am putting this script in Announcement Baner is there any other way to put this script.Thanks!!!
Comment: no its not working on browser console also. it is not getting the pop up window of the issue linking.
Comment: Error: Permission denied to access property 'toString'
I am getting above error on console log
Comment: Hi Kuf, I have tried your above script in the browser console. I am getting following error : SyntaxError: missing } in XML expression
data:
Comment: Hi Kuf, This script is not working when I right click on More Actions->Link & open it into a new window.  How can I achieve that???
Comment: Try using setInterval() instead of setTimeout() , this will solve the open in new window issue . let me know if it works for you.
Comment: @Mizan, the problem was that when writing this on `Announcement Banner` it won't work when  right clicking on More Actions->Link & open it into a new window. That's why i've updated my answer. I can't see why to use 'setInterval' instead of `setTimeout` since we want to run this script only once.
Comment: Hi Mizan, setInterval is working when I click on Web Link & then I click on Jira Issue on the popup for Link.
Comment: Hi Kuf, I do not want it to run once it should run if I click on some other link then again click on Jira issue the js should work. setInterval is working for me.
Answer: The previous solution has an issue:
It will only work when clicking the "Link Issue"-Menu-Item.
When I use the Point (.)-Shortcut-Menu, it won't remove the issue types.
I have established the following solution:
JS-Binding-Part:
AJS.$(document).ready(function() {
JIRA.bind(JIRA.Events.NEW_CONTENT_ADDED, function(e, context, reason) {
     hideIssueLinkTypes();
  });
});

JS-Backing-Function:
function hideIssueLinkTypes() {
var apiURL = "/rest/scriptrunner/latest/custom/getHiddenLinkTypes"

  $.getJSON( apiURL, {
  }).done(function( objectData ) {
      $.each( objectData, function( i, item ) {
        var issueLinkType = item.issueLinkType[0];
        AJS.$("#link-type option[value='"+issueLinkType.inwardDescription+"']").remove();
        AJS.$("#link-type option[value='"+issueLinkType.outwardDescription+"']").remove();
      });
    });
}

Scriptrunner-REST-Endpoint:
import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.JsonBuilder
import groovy.transform.BaseScript
import com.atlassian.jira.issue.link.DefaultIssueLinkTypeManager
import com.atlassian.jira.issue.link.IssueLinkTypeManager
import com.atlassian.jira.issue.link.IssueLinkType
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.config.properties.ApplicationProperties

import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response

@BaseScript CustomEndpointDelegate delegate

String HIDDEN_IDENT="[hidden]"

getHiddenLinkTypes(httpMethod: "GET") { MultivaluedMap queryParams, String body ->

    def appProperties = ((ApplicationProperties) ComponentAccessor.getComponentOfType(ApplicationProperties.class));
    def appClonersLinkTypeName = appProperties.getDefaultBackedText("jira.clone.linktype.name");

    def jsBuilder=new JsonBuilder();
    def issueLinkTypes = ((IssueLinkTypeManager) ComponentAccessor.getComponentOfType(IssueLinkTypeManager.class)).getIssueLinkTypes();

    jsBuilder issueLinkTypes.findAll({it.getName().contains(HIDDEN_IDENT) || it.getName()==appClonersLinkTypeName }),
    { IssueLinkType linkType ->
        issueLinkType linkType.getId(),
        name: linkType.getName(),
        inwardDescription: linkType.getInward(),
        outwardDescription: linkType.getOutward()
    }

    return Response.ok(jsBuilder.toString()).build();
}

What you can do then ist just annotate and Link-Type with putting [hidden] in the link name and it will disappear for all users (It can still be programmatically added though or created by cloning).
If you don't have Scriptrunner or don't need the dynamic nature of the implementation, you can still hard-code the values as Kuf described in the answer above in hideIssueTypes() like this:
AJS.$("#issue-link-link-type option[value*='clon']").remove();


How to make SlidingDrawer push existing layouts when showing?

Question: Main purpose:
I have a listview display on screen, and want to have a SlidingDrawer on the bottom of it.
I'm actually making the "handle" view of the SlidingDrawer toggle by code to show/hide the drawer.
I want my bar to show by sliding in and "shrink" the listview layout.
And when it hides to make the listview layout return to its original view.
Right now I'm having a listview layout that's fixed in place, and a transparent placeholder for the drawer to show or hide in.
Can someone help me figure this one out ?
Activity xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/Container"
android:id="@+id/layout"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1" >

    <ListView
        android:id="@+id/listview"
        style="@style/Widget.ListView" />
</LinearLayout>

<include
    layout="@layout/delete_bar" />

</LinearLayout>

delete_bar xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/MarginTopBottom"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="bottom"
    android:orientation="vertical"
    android:padding="10dp" >

    <my.WrappingSlidingDrawer
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:content="@+id/content"
        android:handle="@+id/handle" >

        <LinearLayout
            android:id="@+id/content"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <Button
                style="@style/Widget.Button.Wrap"
                android:id="@+id/btn_DeleteBar_delete"
                android:layout_weight="1"
                android:onClick="onClick"
                android:text="@string/w_Delete" />

            <Button
                style="@style/Widget.Button.Wrap"
                android:id="@+id/btn_DeleteBar_cancel"
                android:layout_weight="1"
                android:onClick="onClick"
                android:text="@string/w_Cancel" />
        </LinearLayout>

        <Button
            android:id="@+id/handle"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:visibility="gone" />
    </my.WrappingSlidingDrawer>
</LinearLayout>

Answer: You may want to check out this answer (and possibly the others with it). It seems they were trying to accomplish something similar. - Android: Expand/collapse animation
Answer: Try this with default drawer.
actionBarToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            mDrawerLayout,         /* DrawerLayout object */
            R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open,  /* "open drawer" description for accessibility */
            R.string.drawer_close  /* "close drawer" description for accessibility */
            ) {public void onDrawerSlide(View drawerView, float slideOffset)
        {
            float moveFactor = (mDrawerList.getWidth() * slideOffset);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            {
                frameLayout.setTranslationX(moveFactor);
            }
            else
            {
                TranslateAnimation anim = new TranslateAnimation(lastTranslate, moveFactor, 0.0f, 0.0f);
                anim.setDuration(0);
                anim.setFillAfter(true);
                frameLayout.startAnimation(anim);

                lastTranslate = moveFactor;
            }

or use different library's for drawing drawer.
Answer: i hope this would help u out
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FF4444CC">
<SlidingDrawer android:id="@+id/drawer" android:layout_width="fill_parent" android:layout_height="fill_parent" android:handle="@+id/handle" android:content="@+id/content">

<ImageView android:id="@id/handle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/tray_handle_normal"`/>

<Button android:id="@id/content" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="I'm in here!" />

</SlidingDrawer> </FrameLayout>


Django routing to database based on model table

Question: I have a Django (1.6) project with two databases. I have one app with one model, and multiple tables.
I want to use the database routers to set specific tables in the model to a specific database. All the documentation I have found seems to explain how to route a particular app to a particular database.
Answer: Looks like you could use a custom router and model attribute for this.
YMMV: Haven't tested this.
https://docs.djangoproject.com/en/dev/topics/db/multi-db/#using-routers
<code>class MyModel(models.Model):
    _DATABASE = "foo"

class CustomRouter(object):
    def db_for_read(self, model, **hints):
      database = getattr(model, "_DATABASE", None)
      return database
    # repeat for db_for_write, etc.
</code>
Comment: The value of `_DATABASE` would just refer to the database name declared in the `DATABASES` setting entry. You can figure out the table name from `model._meta.db_table`.
Comment: Thanks for your response @AKX. Is "_DATABASE" referring to the name of the table? So if I made all the table names name_DATABASE (where database is the name of my other database), it would detect it that way?

Do you know if I can just reference the table names in the routers?
Comment: This doesn't appear to work in Django 1.11. I added a model attribute DATABASE_NAME to my model but it doesn't exist as far as my custom database router is concerned.


PLaying Default Video in Windows Phone 8

Question: I have parsed RSS feed http://www.teluguone.com/videosongs/videoSongsXml.php?cat_id=6.
And displayed songpics in Horizontal List view. As shown below

When I click on a particular song it was playing in the space above.
But,here I want to get default video along with Horizontal list view.And when I click on a particular video it should be played.
How to get the default video along with List view.
XAML code:
    <phone:PhoneApplicationPage
    x:Class="PhoneApp1.MainPage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
   xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:delay="clr-namespace:Delay;assembly=PhonePerformance"
   mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
   FontFamily="{StaticResource PhoneFontFamilyNormal}"
   FontSize="{StaticResource PhoneFontSizeNormal}"
   Foreground="{StaticResource PhoneForegroundBrush}"
   SupportedOrientations="Portrait" Orientation="Portrait"
   shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
        <TextBlock x:Name="ApplicationTitle" Text="Teluguone" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock x:Name="PageTitle" Text="Songs" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

        <MediaElement x:Name="player" AutoPlay="True" Margin="0,0,0,282"/>

        <ScrollViewer HorizontalScrollBarVisibility="Hidden" Height="Auto" Margin="-60,411,-93,10"  >
            <ListBox x:Name="videosongList" ScrollViewer.HorizontalScrollBarVisibility="Auto"
         ScrollViewer.VerticalScrollBarVisibility="Disabled" Height="200" Width="1000" SelectionChanged="videosongList_SelectionChanged" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Margin="0,50,0,0"  Orientation="Horizontal">
                            <Image  x:Name="img1" Source="{Binding songpic}"  ></Image>

                            <TextBlock Text="{Binding songname}"  TextWrapping="NoWrap"  VerticalAlignment="Bottom"
                                       FontSize="20" />

                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
                <ListBox.ItemsPanel >
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal"></StackPanel>

                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
            </ListBox>
        </ScrollViewer>
    </Grid>
</Grid>

Code for XAML.cs:
namespace PhoneApp1
   {
        public partial class MainPage : PhoneApplicationPage
       {
          public MainPage()
        {
             InitializeComponent();
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            // is there network connection available
             if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                MessageBox.Show("No network connection available!");
                return;
            }
            // start loading XML-data
            WebClient downloader = new WebClient();
            Uri uri = new Uri("http://www.teluguone.com/videosongs/videoSongsXml.php?cat_id=6", UriKind.Absolute);
            downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(VideosongsDownloaded);
            downloader.DownloadStringAsync(uri);
          }

          void VideosongsDownloaded(object sender, DownloadStringCompletedEventArgs e)
    {
            if (e.Result == null || e.Error != null)
            {
                MessageBox.Show("There was an error downloading the XML-file!");
            }
            else
            {
                // Deserialize if download succeeds
                XDocument document = XDocument.Parse(e.Result);
                XmlSerializer serializer = new XmlSerializer(typeof(videosongs));
                videosongs videosongs = (videosongs)serializer.Deserialize(document.CreateReader());
                videosongList.ItemsSource = videosongs.Collection;
            }
        }

    private async void videosongList_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        Songsdetails song = (Songsdetails)videosongList.SelectedItem;

        var url = await YouTube.GetVideoUriAsync(song.songcode, YouTubeQuality.Quality480P);
        player.Source = url.Uri;
    }
}

}

Anybody please give me any suggestion of getting default video playing along with horizontal list view.
Many Thanks.
Answer: Did you try playing Youtube videos using the Youtube class from Codeplex.
Youtube Class
or else you could refer the sample from msdn:
Youtube Video sample
Comment: Thank you  sir.I am refering Youtube class


bash command to either open one command or another command

Question: I am using two different OSes.

for MacOS : open file.pdf  ( it opens pdf in default pdf program in Mac)
for Linux : xdg-open file.pdf ( it does so in Linux)

If I interchange the command it doesnot work.
Is there any single line set of commands like:

open file.pdf or xdg-open file.pdf

I want a command (or commands) that works for both of them without showing any error.
The place where I need this command is in make file.
I have a makefile like this:
all:
open file.pdf
xdg-open file.pdf
other things ..

Here, inside the makefile how can I be sure that make commands run without
error both in Mac and in Linux?
Thanks to @rubiks, now the code works fine.
The code looks like this:
# set pdfviewer for linux and unix machines
####################################################

UNAME_S := $(shell uname -s)

$(info $$UNAME_S == $(UNAME_S))

ifeq ($(UNAME_S),Linux)
PDFVIEWER := xdg-open
else ifeq ($(UNAME_S),Darwin)
PDFVIEWER := open
else

$(error unsupported system: $(UNAME_S))
  endif
$(info $$PDFVIEWER == $(PDFVIEWER))
####################################################
# open the pdf file
default: all
    $(PDFVIEWER) my_pdf_filename.pdf

Answer: I think it is better to do this a little more intelligently and determine the OS you are on:
if [ `uname` == "Darwin" ]; then
  open file.pdf
else
  xdg-open file.pdf
fi

If you are trying to configure your terminal so that you can always use the same command, I would recommend adding this to your .bashrc or .bash_profile:
if [ `uname` == "Linux" ]; then
   alias open=xdg-open
fi

This way, you can always use the command open and it will work on either OS.
Answer: If you don't mind invoking the shell, you can query the system from within the Makefile and set PDFVIEWER accordingly:
UNAME_S := $(shell uname -s)

$(info $$UNAME_S == $(UNAME_S))

ifeq ($(UNAME_S),Linux)
  PDFVIEWER := xdg-open
else ifeq ($(UNAME_S),Darwin)
  PDFVIEWER := open
else
  $(error unsupported system: $(UNAME_S))
endif

$(info $$PDFVIEWER == $(PDFVIEWER))

Comment: This worked for me. Thanks to @rubiks. If i had more than 15 points I would have given upvote for you.
Comment: @BhishanPoudel  it's all good---I'm just happy you got something working for you! :-)
Answer: You may try to use which to return first available executable, e.g.
open  := $(shell which open xdg-open | head -n1)
xargs := $(shell which gxargs xargs  | head -n1) # Another example.

then run it as:
$open file.pdf


Can the Fourier transform witness complete normality of the dual group?

Question: Let $\Gamma$ be a countable Abelian group and let $G$ be its dual (compact) group. Consider the Fourier transform $F$ as a map from $\ell_1(\Gamma)$ into $C(G)$.
Take a non-empty open subset $U$ of $G$. Is there $f$ in $\ell_1(\Gamma)$ such that $F(f)$ is positive exactly on $U$ and zero otherwise?
Answer: Edit: The answer is no in general, since $\{f>0\}$ must be an $F_\sigma$. If $S$ is an $F_\sigma$ the answer is yes.
Note In fact there's no significant use of the fact that $G$  is compact below; if $G$ is any LCA group and $\Gamma=\hat G$ then (of course writing $L^1(\Gamma)$ in place of  $\ell_1$) the answer is yes if and only if $S$ is a countable union of compact sets.
Hint to maybe get started: In this context the basic  way one gets $f\in\ell_1$ such that $\hat f$ does something is to note that Plancherel shows that $$L^2*L^2=\widehat{L^1}.$$
More explicitly:

Lemma Suppose $V$ is a neighborhood of the origin in $G$. There exists $f\in\ell^1(\Gamma)$ such that $\hat f\ge0$, $\hat f(0)>0$, and $\hat f$ vanishes on $G\setminus V$.

Proof: Let $W$ be an open set with $0\in W$ and $W+W\subset V$. Let $$\phi_V=\chi_W*\chi_W.$$ Then $\phi_V\ge0$, $\phi_V(0)>0$, and $\phi_V$ vanishes on $G\setminus V$.
And $\hat\phi_V=(\hat\chi_W)^2$, so $$||\hat\phi_V||_1\le||\chi_W||_2^2=m(W)<\infty.$$Qed.
It's easy to use the lemma to prove this:

Theorem. If $U\subset G$ is open and $K\subset U$ is compact there exists $f\in\ell_1(\Gamma)$ with $\hat f\ge0$, $\hat f>0$ on $K$, and $\hat f=0$ on $G\setminus U$.

Hint: Say the function obtained in the lemma is $f_V$. Say $S(V)$ is the set where $f_V>0$. You can concoct things so $x_j+V_j\subset U$, $K\subset\bigcup_j(x_j+S(V_j))$.
(And then $f=\sum c_jf_j$ gives $\{f>0\}=U$ if  $U$ is an $F_\sigma$...)


Symfony and Doctrine - getDoctrine not found

Question: I am trying to build a simple app
I have a database with a table "matches"the table structure
and i wrote this code as Entity
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="matches")
 */

class Match
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="text", length=512)
     */
    private $descr;
    /**
     * @ORM\Column(type="string", length=255)
     */
    private $team_a;
    /**
     * @ORM\Column(type="string", length=255)
     */
    private $team_b;
    /**
     * @ORM\Column(type="string", length=255)
     */
    private $location;
    /**
     * @ORM\Column(type="datetime")
     */
    private $datetime;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set descr
     *
     * @param string $descr
     *
     * @return Match
     */
    public function setDescr($descr)
    {
        $this->descr = $descr;

        return $this;
    }

    /**
     * Get descr
     *
     * @return string
     */
    public function getDescr()
    {
        return $this->descr;
    }

    /**
     * Set teamA
     *
     * @param string $teamA
     *
     * @return Match
     */
    public function setTeamA($teamA)
    {
        $this->team_a = $teamA;

        return $this;
    }

    /**
     * Get teamA
     *
     * @return string
     */
    public function getTeamA()
    {
        return $this->team_a;
    }

    /**
     * Set teamB
     *
     * @param string $teamB
     *
     * @return Match
     */
    public function setTeamB($teamB)
    {
        $this->team_b = $teamB;

        return $this;
    }

    /**
     * Get teamB
     *
     * @return string
     */
    public function getTeamB()
    {
        return $this->team_b;
    }

    /**
     * Set location
     *
     * @param string $location
     *
     * @return Match
     */
    public function setLocation($location)
    {
        $this->location = $location;

        return $this;
    }

    /**
     * Get location
     *
     * @return string
     */
    public function getLocation()
    {
        return $this->location;
    }

    /**
     * Set datetime
     *
     * @param \DateTime $datetime
     *
     * @return Match
     */
    public function setDatetime($datetime)
    {
        $this->datetime = $datetime;

        return $this;
    }

    /**
     * Get datetime
     *
     * @return \DateTime
     */
    public function getDatetime()
    {
        return $this->datetime;
    }
}

and this as controller:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Match;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class AddMatch
{
    /**
     * @Route("/addmatch")
     */
    public function createAction()
    {
        $match = new Match();
        $match->setDescr('Descrizione Partita');
        $match->setTeamA('Squadra A');
        $match->setTeamB('Squadra B');
        $match->setLocation('a nice Gym');
        $match->setLocation('12/12/2012');
        $em = $this->getDoctrine()->getManager();

        // tells Doctrine you want to (eventually) save the Product (no queries yet)
        $em->persist($match);

        // actually executes the queries (i.e. the INSERT query)
        $em->flush();

        return new Response('Saved new match with id '.$match->getId());
    }

}

but it dosent work and I get Not Found
What am I missing?
I am super n00b :(
thanks for your help
Comment: Follow the example in the docs: http://symfony.com/doc/current/controller.html There are several other things you need to do besides extending the symfony base controller class.
Comment: you should extends `Symfony\Bundle\FrameworkBundle\Controller\Controller` class
Comment: You need to extend the base symfony controller in order to have the getDoctrine method available
Comment: how do I do that?
Answer: You have to extend the base symfony controller:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class AddMatch extends Controller
{
    ...
}

If, for some reason, you can't extend a controller, you still can use Doctrine entity manager. In that case you need to inject the service container and then get the entity manager with
$container->get('doctrine')->getManager();

You should thoroughly read the Symfony guide on Service Container.


Why is just 1 smtp server redirecting wrong?

Question: I have 2 domains: vanbulck.com and oliviervanbulck.com. I use oliviervanbulck.com for my personal website, and vanbulck.com for my e-mail address. Vanbulck.com also redirects to oliviervanbulck.com, so they reach my website both.
Most of the time this works, but a friend of me told me that he was unable to reach me by mail, and it was just by one smtp-server. This server does the redirect to oliviervanbulck.com instead of using the mx record which redirect to outlook.com (domain service from Microsoft).
My DNS from vanbulck.com is set like this: http://puu.sh/6o6TX.png
What do I have to change for letting this work correctly? That also that smtp-server can send emails to me correctly?
Answer: Do you want to receive mail on:mail.vanbulck.com or vanbulck.com. Your mx-record is for vanbulck.com
Comment: I want to receive email on vanbulck.com, which is redirecting to the servers from outlook.
Comment: It seems like your olivervanbulck redirect is causing the trouble. If you try this mx-tool i goes directly to your cname redirect: http://mxtoolbox.com/SuperTool.aspx?action=mx%3avanbulck.com&run=toolpage#

Try remove the cname for a test, and see if that helps. Have you followed this guide http://www.wpsite.net/how-to-setup-outlook-com-for-your-domain/ for mail settings on outlook?
Comment: The website you gave me doesn't show me an error. I have tried to add the TXT-record in DNS from the guide, I hope this will help. The weird thing is that there's just 1 person who can't reach me, all the other mails are perfectly working.


Roman Numeral Analysis of Chords Outside Of The Key: C7 in the key of E major

Question: I'm completing a roman numeral analysis in E Major, but there's several chords marked out that fall outside of the key - either with an accidental that shouldn't be there or they're marked as minor.
How how does this affect my analysis? Should a C7 still be chord vi7 without the sharp?
Comment: It would be very useful, and glean more detailed answers, if there was a copy of said piece to better analyse.
Comment: are you asking about a C7 in the key of E major?
Comment: If you want to do an analysis ignoring modulation, then just yeah, put the C7 as a bVI7.  If you want to account for modulation it's pretty hard without a melodic context.
Comment: what is this from?  Sounds like a bossa tune or something
Comment: Also as a tip I'd try and group the bars into 4s and see how that works out for you.
Answer: Everything you analyze in roman numeral analysis needs to reflect the key you are in and where the chord comes from. If the chord is not in the key, it needs to be marked appropriately. There is no scenario where you would mark a C7 as vi7 in the key of E major because:

The standard vi chord in E major is C#, thus a root of C needs to be denoted with a flat to show it is does not have a root of C#.
The chord is major in nature, so in most styles of analysis the Roman Numerals would have to be capitalized.

So if the C7 was considered a borrowed chord was functioning in E major it would be shown as bVI7, which is very unlikely because of the dominant nature of the C7.
The most likely scenario is you are modulating to either F major or F minor. In either case the chord would be seen as a V7 in each key. Most likely it would not be a secondary dominant because F is not in the key naturally. If it was however, it would be analysed as V7/bII.
There are a few more possibilities that are a little more involved. The chord itself could be part of a sequence where there is some kind of pattern being repeted over, and over agian to take you from one idea to another. Most likely in this case you would analyze it as a modulation. It could also just be a passing chord in which case, you don't analyse it because it is not functioning as a typical chord in the key.
Comment: In jazz and popular music the most likely function of C7 in E major would not be a secondary dominant of F (major or minor), but a subV7 (tritone substitute) leading to the V, i.e. B7. So it replaces F#7, the secondary dominant of B7.
Comment: another function could simply be a piece where the major/minor character of the key is pretty ambiguous, and the C7 is functioning as a vi7 in E minor.

E, G, A  is not an uncommon progression in Rock music for example.

If I *had* to write that in romans I think I'd go for `I bIII IV`.  But you could just choose to write it in Em and go for `i III IV` , and I don't think you could necessarily say that was wrong either.
Comment: @Some_Guy but if you say it is in E major, III and bIII are two completely different chords and you need to be extremely verbose in stating what it is that's why I stated the vi7 alone in E major  does not mean C7, but instead Cm7.
Comment: I don't quite get how your comment relates to what I was saying.  I know that whether you flatten the root or not matters haha... I was just giving a further context in which something like a bVI7 could be very likely, not just as a modulation, in modern popular music where "majorness" and "minorness" are more ambiguous than in Common Practice music.

In the same way when notating this music you have to "pick" a key signature, when you consider a roman numeral analysis you just have do the same and analyse according to that.  By convention we go for the major for a variety of reasons.
Comment: Just trying to give a bit more context as to when a plain ol flat 6 might show up in a major key, even a flat 6 root note with a seventh chord, which means a flat 5 note just staring you in the face like, yeah man, and what.
Comment: here is a C7 in the key of E major, used in anger: http://vocaroo.com/i/s1YV8j8oIHdP   I mean, it's not elegant, but it illustrates the point haha
Comment: @Some_Guy In one of my favorite progressions ever: I - bVI - IV - V or in C major: C - Ab - F - G. It's borrowed from the relative minor, but your in a major key thus it's borrowed. If you tried to say it was a VI chord, it wouldn't make sense as that would be an A.
Answer: Chords outside the key that you find within a piece of real-world music are called Secondary Dominants or Borrowed Chords. Or in some cases the music may temporarily modulate from the main key into a related key and then back to the main key again. In that case you would see several chords in sequence that outline the modulation to the different key.
There are sections in all the music theory textbooks about how to analyze modulations, secondary dominants, and borrowed chords.
Answer: A chord analysis has less to do with the the chords that are traditionally at each tone degree and more with what notes you see in front of you. Yes the Sub Mediant chord in a Major scale is a Major chord but what happens when an accidental is used and this chord does suddenly not conform to the norm?
You need to be able to look at any chord and tell me is it Major / minor / Augmented or Diminished and also know the inversions of the triads and the quadtats.
Not just take the easy way out and memorise the standard chords in Major keys and assume all of them are always going to be the case.
Comment: Quadtat is a new one on me. Help?
Comment: I believe that is the word for a four note chord triad - tri - three quadtat - quad - four. I may be mistaken.
Comment: Can't find a word at the moment!
Comment: maybe he means tetrad?
Answer: There is so little to gain from a roman numeral analysis of this excerpt as it features so many transient modulations, cycles of secondary dominants, and non-functional harmony. I'd argue that, although there are elements of tonality, it is essentially non-tonal. It is simply not the type of piece to which you apply a roman numeral analysis.
C7 is the dominant of the Neapolitan in E major.
Comment: Calling this non tonal is ridiculous.  Admitting you don't understand jazz is one thing, but just insulting anything that doesn't fit into your narrow definition of harmony is small-minded.  I'm sorry if I seem OTT here but to write off this as non tonal and then use your "expertise" as a justification is just ridiculous.  The first four chords are literally a circle of fifths...  It's basic stuff man
Comment: Unfortunately I have to, it's a university assessment
Comment: I see. It's hardly in E major by the way. The first line makes sense in B major. Third line has a bit of Neapolitan action going on. A couple of cycle of 5th progressions in there as well.
Comment: is this non tonal?! https://www.youtube.com/watch?v=FOTZJ8EFgpk   Lighten up, stop worrying about whether it fits into your theory box and enjoy music!
Comment: ah, lighten up? I'll leave you to your monologue.
Comment: Hey man, sorry I came on so strong.  Tough day and all that.  That "I know classical theory and therefore can tell you with authority that this music is invalid" schtick was just reminiscent of an attitude I'm all too familiar with haha, but yeah I blew it way out of proportion...
Answer: As a contrary to the selected answer, allow me to illustrate how the first 4 chords are perfectly functional in the key of E
<code>             EΔ
YOU SEE IT'S TRUEEEEEE
             C#7
AN APE LIKE MEEEEEE
      F#7
KINDA LIKE TO BE
B7         E7 B7
HUUUU UMAN TOOOOO
</code>


Let $x,y,z>0; ~ xyz(x+y+z)=1$. Show that $(x+y)(y+z)\ge 2$

Question: Assuming positive real values of $x,y,z$, and that $ xyz(x+y+z)=1$, how can we prove that $(x+y)(y+z)\ge 2$
I tried using the AM-GM inequality but as if I were looping. I'm not sure if C-S or other inequality methods could help.  Thanks for helping me.
Answer: $$(x+y)(y+z)=xy+y^2+zx+yz=y(x+y+z)+zx=\frac y{xyz}+zx=zx+\frac1{zx}\ge 2\sqrt{\frac1{zx}zx}=2$$ using A.M.$\ge$ G.M. for $z,x>0$
Comment: I reached until $zx +\frac{1}{zx}$ but never thought of completing your answer. Thanks!
Comment: @Tariq, welcome, hope I could make things lucid.


Proving if $x<y$ then $\sqrt{x} < \sqrt{y}$

Question: I am stuck on this homework problem!
Prove that if $x$ and $y$ are real numbers such that $0<x<y$ , then $\sqrt{x}<\sqrt{y}$.
This is in a chapter involving the least upper bound axiom and the Archimedean Principle, but I cannot figure how to use either of those to prove this!  Any help would be most appreciated!  Thanks
Comment: Is there a part missing to the question?
Comment: oops, I think you want to clarify your problem statement in your post...if $x, y > 0?$...and what is it to prove?
Comment: Have you tried proving the contrapositive?
Answer: Hint : $ y-x=(\sqrt{y}+\sqrt{x})(\sqrt{y}-\sqrt{x})$ Now look at the signs..
Comment: This idea popped into my mind immediately after reading the question.
Comment: This was really beautiful
Answer: Suppose $0 < a < b$, multiplying by a gives us, $0 < \color{brown}{a^2 < ab}$.
Similarly, multiplying by $b$ gives $0 < \color{green}{ab < b^2}$ so $ab < b^2$. So from the brown and green, we have $0 < a < b \Leftrightarrow 0 < a^2 < b^2$.
Notice that your result is a corollary of this, let $x = a^2$ and $y = b^2$.
Answer: Hint: write it in contrapositive form - if $\sqrt{x}\geq \sqrt{y}$, then $x\geq y$ (assuming $x,y>0$).


Primefaces columToggler losing effect on filters

Question: I have a lazy datatable with filters, also have the option of toggling columns with the , it works fine on the first time, but if i remove let's say 3 columns and then make a new filter the columToggler keep's its state of selection and the headers of those columns are invisible as well, but the values come up again...
Sounds a little weird explaining, so i'll illustrate it.

So after the columns are selected i get:

But when i do some filtering or ordering on the dataTable i get:

I'm declaring my columnToggler the following way:
                <f:facet name="header">
                    Lista de CSRs

                </f:facet>

If any other information that is needed was omitted please tell me.
Answer: I've found the answer on the primefaces blog: http://blog.primefaces.org/?p=3341
I changed my columToggler to:

And on my Bean i added the following:
private List<Boolean> colunas; //Getters and setters

public void init(){

       setColunas(Arrays.asList(true, true, true, true, true, true, true, true, true, true, true));
}

public void onToggle(ToggleEvent e) {
        getColunas().set((Integer) e.getData(), e.getVisibility() == Visibility.VISIBLE);
    }

Then i just added the rendered state on each colum:

And done.


Must implement interface > Drupal\Core\Entity\EntityTypeManagerInterface, none given in __construct() function

Question: I am trying to write a custom eventsubscriber for commerce 2.x for an event after a successful checkout. Everything works and now I want to create a __construct function to initialize an object, but then I get the following error:

TypeError: Argument 1 passed to
  Drupal\custom_module\EventSubscriber\OrderCompleteEventSubscriber::__construct()
  must implement interface
  Drupal\Core\Entity\EntityTypeManagerInterface, none given, called in
  /home/user/websiteName/docroot/core/lib/Drupal/Component/DependencyInjection/Container.php
  on line 264 in Drupal\custom_module\EventSubscriber\OrderCompleteEventSubscriber->__construct()

I've tried explicitly defining the EntityTypeManagerInterface within the class, but everything is resulting in this error. Not finding anyone with any similar issues, and this particular block of code works for other people, just wondering what I am missing or If I am doing something incorrect. This code runs great if I don't construct an object with EntityTypeManagerInterfaceas the argument ... any ideas?
namespace Drupal\custom_module\EventSubscriber;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\rng\RegistrantFactoryInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class OrderCompleteEventSubscriber implements EventSubscriberInterface {

  use StringTranslationTrait;

  /**
   * The registration entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $registrationStorage;

  /**
   * The user entity storage.
   *
   * @var \Drupal\user\UserStorage
   */
  protected $userStorage;

  /**
   * The registration access handler.
   *
   * @var \Drupal\Core\Entity\EntityAccessControlHandlerInterface
   */
  protected $registrationAccessHandler;

  /**
   * The registrant factory.
   *
   * @var \Drupal\rng\RegistrantFactoryInterface
   */
  protected $registrantFactory;

  /**
   * Drupal\Core\Session\AccountProxyInterface definition.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a new OrderCompleteEventSubscriber object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   * @param \Drupal\rng\RegistrantFactoryInterface $registrantFactory
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, RegistrantFactoryInterface $registrantFactory, AccountProxyInterface $current_user) {
    $this->registrationStorage = $entity_type_manager->getStorage('registration');
    $this->registrationAccessHandler = $entity_type_manager->getAccessControlHandler('registration');
    $this->userStorage = $entity_type_manager->getStorage('user');
    $this->registrantFactory = $registrantFactory;
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      'commerce_order.place.post_transition' => ['buildRegistration'],
    ];
  }

  /**
   *
   * @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
   */
  public function buildRegistration(WorkflowTransitionEvent $event) {
    $order = $event->getEntity();
    // do stuff
      }
    }
  }

}

Services.yml File
services:
   custom_module_event_subscriber:
      class: '\Drupal\custom_module\EventSubscriber\OrderCompleteEventSubscriber'
      tags:
        - { name: 'event_subscriber' }

Comment: Probably the arguments in the service definition are missing, can you show the content of the *.services.yml file?
Comment: yes, you need this line: `arguments: ['@entity_type.manager', '@...', '@...']`
Comment: The services are named arbitrarily, you have to look them up. You find the core services in `core.services.yml`. The second service is from a module, so you find this in `rng.services.yml` of that module.
Comment: @4k4 that might be it, I did not provide arguments in my services file :P
I have put my `services.yml` file up
Comment: @4k4 That worked and cleared up the issue with the `EntityTypeManagerInterface` issue. Thanks! Where did you come up with `entity_type.manager` instead of `entity_type_manager`?  I am going through the docs and am not finding too many useful things on arguments. My second argument is now throwing an error saying the services has a dependency on a non-existent service, but when i take it out of the `services.yml`, the program white screens with the error saying I need my second argument to be of that type which symphony says it doesn't exist so I can't clear caches.
Answer: A bit late but the code from EventSubscriber has three arguments so your services.yml file should read:
services:
  custom_module.order_complete:
    class: Drupal\custom_module\EventSubscriber\PurchaseBuildRegistration
    arguments: ['@entity_type.manager', '@rng.registrant.factory', '@current_user']
tags:
  - { name: event_subscriber }


'pass through' php upload to amazon's s3?

Question: I've seen ways to upload files directly to S3 and I've seen ways to upload a file already on the server. I need to modify the file's name before sending it on to S3, but I don't want to store it locally and then upload it, if I can help it. Is there a way to put it in a buffer or something? Thx.
Answer: The file will always end up in the temporary directory first while the upload completes, even before you're able to work with the uploaded file. You get all the file's chunks before, and then it get rebuilt in the /tmp directory by default. So no, there's no "pass-through". But I guess you could re-upload directly from the temporary directory afterwards instead of moving it to another working directory.
Comment: Thx. Didn't think about the fact that it writes to a temp folder first and that there's no way to intercept it.
Comment: Well, there's always a way. You could probably rewrite part of PHP to have it all in memory but I guess it won't be worth the trouble. And having it on disk can mean you can put in place mechanisms for when it's down and maybe process files in bulk to S3, depending on what you're doing. :)
Comment: Ha, rewriting PHP is def not for me. I'm just letting the file upload locally and then firing a script that will upload it to Amazon in the background. Good enough. Thanks for yr help.


Any one Know ?? how to get router ip address from mac and iPhone?

Question: i wanna get router ip address,i got code for how to get ip address but i didn't get router ip address(Ex: 20.30.40.01 like that).any one know please ping me..
Comment: Are you looking for the router's internal IP address (the LAN address and your device's gateway), or the external IP address (the WAN address)?
Comment: http://imgur.com/WvD44Af
Comment: see about image i wanna that router address...
Comment: I'm not sure, but it sounds like using the user's IP address for an iOS app *may* be against Apple's terms. If not you may have to ask permission first
Comment: Also, your question will most likely be closed if you don't edit in more. So, what have you tried and why doesn't it work? What *exactly* are you looking for?
Comment: is it possible to convert ip address to router address??becz end of should be 1 that is router address
Comment: see the image i wanna that router ip address: http://imgur.com/WvD44Af
Comment: programmatically i can do as a ip address programmatically but i can't get router ip address programmatically
Answer: If you want the external address:
curl -4 ifconfig.co
curl -6 ifconfig.co

If you want the internal address:
Check if your code also returns the gateway, that's the routers internal address
Comment: i waana programmatically how to do??
Comment: could u say how to get DHCP Gateway address??
Comment: see the image i wanna that router ip address: http://imgur.com/WvD44Af
Answer: Follow the below steps:-
1)Go to Settings
2)Network
3)Advanced
4)Select TCP/IP tab
You will get IP address of MAC.
Comment: bro,could u say programmatically i wanna programmatically
Comment: http://stackoverflow.com/questions/7072989/iphone-ipad-osx-how-to-get-my-ip-address-programmatically refer this link
Comment: see the image i wanna that router ip address: http://imgur.com/WvD44Af
Comment: https://developer.apple.com/library/mac/samplecode/GetPrimaryMACAddress/Introduction/Intro.html refer this link
Comment: thats showed mac ip address but i wanna that like 22.214.171.124 like router address
Answer: Your local network router is always at 192.168.1.1 it plays the role of "machine 1" on the local network, or the last 1 in 192.168.1."1"
In the event this is not typically default, and to program it into your application I would refer to the code in this posting: (How can I determine the default gateway on iPhone?)
open up terminal, type:

scutil
list (Lists all your settings)
show State:/Network/Global/DNS
Terminal should read "192.168.1.1" or other primary connection(router ip)
Should be able to script that and include it into your apps. :)

Happy Coding Ahead!
Comment: That might be true for home routers in default configuration but there are networks where the router is not the first host in a subnet.
Comment: yeah thats right but how could i get programmatically
Comment: ok but i wanna router ip address i got ip address but i can't router ip
Comment: see the image i wanna that router ip address: http://imgur.com/WvD44Af
Comment: could u say what is this #include "getgateway.h" becz while using in the Xcode it showing error


Simple application of differential calculus

Question: A right circular cone is inscribed in a sphere. Prove that the volume of the cone cannot exceed ⁸/₂₇ of the volume of the sphere.
One would have asked what I have done on this question but no matter what I did I wasn't making headways I was only moving back and forth.
$V = 4/3πr^3$ , $(πr^2*h )/3$
 For sphere and cone.. I have differentiated trying to make some substitutions. ..tried considering those points where the cone touches the sphere. Any clue to this will be appreciated.
Comment: $r$ of the cone and of the sphere are not necessarily equal.
Answer:
In my diagram the sphere has centre $C$ and radius $R$. The cone has base radius $r$ and height $h$.
The volume of a right circular cone is $V = \frac{π r^2 h}{3}$. To apply the calculus you know you need to express this volume as a function of one variable. The right triangle ABC gives the information you need.
By Pythagoras theorem
$|CA|^2 + |AB|^2 = |BC2|^2$
thus
$(h - R)^2 + r^2 = R^2$
or
$r^2 = R^2 - (h - R)^2.$
Substitute $r^2$ into the expression for the volume of the cone and you have then a function of one variable $h$. Use your calculus to find the value of $h$ that maximized the volume.
It is then trivial to prove.
Comment: thanks. Quite insightful
Comment: Thank you, please accept the answer if you are happy with my argument :)


What's the difference between \r\n and \n

Question: In Terminal it seems like no difference between the two
echo -en 'first\r\nsecond' and echo -en 'first\n\second'
but in the code without \r it doesn't work
echo -en 'GET /test HTTP/1.1\r\nHost: localhost\r\n\r\n' | nc localhost 9292

works, but
echo -en 'GET /test HTTP/1.1\r\nHost: localhost\n\n' | nc localhost 9292

doesn't
anyone can explain why it is?
Comment: See http://stackoverflow.com/questions/3091524/what-are-carriage-return-linefeed-and-form-feed
Answer: Some applications can handle both \r\n (a.k.a. CRLF, carriage return line feed) and \n (a.k.a. LF, line feed) equivalently as newline sequences. Your terminal is an example.
The HTTP/1.1 Specification dictates that HTTP header lines always end with CRLF. So, an HTTP server which adheres to the specification (such as the one you're running on localhost:9292) will not interpret LF by itself as a valid HTTP header line termination sequence.