Python object1 = object2

Question: I am writing a vector class in python (just to see if i can). i ran into a problem with the subtract method and i have no idea what could be causing this.
this is the class (i omitted "class Vector:").
def __init__(self, p):
    print self
    self.p = p

def __str__(self):
    return str(list(self.p))

def equals(self, v):
    if type(self) == type(v):
        return str(self) == str(v)
    return false

def size(self):
    return len(self.p)

def add(self, v):
    a = self.p
    b = v.p
    if self.size() == v.size():
        for i in range(0, self.size()):
            a[i] += b[i]
        return Vector(a)
    raise Exception()

def subtract(self, v):
    a = self.p
    b = v.p
    if self.size() == v.size():
        for i in range(0, self.size()):
            a[i] -= b[i]
        return Vector(a)
    raise Exception()

def dot(self, v):
    total = 0
    if self.size() == v.size():
        for i in range(0, len(self.p)):
            total += self.p[i] * v.p[i]
        return total
    raise Exception()

def norm(self):
    total = 1
    if self.size() == v.size():
        for i in range(0, len(self.p)):
            total += self.p[i]^2
        return total
    raise Exception()

when i try to do:
a = Vector([1,1])
a.subtract(Vector[1,1])
print a

my thought says i should get [1,1] as output because i do not change any values of Vector a when i do the subtraction, i return a new vector with the values it should have. when i print the object it shows me that it is in a different space in memory but my output from 'print a' is [0,0]
also if i do
a = Vector(1,1)
b = a
a.subtract(Vector([1,1])
print a,b

my output is [0,0][0,0], what i want is [0,0][1,1]
why does b change with a ?
Comment: aren't there methods like `__sub__` and `__add__` in python?
Comment: See this [code](https://gist.github.com/anonymous/9d63da5f36c94605e285), I wort it to review vectors, you way find it useful.
Answer: First question:
(1, 1) - (1, 1) == (0, 0)

The output of your program is correct. You change the values of a in your function with a[i] -= b[i] where a is the list of coordinates (not a copy of the list) in self and b the list of coordinates (again, not a copy) in v.
Second question:
b = a

a and b are now the same object (not different objects with the same value), so they change simultaneously.
Think of a and b as addresses for your computer.
a = Vector(1,1)           # There is a Vector object somewhere in memory, e.g. 12345. Then a = 12345
b = a                     # b = a = 12345 (still the address of the same Vector object)
a.subtract(Vector([1,1])) # Change whatever is stored at the address of a = 12345
print a,b                 # both are still the address of the same object you modified in the previous step!

Comment: my output of print a should be (1,1) because i return a new vector with coords a.p. what about when i said b = Vector(a.p)?
shouldnt i get a new vector with the same coordinates?

Python object1 = object2


How to send an eMail to registered users after they are invited using the Group module?

Question: I use the Group module and the "Ginvite" submodule on Drupal 7.52.
The module allows you to invite people (either registered users or users without an account) to become a member of the group that the invitation is about.

This is what happens after somebody is invited:

When I write an email in "Invitations by email" and the person is not registered on my site, then the person receives an email invitation.
when I write an email in "Invitations by email" and the person is already registered on my site, then the person receives an invitation message on the user's account, as shown in this screenprint:

However, I want people who already have a user account, to receive an email notification about that invitation in addition to the invitation (message) on their user account.
How to do this?
Comment: @Pierre.Vriens I have updated my question. I do not know what to put more.
Comment: ***Now*** the question is clear, and complete ... I think!
Answer: You can use the Rules module to achieve that "people who already have a user account, also receive an email invitation in addition to the invitation on their user account" (as in your question).
Here is the rule (in Rules export format) to actually do so:
{ "rules_send_email_after_inviting_a_registered_user" : {
    "LABEL" : "Send eMail after inviting a registered user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "group" ],
    "ON" : { "group_membership_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "group-membership:status" ], "value" : "invited" } },
      { "NOT user_has_role" : {
          "account" : [ "group-membership:user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[group-membership:user:mail]",
          "subject" : "You have a pending group invitation",
          "message" : "Hi there!\r\n\r\n[site:current-user:name] has invited you to become a member of the group \u0022[group-membership:group]\u0022 on [site:name].\r\nIf you wish to accept the invitation, you need to login with your existing account first, which is \u0022[group-membership:user:name]\u0022.\r\nPlease visit the following address in order to do so: [site:login-url]\r\n\r\nKind regards,\r\nThe [site:name] team",
          "from" : "[site:current-user:mail]",
          "language" : [ "" ]
        }
      },
      { "drupal_message" : { "message" : "You just invited existing user with name [group-membership:user:name] and eMail Id [group-membership:user:mail] to the group named [group-membership:group].\r\n\r\nAn appropriate message about this invitation just got eMailed to [group-membership:user:name] also." } }
    ]
  }
}

Some more details about the magic included in this rule:

Sending an invitation in the Group module's terminology is equivalent to inserting a new Group Membership with status "invited" (how easy can it be?). So that explains the Rules Event I'm using, and the first Rules Condition.
Since we only want to send such eMail to users who already have an account, the 2nd Rules Condition is to check that the invited user does NOT (!!!) have role anonymous.
The Rules Action is just to send an appropriate eMail, using specific tokens related to the Group Membership, etc.
For debugging purposes, the 2nd Rules Action shows a confirmation message about the triggered eMail (feel free to remove that action if you don't like it).

Just import the above rule (using the Rules UI) in your own site, with no customization (changes) needed to see it at work in your own site (don't worry, there is no spyware in the eMail being produced ...).
The eMail content is pretty close to the eMail delivered when inviting anonymous users (the only difference is that it has an instruction to login with their existing account, also included in the eMail body). Here is how a sample eMail body looks like:
Hi there!

Pierre.Vriens has invited you to become a member of the group
"Drupal for Sitebuilders" on www.example.com.

If you wish to accept the invitation, you need to login with your existing
account first, which is "Dries.Buytaert".

Please visit the following address in order to do so:
http://www.example.com/user

Kind regards,
The www.example.com team

Possibly you may want to finetune the eMail subject, or eMail body. But apart from that no other changes should be needed.
Voilà ...
Comment: thank you for all those informations. Indeed this rule offers many possibilities
Comment: @Mathieu, merci! May I say "***What else did you expect***"??? Not sure if you realize, but this could be used as a prototype also for anything to implement "tracking" of who invites who, and if an invite is accepted, then make another something happen for the inviting user, such as granting user points, assiging user badges, combining it with the [Goals](https://www.drupal.org/project/goals) module (eg: to identify / reward users who succeed in inviting X other users). If any of these thoughts make you wonder how to do so, use [this](http://drupal.stackexchange.com/questions/ask) link


Laravel eloquent get index once

Question: I have table contain user posts and each post has an image :-
table(posts): (id,title,image)
I am trying to build an image gallery where user can select from previously uploaded photos, this is query i use to get user previous used images:-
        $images = Auth::user()->posts()
        ->where('image','!=','NULL')
        ->select('image')
        ->orderBy('created_at','desc')
        ->paginate(6);

        return response()->json($images);

The problem with above query is when the same image eg.(imageE.jpg) is used in many posts, the image get repeated in user gallery.
What should i add to the query above to retrieve only unique values
Comment: you have to generate a `unique` name for every file while saving it in the database
Comment: @Basharmal I am generating a unique name for a file, but i am not saving that file in separate table like (uploads) then referring it as FK in posts. Instead i am directly saving the file to posts table, so when user later want to create a new post i will show him option to select from previous uploaded photo
Answer: Try the following
$images = Auth::user()->posts()
        ->where('image','!=','NULL')
        ->select('image')
        ->distinct()
        ->orderBy('created_at','desc')
        ->paginate(6);

        return response()->json($images);

Adding the distinct function will change the query to not show multiples. More details can be found on https://laravel.com/docs/8.x/queries#select-statements

Laravel eloquent get index once


Need help with an Isoperimetric Problem. Am I doing the correct steps? What am I doing wrong?

Question: I have been given a Functional:
$$
I=\int^1_0 \left[(x_1')^2+(x'_2)^2-4tx_2-4x_2\right]dt
$$
where $x_1=x_1(t)$ and $x_2=x_2(t)$
And auxiliary constraint:
$$
\int^1_0 \left[(x'_1)^2-tx_1'-(x'_2)^2\right] dt = 2
$$
and boundary conditions:
$$
x_1(0)=x_2(0)=0\\
x_1(1)=x_2(1)=1.
$$
That gives me
$$
\begin{split}
L(t,x_1,x_2,x'_1,x'_2) &= (x_1')^2+(x'_2)^2-4tx_2-4x_2 \\
L_\mu &= (x'_1)^2-tx_1'-(x'_2)^2 \\
i &= 2 \\
\mu &= 1.
\end{split}
$$
I am given the Euler-Lagrange Equation:
$$
\frac{d}{dt}\left(\frac{\partial L}{\partial x'_i}\right)
 - \frac{\partial L}{\partial x_i}
 - \sum^p_{\mu=1} \lambda_\mu
      \left[\frac{d}{dt} \left(\frac{\partial L_\mu}{\partial x'_i}\right)
            - \frac{\partial L_\mu}{\partial x_i}
      \right]
= 0
$$
Where $\lambda_\mu$ are Lagrange multipliers, which due to the multiplication rule, is constant
Working through this, I am given 2 Equations for $x''_1$ and $x''_2$:
$$x''_1=\frac{\lambda}{2-2\lambda}$$
and
$$x''_2=\frac{2t-2}{1-\lambda}.$$
These are then simply integrated to find $x_1(t)$ and $x_2(t)$ respectively:
$$
\begin{split}
x_1(t) &= \frac{1}{2}\frac{\lambda}{2-2\lambda}t^2+at+b \\
x_2(t) &= \frac{1}{6}\frac{2}{1-\lambda}t^3
        - \frac{1}{2}\frac{2}{1-\lambda}t^2
        + \left(1 - \frac{1}{6}\frac{2}{1-\lambda}
                  + \frac{1}{2}\frac{2}{1-\lambda} \right) t
\end{split}
$$
in both $x_1$ and $x_2$, $\lambda \ne 1$. In order to get find $\lambda$, I'd need to plug bot $x_1$ and $x_2$ into the auxiliary constraint:
$$\int^1_0 \left[ (x'_1)^2-tx_1'-(x'_2)^2 \right]dt = 2.$$
But this I know will end up giving me a situation where $\lambda$ has more than 1 value.
Can anyone help me please?
Comment: Derivatives are squared. Why are two solutions from two $\lambda $ values not permissible?
Comment: Related post by OP: https://math.stackexchange.com/q/4467411/11127
Answer: In this answer let us outline a strategy:

The Euler-Lagrange (EL) equations for $x_1$ and $x_2$ yield families of solutions that depend on the Lagrange multiplier $\lambda$ and 4 integration constants.

Use the 4 boundary conditions to determine the 4 integration constants.

At this stage the pair $(x_{1,\lambda},x_{2,\lambda})$ is a 1-parameter solution with parameter $\lambda$.

Use the constraint to get an equation for $\lambda$. This turns out to be a polynomial equation in $\lambda$ with a finite number of real solutions $\{\lambda_1,\ldots, \lambda_n\}$.

Determine which pair $(x_{1,\lambda_1},x_{2,\lambda_1}), \ldots, (x_{1,\lambda_n},x_{2,\lambda_n})$ minimizes OP's functional $I[x_1,x_2]$.
Comment: I get value for $\lambda$ that are $a+bi$ in format...is that right
Comment: I updated the answer.


If an attribute has ranges as its possible values, is that attribute a numerical attribute or a categorical (ordinal categorical) attribute

Question: For example if I ask for someone's age, but instead of them being able to enter any natural number their responses are cropped and saved into bins such as "1-10" and "11-20" etc. Is this a numerical or a categorical attribute?
Asking as I'm confused whether its categorical nature overrides the fact that it is still sort of ratio-scaled.
Comment: Numerical variable is binned to make ordinal categorical variable.
Answer: Ask not what an attribute is--ask what sort of analysis makes sense :-).
Often it is helpful to think in terms of "This analysis treated attribute A as {ratio | interval | ordinal | categorical}."
For some attributes, there might be only one plausible answer.
For other attributes, like broad age bins, there might be two or more answers that could yield useful results.  Then you need to be able to explain why it might make sense to do the analysis in a particular way, and also be aware of the potential limitations or shortcomings of doing it that way.
For some helpful definitions.  Other search results are available.


What does this sharp sign with an arrow mean?

Question: I've seen this symbol (that looks like a sharp sign with an arrow sticking out of it) in some meme videos, but I don't know what it means:
Answer: It's an indication for a three-quarter-tone sharp.
Another common symbol for the same thing is what looks like a regular sharp sign with three vertical strokes.

(Image source: MuseScore 4)
A single quarter-tone sharp, using the same convention as the symbol in the OP, uses a downward arrow extending from the left-hand vertical stroke. Alternatively, a sharp-like symbol with a single strike can be used for the same thing.
A whole variety of additional quarter-tone accidental symbols can be found in

What do these unusual signs on key signature mean?,
What is this 4 sharp symbol and what does it mean?, and
What does this T-with-a-bar-in-the-middle accidental mean?.

The symbols for microtonal accidentals generally, and quarter-tones specifically, are not standardized.
Comment: The answer by @ElEctric is more correct as the symbol with the arrow has a specific meaning in that system (to adjust a Pythagorean semitone by a comma).
Comment: @Theodore the symbol is not unique to that system. H-E is the exception rather than the rule.
Comment: I thought the one with the arrow attached was exclusive to HE system because I'd never encountered it anywhere else, including the other questions linked in your answer (though one has a separate arrow above or below).  Do you remember where you might have seen it for some other 3/4-ish tone?
Comment: @Theodore The links I included were for related symbols, not the symbol in this post. I'll see if I can find a good example of the arrow symbol in a score
Answer: In extended Helmholtz–Ellis just intonation (HEJI) notation, this symbol means "sharp, raised by one syntonic comma". In other words, multiply the frequency of the note by 177147/163840, which is 2187/2048 (a Pythagorean chromatic semitone) multiplied by 81/80 (the syntonic comma). In HEJI normal notes are Pythagorean intervals (3-limit), the regular sharps and flats raise and lower by 2187/2048, and the arrows and other accidentals are used to get intervals with other primes in them (5, 7, and beyond).
In equal temperament tunings where sharps raise by three or more steps, you will need to attach arrows to sharps and flats in order to notate the full gamut. Here, a sharp-up means "sharp, raised by one step".
In 53-TET, for example, a sharp raises by five steps, so:

Natural: Root note
Natural-up: Raise by 1 step
Natural-double-up: Raise by 2 steps
Sharp-double-down: Raise by 3 steps (sharp lowered by 2 steps)
Sharp-down: Raise by 4 steps (sharp lowered by 1 step)
Sharp: Raise by 5 steps (one chromatic semitone)
Sharp-up: Raise by 6 steps (sharp raised by 1 step)
Sharp-double-up: Raise by 7 steps (sharp raised by 2 steps)
Double-sharp-double-down: Raise by 8 steps (double sharp lowered by 2 steps)
Double-sharp-down: Raise by 9 steps (double sharp lowered by 1 step)
Double-sharp: Raise by 10 steps (2 chromatic semitones)
Double-sharp-up: Raise by 11 steps (double sharp raised by 1 step)
Double-sharp-double-up: Raise by 12 steps (double sharp raised by 2 steps)

53-TET's flat side is notated in the same way, just in the opposite order:

Natural: Root note
Natural-down: Lower by 1 step
Natural-double-down: Lower by 2 steps
Flat-double-up: Lower by 3 steps (flat raised by 2 steps)
Flat-up: Lower by 4 steps (flat raised by 1 step)
Flat: Lower by 5 steps (one chromatic semitone)
Flat-down: Lower by 6 steps (flat lowered by 1 step)
Flat-double-down: Lower by 7 steps (flat lowered by 2 steps)
Double-flat-double-up: Lower by 8 steps (double flat raised by 2 steps)
Double-flat-up: Lower by 9 steps (double flat raised by 1 step)
Double-flat: Lower by 10 steps (2 chromatic semitones)
Double-flat-down: Lower by 11 steps (double flat lowered by 1 step)
Double-flat-double-down: Lower by 12 steps (double flat lowered by 2 steps)

If the sharps or flats raise by 7 or 8 steps, you'll need stacks of three arrows (or more), giving you accidentals such as a sharp-triple-up (double sharp, then raise by 3 additional steps) or sharp-triple-down.
See Xenharmonic Wiki's articles on notating microtonal EDOs using up/down notation for more info.
Comment: This article includes a reference to the full Extended Helmholtz-Ellis notation system: [The Extended Helmholtz-Ellis JI Pitch Notation](https://marsbat.space/pdfs/notation.pdf). See p. 18.  Maybe worth adding to your answer that the standard accidental symbols (with no extra marks) are used specifically to reference **Pythagorean** (3-limit just) tuning.


Selenium IDE - Placeholder

Question: Estou com dificuldades em automatizar um teste onde preencho um campo (placeholder) e salvo. Ao consultar o que salvei, verifico que a informação inserida no campo não foi feita.
<input id="nomeCliente" class="form-control ng-pristine ng-valid ng-touched" _ngcontent-c8="" maxlength="150" placeholder="Nome Cliente" type="text" style="background-color: rgb(255, 255, 255);">

Comment: Preenche o campo e quer testar o valor? Não entendi o placeholder.
Comment: @Aline Isso mesmo. Eu quero preencher o campo com valor. O campo é preenchido. No entanto, ao consultar depois, o campo não está com o valor.
Há algum outro comando sem ser o "Type"?
Comment: Adiciona seu código com selenium pra vermos.
Comment: @Aline Consegui com o comando "sendKeys".
No entanto, agora não consigo mais substituir uma palavra por outra no campo. Ela apenas vai sendo inserida na frente do já inserido.
Segue o comando (este não é placeholder, mas acontece a mesma coisa):

sendKeys
xpath=(//input[@type='text'])[10]
testeteste

sendKeys
xpath=(//input[@type='text'])[10]
teste

No aguardo!
Muito obrigado desde já.
Answer: Você pode estar pegando o campo errado para facilitar , você pode pegar este campo da forma a baixo:
driver.findElement(By.id("nomeCliente")).sendKeys("Nome Cliente");
desta forma você vai encontrar o elemento via ID e passar o que quer preencher com o sendKeys
Answer: Placeholder não tem nada a ver com o tipo do campo, o que você precisa trabalhar é com o input, placeholder é apenas uma propriedade de um input, sugiro que leia mais sobre isto no seguinte link
A respeito do seu real problema, é a forma com que está tentando enviar informações para o campo. Sempre que precisar inserir dados em um campo de texto(input) você deve usar o método sendKeys(), caso necessite limpar os dados antes de inserir(para que não seja concatenado valores) basta utilizar o comando clear().
driver.findElement(By.id("nomeCliente")).clear();
driver.findElement(By.id("nomeCliente")).sendKeys("Nome Cliente");

Selenium IDE - Placeholder


Uniqueness in Riesz Representation Theorem

Question: I have a slight problem with the proof of the Riesz Representation Theorem, particularly the uniqueness part.
Suppose we have a Hilbert space $H$ and a non-zero linear functional $f : H\rightarrow\mathbb F$. The proof I have seen begins as follows. Since $f$ is non-zero, there exists a $z\in(\ker f)^\perp$ such that $f(z) = 1$ and $\|z\| = 1$. It then proceeds to show that $f(x) = \langle x, z\rangle$ for all $x\in H$. This part is fine.
The uniqueness is confusing me though, because to me this seems to suggest that there is precisely one vector $z\in (\ker f)^\perp$ such that $f(z) = 1$ and $\|z\| = 1$. This seems unlikely to me. Is this true? Or am I thinking about this wrong?
Answer: Yes. If there were a second one ($\bar z$, say), you have
$$\langle z,x\rangle = \langle \bar z,x\rangle\quad \forall x$$
which implies
$$\langle z-\bar z ,x\rangle = 0 \quad \forall x $$
so in particular
$$\langle z-\bar z , z-\bar z\rangle =||z - \bar z ||^2= 0 \quad
\Rightarrow z=\bar z $$
Comment: But doesn't it seem strange that there is only one vector with that value under $f$? That seems quite strange to me. I'm not saying it's not true, I understand the proof, but I guess I'm looking for some intuition as to why there's only one $z$ with $f(z) = 1$ and $\|z\| = 1$.
Comment: +1 for the simplicity (oh and thank you!)
Answer: Concerning your question as to why this would be expected, maybe this will help.
$$ f : H \to \mathbb{F}$$
If $H$ is finite dimensional (dim = $n$), then by the Rank-Nullity theorem,
$$ \text{Null}(f) + \text{Rank}(f)=n$$
but $\mathbb{F}$ has dimension 1 so $\text{Rank}(f) \le 1$. Thus, ''most'' elements of $H$ are in the null space of $f$. In the infinite-dimensional case, all elements except those in the span of $z$ are actually in the null space of $f$.
Comment: Oh of course. Yeah that clears it up. Thanks for that.


OG view-content

Question: Can somebody tell me, how can i restrict viewing a certain-content type in an OG group to only group admin, so no other group members can see it.
And the 2nd question, if anibody knows; you can assign a field called group_audience. Is there an option, to not actually show the field, but assign a value of whatever group the user is in. Can I do this using hook_form_alter?
Answer: In your og node template you can use conditional php to show certain content.
<code><?php if (og_is_node_admin($group)):?>

 // Put whatever fields that you want viewable by the admin only

<?php endif;?>
</code>
Comment: So there is no module that would limit access for viewing the content?
Comment: The various content access modules would give you the ability to limit access for viewing specific fields and content types, but your assigning those permissions per role. I guess you could create a rule that adds a role to that use if they are a group admin, and then assign the appropriate content access permissions, but that seems like a lot of work compared to my answer.
Answer:
Question #2: if anibody knows; you can assign a field called group_audience. Is there an option, to not actually show the field, but assign a value of whatever group the user is in. Can I do this using hook_form_alter?

Check out this comment. It shows you how to create a module that will do that.

OG view-content


Let $S_1 \leq S_2 \leq..$ be a strictly increasing chain of simple subgroups of a group $G$. Show that $\cup_i S_i$ is a simple subgroup of $G$

Question: Let $S_1 \leq S_2 \leq..$ be a strictly increasing chain of simple subgroups of a group $G$. Show that $\cup_i S_i$ is a simple subgroup of $G$
So I understand that how to show that $\cup_i S_i \leq G$... I'm struggling to show that $\cup_i S_i$ is simple.
If $L \leq \cup_i S_i$ and $L \leq S_j$ for some $j \in \mathbb{N}$, then $L$ must not be normal because $S_j$ is trivial. But i'm not sure how to deal with cases $L \leq \cup_i S_i$ and $L \cap S_j \neq 0$ $\forall j$. Can it be shown that in this case $L = \cup_i S_i$?
Comment: Show that if $L\triangleleft \cup S_i$, then $L\cap S_j\triangleleft S_j$ for each $j$. Conclude that $L\cap S_j=S_j$ or $L\cap S_j = \{e\}$ for each $j$.
Answer: Let $S=\bigcup\limits_i {{S_i}} $. Assume that there exist a normal subgroup $N \triangleleft S$, then $N \cap {S_i} \triangleleft {S_i}$ for all i. But $S_i$ are simple, so $N \cap {S_i} = \{ 1\} $ or $N \cap {S_i} = \{ S_i\} $ i.e. $S_i \le N$. Now $N = N \cap S = N \cap \bigcup\limits_i {{S_i}}  = \bigcup\limits_i {(N \cap {S_i})} $, thus it is imposible that $N \cap {S_i} = \{ 1\} $ for all i or $S_i \le N$ for all i. This means that there exist $j$ and $k$ such that $S_k \le N$ and $S_j \cap N={1}$. Now we compare $S_i$ and $S_k$ to see a contradiction. If $j \le k$, then $S_j \le S_k$ and $S_j \cap N={1}$ and $S_k \le N$, a contradiction. If $k \le j$, doing similar leads to a contradiction.
Comment: Oh, Hakuna Matata, thank you, but how can you know that I am gonna take qualifiers?
Comment: Just a minor observation: You need to assume that $N$ is a *proper, non-trivial* normal subgroup of $S$. This assumption is used in the claim which starts " thus it is imposible that...".
Comment: Good luck on qualifiers bro!!!


Save button missing from content type edit form

Question: Here is what the bottom of my "leaflet" content type edit form (i.e. admin > structure > content types > leaflet > edit) looks like:

Here is what the bottom of my "testimony" content type edit form looks like:

Note that there are no save/delete buttons! Another of my content types has also now picked up this bug. This just happened. I have no idea why. I can't save changes! I tried flushing all caches and it didn't help. I'm an administrator and I have permissions for everything.
Why would this have happened and what can I do? Drupal 7.19.
Comment: Try disabling Diff, i18n and other modules that might be altering this form (modules that likely adding new elements to this form). there could be a module altering the form improperly.
Comment: Check in your content type, you probably selected require preview before publishing.
Answer: The problem was the i18n synchronize translations module. Disabling it fixed the problem. Of I have to immediately re-enable it afterwards since I actually use this module. So I filed an issue: http://drupal.org/node/2004260. Thanks to Ayesh K who gave me the idea in his comment on my question. Since it's not an answer I can't mark it correct, so I'm just answering here and will mark this correct.
Answer: Looks like an odd one, some form_alter or theme issue.
If you try a good admin theme like

Tao ( base admin theme )
Rubik ( admin theme )

Download both, enable and set admin theme in

/admin/appearance
ADMINISTRATION THEME
Choose "Default theme" to always use the same theme as the rest of the site. ( RUBIK )
Use the administration theme when editing or creating content ( CHECK )

The buttons should show up again


MySQL - Allow network connections to DB in CentOS 5

Question: Weird issue.
I've got a CentOS 5 server running, and I can't get MySQL to allow remote connections and local connections. IP Tables is setup correctly to allow the one remote server I need to connect to MySQL to do so.
skip-networking is commented out, and I don't have a bind address.
Comment: Can you open the socket?
Comment: Only locally.  I should also mention that I did set permissions to the DB in questions to allow a remote user.
Comment: Sounds like it's your firewall rules, if you're bound to the routable interface as you say.  Provide the output of `iptables -L -n`.
Answer: First off, run something like this to see what you have now:
<code> [root@cacti ~]# netstat -lnpt | grep `cat /var/run/mysqld/mysqld.pid `
 tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      2814/mysqld
</code>
If you don't see a line like that, check what command line options are being passed to your binary by running something like this
<code> [root@cacti ~]# ps auxfwww | grep mysql
 root     12754  0.0  0.0  61200   728 pts/1    S+   10:46   0:00  |                   \_ grep mysql
 root      2767  0.0  0.0  65976  1064 ?        S    Jul12   0:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --socket=/var/lib/mysql/mysql.sock --log-error=/var/log/mysqld.log --pid-file=/var/run/mysqld/mysqld.pid --user=mysql
 mysql     2814  2.1  0.8 348652 16848 ?        Sl   Jul12 464:20  \_ /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --user=mysql --pid-file=/var/run/mysqld/mysqld.pid --skip-external-locking --socket=/var/lib/mysql/mysql.sock
</code>
And lastly, show us your networking options from my.cnf.   By default mysql will bind to tcp 3306 on startup unless you tell it not to.  If you see anything inside the [mysqld] section related to networking you could try starting with just commenting it out.
Also it might help to check the log.  Its not very clear, but it will tell you if and when it binds to a port on startup like this
<code> [root@cacti ~]# grep port /var/log/mysqld.log
 Version: '5.0.45'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  Source distribution
</code>
Answer: OK! Thanks for the help, people. Looking over your comments made me go over everything with a fine-toothed comb. Turns out my rule in iptables wasn't in the correct spot. I reordered my rules and it worked
Answer: SE-Linux is disabled or well configured?
Comment: SE-Linux is disabled.
Comment: Run as root netstat -lntp | grep mysql. What do you see?
Answer: If it's not iptables or mysql privileges and the server is listening on a tcp socket (port 3306) with it's public IP-address or with 0.0.0.0 then I guess all that's left is the  tcpwrapper.
Check /var/log/auth.log (not sure if it's called that way on CentOS) and your /etc/hosts.allow/deny files.
If /etc/hosts.deny has ALL:ALL (which you should have) then add in /etc/hosts.allow:

mysqld: <remote IP-address>
Answer: Sounds like it's your firewall rules, if you're bound to the routable interface as you say. Provide the output of iptables -L -n.


Boost ASIO segfault due to socket no longer existing after a second connection is accepted

Question: I'm currently trying to get a chatroom type program working with boost::asio. In the current state, the server is able to accept connections from clients, and then the clients are able to send messages to the server (at which point, the server formats the message a little bit and then sends it to every client currently connected).
The problem I am having is as follows:
server starts
client 0 connects
client 0 sends a message
  (the message is received by the server and then sent back to client 0 who receives it correctly)
client 1 connects
client 1 sends a message
  (the message is received by the server and then sent back to client 0 and client 1 who both receive it correctly)
client 0 tries to send a message again
  (the message is received by the server and the server processes the header then attempts to call async_read again to read the body of the message, however the socket member variable for client 0 no longer exists and I get a segfault)

I find this really strange because the server still has a valid socket object for client 0 (otherwise it wouldn't be able to send client 1's messages to client 0).
Here is the relevant code:
tcp_connection class (where the segfault occurs)
#include <deque>

#include <boost/asio.hpp>
#include <boost/bind.hpp>

using boost::asio::ip::tcp;

class tcp_connection {
public:
    tcp_connection(tcp::socket socket_, int id, std::function<void (std::size_t, char*, std::size_t)> read_handler)
      : socket_(std::move(socket)), id_(id), read_handler_(read_handler) {
    }

    void start() {
        char first_message[] = "server: connected";
        net_message msg(first_message, strlen(first_message));
        send(msg);

        read_header();
    }

    void send(net_message msg) {
        bool write_in_progress = !write_messages_.empty();
        write_messages_.push_back(msg);
        if (!write_in_progress) {
            do_write();
        }
    }

    int get_id() { return id_; }

private:
    void read_header() {
        boost::asio::async_read(socket_, boost::asio::buffer(read_message_.get_data(), net_message::header_length),
          boost::bind(&tcp_connection::handle_read_header, this, boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
    }

    void handle_read_header(const boost::system::error_code e, std::size_t bytes_transferred) {
        read_message_.decode_header();
        read_body();
    }

    void read_body() {
        /*
        ######################
        THIS IS WHERE THE SEGFAULT OCCURS.
        socket_ is no longer valid for some reason
        despite socket_ still being valid for any async_write
        operations that need to be handled by the do_write() function
        ######################
        */
        boost::asio::async_read(socket_, boost::asio::buffer(read_message_.get_data() + net_message::header_length, read_message_.get_body_length()),
          boost::bind(&tcp_connection::handle_read_body, this, boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
    }

    void handle_read_body(const boost::system::error_code e, std::size_t bytes_transferred) {
        char body[read_message_.get_body_length()];
        memcpy(body, read_message_.get_body(), read_message_.get_body_length());
        // call the read_handler from the net_server object
        read_handler_(id_, body, read_message_.get_body_length());
        read_header();
    }

    void handle_write(const boost::system::error_code e, std::size_t bytes_transferred) {
    }

    void do_write() {
        boost::asio::async_write(socket_, boost::asio::buffer(write_messages_.front().get_data(),
            write_messages_.front().get_body_length() + net_message::header_length),
          [this] (boost::system::error_code ec, std::size_t /*length*/) {
              if (!ec) {
                  write_messages_.pop_front();
                  if (!write_messages_.empty()) {
                      do_write();
                  }
              } else {
                  std::cerr << "error with writing to client " << id_ << " with error code: " << ec << std::endl;
              }
          });
    }

    tcp::socket socket_;
    std::function<void (std::size_t, char*, std::size_t)> read_handler_;
    net_message read_message_;
    std::deque<net_message> write_messages_;
    int id_;
};

net_server class
class net_server {
public:
    net_server(boost::asio::io_context& io_context, std::size_t port,
               std::function<void (std::size_t)> accept_handler,
               std::function<void (std::size_t, char*, std::size_t)> read_handler)
      : io_context_(io_context), acceptor_(io_context, tcp::endpoint(tcp::v4(), 1234)),
        accept_handler_(accept_handler), read_handler_(read_handler)  {
            start_accept();
    }

    void send_to(std::size_t id, const char* body, std::size_t length) {
        net_message msg(body, length);
        connections_[id].send(msg);
    }

    void send_to_all(const char* body, std::size_t length) {
        net_message msg(body, length);
        for (int i = 0; i < connections_.size(); i++) {
            connections_[i].send(msg);
        }
    }

    void send_to_all_except(std::size_t id, const char* body, std::size_t length) {
        net_message msg(body, length);
        for (int i = 0; i < connections_.size(); i++) {
            if (i == id) continue;
            connections_[i].send(msg);
        }
    }

private:
    void start_accept() {
        acceptor_.async_accept(
          [this](boost::system::error_code ec, tcp::socket socket) {
            if (!ec) {
                std::unique_lock lock(connections_mutex_);
                std::size_t index = connections_.size();
                connections_.emplace_back(std::move(socket), connections_.size(), read_handler_);
                lock.unlock();

                connections_[index].start();
                accept_handler_(index);
            }
            start_accept();
          });
    }

    boost::asio::io_context& io_context_;
    tcp::acceptor acceptor_;

    std::vector<tcp_connection> connections_;
    std::mutex connections_mutex_;

    std::function<void (std::size_t)> accept_handler_;
    std::function<void (std::size_t, char*, std::size_t)> read_handler_;
};

main cpp program that sets up the server
#include <iostream>

class client {
public:
    client()
      : valid_(false)
    {}
    client(int id)
      : id_(id), valid_(true)
    {}

    const char * get_name() const {
        std::string str("Client ");
        str += std::to_string(id_);
        return str.c_str();
    }
private:
    int id_;
    bool valid_;
};

class chat_server {
public:
    chat_server(boost::asio::io_context& io_context, std::size_t port)
      : server_(io_context, port, std::bind(&chat_server::handle_accept, this, std::placeholders::_1),
        std::bind(&chat_server::handle_read, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {}

    void handle_accept(std::size_t client_index) {
        std::scoped_lock lock(clients_mutex_);
        if (clients_.size() != client_index) {
            std::cerr << "New client connecting at index " << client_index <<
                    " however, clients_ vector currently has size " << clients_.size() << std::endl;
            if (clients_.size() < client_index) {
                clients_.resize(client_index);
                clients_.emplace_back(client_index);
            } else {
                clients_[client_index] = client(client_index);
            }
        } else {
            clients_.emplace_back(client_index);
        }
        std::cout << "New client with id: " << client_index << std::endl;
    }

    void handle_read(std::size_t sender, char* body, std::size_t length) {
        // whenever the server receives a message, this function will be called
        // where clients[sender] will be the connection that sent the message
        // body will be a pointer to the start of the body of the message
        // and length will be the length of the body
        // we will process the message here and decide if / what to send in response
        // (for example, in a chat server, we'd want to forward the message to every client
        // with the name of the sender attached to it so that clients can update the chat dialogue)
        std::size_t sender_name_len = strlen(clients_[sender].get_name());
        std::size_t new_message_length = sender_name_len + length + 3;
        char new_message[new_message_length];

        sprintf(new_message, "%s: ", clients_[sender].get_name());
        memcpy(new_message + sender_name_len + 2, body, length);
        new_message[new_message_length - 1] = '\0';

        std::cout << new_message << std::endl;

        server_.send_to_all(new_message, new_message_length-1);
    }
private:
    net_server server_;
    std::vector<client> clients_;
    std::mutex clients_mutex_;
};

int main() {
    try {
        boost::asio::io_context io_context;
        chat_server serv(io_context, 1234);
        io_context.run();
    } catch (std::exception& e) {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

What I want is for my server class to maintain a list of tcp_connections which each represent a client that has connected to the server. When the server accepts a connection, a tcp_connection object is created for that connection and then that tcp_connection object starts an infinite asynchronous "read_header -> read_body -> repeat" loop. Whenever the server receives a message from any of the clients, it should format the message and then send it to every tcp_connection in the list.
Comment: Your `connections` vector is probably getting reallocated when you push a new connection which will change the address of existing connections and break the asio callbacks
Comment: Which line get segfault?
Comment: @FarhadSarvari in the read_body() function of the tcp_connection class
Comment: @AlanBirtles You're a genius!! **Thank you so much**. I doubt I ever would have thought of that, but changing connections to a `std::vector>` seems to have solved the issue.
Answer: Your connections_ member variable is being reallocated when you add new elements to it. In your various handlers in tcp_connection you are capturing this, when the vector is reallocated the value of this will change and your handlers will then try to operate on the old copy of the object causing undefined behaviour.
The simple solution is to make your connections_ vector a vector of std::shared_ptr.
It is also best practice to capture your object's shared_ptr in your handlers so that the object can't go out of scope before your callbacks execute. e.g.:
void do_write() {
    auto self = shared_from_this();
    boost::asio::async_write(socket_, boost::asio::buffer(write_messages_.front().get_data(),
        write_messages_.front().get_body_length() + net_message::header_length),
      [self, this] (boost::system::error_code ec, std::size_t /*length*/) {
          if (!ec) {
              write_messages_.pop_front();
              if (!write_messages_.empty()) {
                  do_write();
              }
          } else {
              std::cerr << "error with writing to client " << id_ << " with error code: " << ec << std::endl;
          }
      });
}

You'll need to derive tcp_connection from std::shared_from_this<tcp_connection> and make sure that you have created the shared_ptr before setting up any handlers (e.g. don't create handlers in the constructor).
Comment: I like to make `connections_ ` a container with reference stability. Like `std::list` (or `std::map` and friends)
Comment: I think I know what you're talking about in your last sentence, but could you provide an example of what that would look like?

Something like `auto self = shared_from_this();` `async_read(socket, buf, boost::bind(&callback, self, error, bytes));` ?


how do I render out all objects of a loop in a email template

Question: I'm trying to render all the product names, prices and quantities related to list_ordered_items into my email template. But the email contains just one product object detail instead of multiple product object details, I'm already looping through in the view! what's causing this? how do I fix this?
models
class Product(models.Model):
    name = models.CharField()
    final_price =  models.DecimalField()

class OrderItem(models.Model):
    product = models.ForeignKey(Product)
    quantity = models.IntegerField(default=0)

views
list_ordered_items = OrderItem.objects.filter(order__customer__user=request.user).select_related('product')

for loi in list_ordered_items:
    product_name = loi.product.name
    product_price = loi.product.final_price
    product_qty = loi.quantity
    context = {'product_name': product_name, 'product_qty': product_qty, 'product_price': product_price}

email template

{{product_name}}

{{product_qty}}

${{product_price | floatformat:2}}

current view:

should look like this:
Answer: In views.py, your current code just renames the variables on each iteration without saving them anywhere. Instead, you should put the loop in your template. For example,
in views.py:

list_ordered_items = OrderItem.objects.filter(order__customer__user=request.user).select_related('product')

context = {'list_ordered_items':list_ordered_items}

in yourtemplate.html:
(you can add your styling into the below code)

{% for item in list_ordered_items %}

  {{item.name}}

  {{item.price}}
  {{item.qty}}

{% endfor %}


How to interpret minimal sufficient statistics?

Question: I know the definition of minimal sufficient statistics is:
A sufficient statistic T(X) is called a minimal sufficient statistic if, for any other sufficient statistic T'(X), T(X) is a function of T'(X).
I want to know how to interpret this definition from function view. T is smaller than T', if T is a function of T'. What does that mean?
Comment: If $T$ is a function of $T'$ then you can calculate $T$ from $T'$ but not necessarily the other way round.   If you cannot then this suggests $T'$ may have more detailed information than $T$ (this is what makes $T$ *smaller*), but if $T$ is sufficient then the extra information is unnecessary to answer questions about the parameter you are considering
Answer: The notion of sufficiency is data compression.
A sufficient stat is a stat which in some sense contains all useful information about the sample $X$. (for estimating the true parameter, of course)
The definition of a sufficient stat is the following: the conditional distribution of X(sample) given T(X) does not depend on $\theta$, which is saying in more human language $T(X)$ is a summary of $X$. Immediately, we see each sufficient stat defines an equivalence relation on the sample space. Again, we're compressing data so a set of samples which yield repetitive information about the true parameter is compressed to a single equivalence class. For example, suppose we do $n$ iid Bernoulli $\theta$ trials, any set of samples such that each sample in the set has the same sum may be regarded as one sample for the purpose of estimating $\theta$.
We want maximal compression, which is a sensible way to understand the samples. All that the definition of MSufficientStat T says is if $T'(x) = T'(Y)$, then T(X) = T(Y). In order to define T as a composition of T' and a function g on the image of T', we may have to even define g in a funny way, but the point is it always exists. I guess we can think about the equivalence classes induced by a 'smaller' sufficient stat as grouping and merging the equivalence classes induced by a 'larger' sufficient stat.
Answer: If $T'\le T$, then there exists a surjective function from T to T'. For this you will need to recall what the definition of a function is. The right is not a surjective function, but the left is.

As an example, consider $\mathscr {Unif}(-\theta, \theta)$ with $\theta>0$. A sample has likelihood function of $f(x|\theta)=\frac{1}{2^n\theta^n}I(X_{(1)}\ge-\theta)I(X_{(n)}\le\theta)$ and so by the factorization theorem $T=\{X_{(1)}, X_{(n)}\}$ is a sufficient statistic for $\theta$. It is not minimal sufficient though, because $f(x|\theta)\propto I(-X_{(1)}\le\theta)I(X_{(n)}\le\theta)=I(\max\{-X_{(1)},X_{(n)}\}\le\theta)$. So $T'=\max\{-X_{(1)},X_{(n)}\}$ is a minimal sufficient statistic. There exists a surjective function from T to T', namely take the max of the components of T. But there is no surjective function from T' to T. In this sense you can construct T' from T but not the other way around. For this example, if you know the largest and smallest value, you know the largest absolute value. But if you know the largest absolute value, you don't necessarily know the smallest or largest value. (It could be either the largest or smallest value, and then the other will be unknown.)


Verificar se item existe no array

Question: Tenho este objeto.
stdClass Object
(
    [assessoria_id] => 1
    [id] => 3
    [nome] => wagner.fillio
    [cpf] => 00000000000
    [login] => wagner.fillios
    [ramal] => 123
    [pin] => 123
    [reset_senha] =>
    [sistema] =>
    [ativo] => 1
    [email] => Array
        (
            [0] => stdClass Object
                (
                    [pessoa_id] => 3
                    [id] => 13
                    [email] => firstname.lastname@example.com
                    [observacao] =>
                    [preferencial] => 1
                    [ativo] => 1
                    [origem_dados_id] => 1
                    [crud] => R
                )

        )

    [unidade] => stdClass Object
        (
            [_empty_] =>
        )

    [view] => stdClass Object
        (
            [equipe] => 61 a 90
        )

)

E esta função:
public function atualizar($where, $dados)
    {
        print_r($dados);
        $operador = [
            'ope_nome'        => $dados->nome,
            'ope_cpf'         => $dados->cpf,
            'ope_login'       => $dados->login,
            //'ope_senha'       => $dados->senha,
            'ope_ramal'       => $dados->ramal,
            'ope_pin'         => $dados->pin,
            'ope_reset_senha' => $dados->reset_senha,
            'ope_ativo'       => $dados->ativo,
        ];

        $this->db->update($this->tb_operador, $operador, $where);
        return $this->db->affected_rows();
    }

Preciso identificar se neste objeto, existe o item $senha. Posso fazer isto?
public function atualizar($where, $dados)
    {
        print_r($dados);
        $operador = [
            'ope_nome'        => $dados->nome,
            'ope_cpf'         => $dados->cpf,
            'ope_login'       => $dados->login,

            if(in_array($dados->senha, $dados)
            {
                'ope_senha'  => $dados->senha,
            }

            //'ope_senha'       => $dados->senha,
            'ope_ramal'       => $dados->ramal,
            'ope_pin'         => $dados->pin,
            'ope_reset_senha' => $dados->reset_senha,
            'ope_ativo'       => $dados->ativo,
        ];

        $this->db->update($this->tb_operador, $operador, $where);
        return $this->db->affected_rows();
    }

Comment: Utilize [isset](http://br.php.net/manual/pt_BR/function.isset.php)
Comment: Já tentei  e tenho isso: Message:  syntax error, unexpected 'if' (T_IF), expecting ']', sei que tenho que utilizar o if fora do array, assim teria que repetir o array $operador, tirando o item $senha.
Answer: Usando isset
public function atualizar($where, $dados)
{
    if (!isset($dados->senha)) {
        return 'Falta o campo senha';
    }

    $operador = [
        'ope_nome'        => $dados->nome,
        'ope_cpf'         => $dados->cpf,
        'ope_login'       => $dados->login,
        //'ope_senha'       => $dados->senha,
        'ope_ramal'       => $dados->ramal,
        'ope_pin'         => $dados->pin,
        'ope_reset_senha' => $dados->reset_senha,
        'ope_ativo'       => $dados->ativo,
    ];

    $this->db->update($this->tb_operador, $operador, $where);
    return $this->db->affected_rows();
}

Ou com empty que vai checar se é vazia:
public function atualizar($where, $dados)
{
    if (empty($dados->senha)) {
        return 'Falta o campo senha';
    }

    $operador = [
        'ope_nome'        => $dados->nome,
        'ope_cpf'         => $dados->cpf,
        'ope_login'       => $dados->login,
        //'ope_senha'       => $dados->senha,
        'ope_ramal'       => $dados->ramal,
        'ope_pin'         => $dados->pin,
        'ope_reset_senha' => $dados->reset_senha,
        'ope_ativo'       => $dados->ativo,
    ];

    $this->db->update($this->tb_operador, $operador, $where);
    return $this->db->affected_rows();
}

Poderia ser interessante usar Exceptions, assim por exemplo:
public function atualizar($where, $dados)
{
    if (empty($dados->senha)) {
        throw new Exception('Falta o campo senha');
    }

    $operador = [
        'ope_nome'        => $dados->nome,
        'ope_cpf'         => $dados->cpf,
        'ope_login'       => $dados->login,
        //'ope_senha'       => $dados->senha,
        'ope_ramal'       => $dados->ramal,
        'ope_pin'         => $dados->pin,
        'ope_reset_senha' => $dados->reset_senha,
        'ope_ativo'       => $dados->ativo,
    ];

    $this->db->update($this->tb_operador, $operador, $where);
    return $this->db->affected_rows();
}

E no momento de usar:
try {
    $objeto->atualizar({
       ...
    ));

    //... continua aqui se não falhar
} catch ($ee) {
    echo 'Erro: ',  $ee->getMessage(), "\n";
}

Se deseja adicionar o item basta usar assim:
public function atualizar($where, $dados)
{
    $operador = [
        'ope_nome'        => $dados->nome,
        'ope_cpf'         => $dados->cpf,
        'ope_login'       => $dados->login,
        'ope_ramal'       => $dados->ramal,
        'ope_pin'         => $dados->pin,
        'ope_reset_senha' => $dados->reset_senha,
        'ope_ativo'       => $dados->ativo,
    ];

    if (isset($dados->senha)) {
        $operador['ope_senha'] = $dados->senha;
    }

    $this->db->update($this->tb_operador, $operador, $where);
    return $this->db->affected_rows();
}

Comment: Obrigado. Deu certo.
Comment: Se $dados->senha NÃO existir, então o array $operador não deve conter o item $senha, caso contrário, o array $operador DEVE conter o item $senha
Comment: @WagnerFilho Você NÃO EXPLICOU isto na pergunta, de qualquer forma basta ajustar o IF criando um ELSE!
Comment: certo, eu só queria evitar de escrever o array duas vezes.
Comment: @WagnerFilho não é necessário escrever duas vezes. Estou editando a resposta... Pronto, resposta editada.
Answer: Você também pode utilizar o isset dessa forma:
public function atualizar($where, $dados)
{
    print_r($dados);

    $operador = [
        'ope_nome'        => $dados->nome,
        'ope_cpf'         => $dados->cpf,
        'ope_login'       => $dados->login,
        //'ope_senha'       => $dados->senha,
        'ope_ramal'       => $dados->ramal,
        'ope_pin'         => $dados->pin,
        'ope_reset_senha' => $dados->reset_senha,
        'ope_ativo'       => $dados->ativo,
    ];

    if(isset($dados->senha)) {
        $operador['ope_senha']  => $dados->senha,
    }

    $this->db->update($this->tb_operador, $operador, $where);
    return $this->db->affected_rows();
}

Dessa forma, caso $dados->senha exista, ele adicionará o índice "ope_senha" no array $operador

Verificar se item existe no array


Utility to determine application (or process) that displayed a (hung) window?

Question: Just curious if such a thing exists -
I have a hung window on my screen (you know, the kind that 'captures' images of the last window that you move over it), and I was wondering if anyone knows of a utility that will "work backwards" and help me determine what process/application on my PC created/owns the 'hung' window?
Obviously I appreciate that a restart of my PC would 'cure' this, but I don't want to have to go through that process, and I don't fancy playing roulette with running processes in task manager.
I've rummaged around the web and also searched the sysinternals website but nothing jumps out at me - I figured if someone knows, they're bound to be on here :-)
Thanks in advance...
Answer: You can use Process explorer from Microsoft sysinternals, it's free
Once launched, drag the target symbols from the menu bar upon your hanged windows. It will then highlight the process owning this window.
This is just a small hint, this tool is heavy can do a lot more..Learn it !
Answer: I second using Procexp, it can be packed on a flash drive and is immensely useful, and can even be setup to replace task manager, and has saved me tons of work, though really everything Mark Russinovich makes is quite awesome.
Comment: Even better, you can run the tools right from the SystemInternals site. Both via SMB \\live.sysinternals.com or HTTP http://live.sysinternals.com


How does showing $\tau(i) = j \implies a\tau a^{-1}(a(i)) = a(j)$ demonstrate that $a\tau a^{-1}$ has the same cycle type as $\tau$?

Question: I am completely new to group theory. My class is beginning to learn about centralizers, which, if I am not mistaken, is the set of all elements $x$ in a group $G$ that commute with a specified element $a$ in $G$. To help us calculate the cardinality of the centralizer of an element in $S_5$, my teacher has introduced the orbit-stabilizer theorem $|O_x| \cdot |G_x| = |G|$ (I still do not understand what an orbit or stabilizer refers to). He states that the cardinality of the centralizer of an element in $S_5$ is $|G_x|$ (because I am still confused as to what a stabilizer is, I am not sure how this is true) and that $|O_x|$ is the "conjugacy class" (I do not remember the exact terminology my teacher employed), so we can calculate $|G_x|$ by finding $\frac{|G|}{|O_x|}$.
To lead us to finding $|O_x|$, my teacher has stated that we have to show an equivalence between the "conjugacy class" and the cycle types of $S_5$; to do so, we must show  $\tau(i) = j \implies a\tau a^{-1}(a(i)) = a(j)$ for cycles $a, \tau$.
I understand that $a\tau a^{-1}(a(i)) = a\tau (a^{-1}a)(i) = a\tau(i) = a(j)$. However, how does showing this implication demonstrates that $a\tau a^{-1}$ has the same cycle type as $\tau$. Additionally, how does this relate to the supposed equivalence between the "conjugacy class" and cycle types of $S_5$?
Thanks in advance!
Comment: This is one of those things that seem obvious once you see it, but unclear at first. You should work out a few examples (in $S_8$ for example) be hand. The  you might understand what is going on.
Answer: Here we have the group $G$ acting on itself by conjugation. That is, for $g \in G$ and $h \in G$ have that $\alpha : G \times G \to G$ by $\alpha(g,h) = ghg^{-1}$.
Now for a given $h \in G$. The stabilizer $G_h$ are all $g$ such that $ghg^{-1} = h$ multiplying on the right by $g$ we get that $gh = hg$. Thus, the stabilizers are exactly the centralizers.
Now let $i_1 \to i_2 \to \ldots \to i_k \to i_1$ be a cycle in the cycle decomposition of $\tau$. Then by the above $a(i_1) \to a(i_2) \to \ldots \to a(i_k) \to a(i_1)$ is a cycle in the cycle decomposition of $a\tau a^{-1}$. Thus, they have the same same cycle type.
Now to complete the proof, we have to show that if $\tau_1$ and $\tau_2$ are two permutations with the same cycle type, then there exists a permutation $a$ such that $a\tau_1 a^{-1} = \tau_2$. But this also follows from your computation (just match cycles in the cycle types and define $a$ using that).
Thus, this tells us that the orbit of a permutation is exactly all permutations with the same cycle type. Thus, we can compute the size of the by orbit by counting. Thus, we get the size of the stabilizers and hence the size of centralizer.
Comment: Yes, that would be the stabilizer.
Comment: Thanks for the answer! I have a follow-up question about notation. If the stabilizer of an element $s$ in G is defined as Stab($s$) = $\{g \in G \mid s\cdot \alpha(g) = s\}$, then how should I notationally represent the stabilizer of an element $s$ in $S_5$ given that $\alpha(g,s) = gsg^{-1}$ operates on two elements $g, s$ Would it be Stab($s$) = $\{g \in S_5 \mid \alpha(g, s) = s\}$?
Comment: If you don't mind, I have some more follow up questions. How do we know "$a(i_1) \to a(i_2) \to \ldots \to a(i_k) \to a(i_1)$ is a cycle in the cycle decomposition of $a\tau a^{-1}$" and why must  $a\tau a^{-1}$ and $\tau$ have the same cycle type if this is true?
Comment: You showed that is $\tau(i) = j$, then $a\tau a^{-1} (a(i)) = a(j)$. Then we can apply that to $j$ and so on. The cycle type only depends on the sizes of the cycles, which would be the same due to this calculation.
Comment: Doesn't showing that $\tau(i) = j \implies a\tau a^{-1}(a(i)) = a(j)$ only demonstrate that $a(i)$ and $a(j)$ have the same cycle types, though?


Consulta SQL comparando dois campos da mesma tabela

Question: Tenho uma tabela no SQL Server e estou com dificuldade em fazer uma consulta.
Tenho uma tabela como esta:
alunos

ra     nome     serie     cod_curso
23     joão     1         EI
23     joão     2         EI
23     joão     3         EI
44     maria    5         EF
44     maria    6         EF
61     jose     10        CCO
32     ana      7         PED
78     ana      8         PED

Preciso selecionar o maior valor de serie para cada ra. O resultado da consulta deve ficar assim:
alunos

ra     nome     serie     cod_curso
23     joão     3         EI
44     maria    6         EF
61     jose     10        CCO
78     ana      8         PED

Se eu selecionar MAX(serie) mas não vai dar certo. Preciso selecionar MAX(serie) de acordo com cada ra, mas não sei como fazer isso.
Answer: Caso serie seja um numero a função Max() irá funcionar, não tem mistério.
select ra, nome, max(serie), cod_curso from alunos group by  ra, nome, cod_curso

Answer: Você pode fazer dessa forma:
select ra, nome, cod_curso, max(serie) as serie from alunos group by ra, nome, cod_curso

Outra forma sem precisar colocar todos os campos no gruop by:
select a1.* from alunos as a1
inner join (
   select a2.ra, max(a2.serie) as serie
   from alunos as a2 group by a2.ra
) a2 on a1.ra = a2.ra and a1.serie = a2.serie

Comment: Quando uso essa consulta, retorna este erro:

`Column 'alunos.nome' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.`
Comment: Acrescenta group by ra, nome, cod_curso no final da query.
Comment: Mas se minha tabela tiver 30 colunas vou ter q colocar as 30 no group by?
Comment: Sim, precisaria, mas ver a outra forma que eu coloquei com inner join.
Answer: Tente usar: "GROUP BY ra" no final de sua consulta.
O GROUP BY vai agrupar sua consulta pela coluna que você quiser, no caso a ra.
Answer: Não sei se estou confundindo aqui o que vc quer... mas vc tem duas ana com ra diferentes, sendo que vc quer somente uma ana não daria par asar o group by e ter o resultado que vc mostrou, mas se forem diferente seria mais fácil...
Veja o como fica abaixo para obter o que vc quer...
declare @alunos table
(
 ra int,
 nome nvarchar(100),
 serie int,
 cod_curso nvarchar(100)
)

insert into @alunos
values
(23,'joão',1,    'EI'),
(23,'joão',2,    'EI'),
(23,'joão',3,    'EI'),
(44,'maria',    5,    'EF'),
(44,'maria',    6,    'EF'),
(61,'jose',10,   'CCO'),
(32,'ana', 7,    'PED'),
(78,'ana', 8,    'PED')

select a.* from @alunos a
join(select nome,     max(serie) as serie,    cod_curso from @alunos
        group by nome,  cod_curso
    )d
on d.nome = a.nome
and d.serie = a.serie
and d.cod_curso = a.cod_curso

Se for o caso de pegar o maior ra vc pode fazer direto assim..
select max(ra) as ra, nome,     max(serie) as serie,    cod_curso from @alunos
group by nome,  cod_curso

Ou se a ana forem pessoas diferente use
select ra, nome,     max(serie) as serie,    cod_curso from @alunos
group by ra, nome,  cod_curso


Algebra representing the group scheme $\mathbb Z/ n\mathbb Z$

Question: as title says, I can not figure out the hopf algebra structure to put on $k^n$ to make it represent the group scheme $\mathbb Z/n\mathbb Z$. With the usual example of group schemes like $G_a$ or $G_m$ it is easy, but I can not use the same reasoning in this case it seems.
Help?
Thanks!
Answer: So the scheme $\mathbb{Z}/n\mathbb{Z}$ over a field $k$ is $\text{Spec}(k^{\oplus n})$. I'm going to label the points by some basis, say $e_0,...,e_{n-1}$.
The Hopf-algebra structure is a map $k^{ n}\rightarrow k^{ n} \otimes k^{ n}$ and we need that the preimage of the ideal $(e_i\otimes e_j)$ is the ideal $(e_{{i+j} \pmod n})$.
So define it like that, send the basis vector $e_i$ to the sum of basis vectors $\sum_{j,k} e_j\otimes e_k$ whenever $j+k= i \pmod{n}$.
Example: Label the points of $\mathbb{Z}/2\mathbb{Z}$ by $e_0,e_1$ corresponding to the prime ideals $(1,0)$ and $(0,1)$ in $k^2$. The Hopf algebra map is $k^2\rightarrow k^2\otimes k^2$ by $(0,1)\mapsto (1,0)\otimes (0,1) + (0,1) \otimes (1,0)$ and $(1,0)\mapsto (1,0) \otimes (1,0) + (0,1)\otimes (0,1)$. Now if I want to compute the product of two points like $e_0,e_1$ I need to look at the preimage of the ideal $(1,0)\otimes (0,1)$ under the Hopf algebra map. But this is just $(0,1)$ (which can be seen by observing the ideal generated by $(1,0)\otimes (0,1) + (0,1)\otimes (1,0)$ contains $(1,0)\otimes (0,1)((1,0)\otimes (0,1) + (0,1)\otimes (1,0))=(1,0)\otimes (0,1)$).
Constant group schemes aren't so fun to describe but you can generalize fairly easily to an arbitrary group in a way similar to the above.
For connected spectra $\text{Spec}(R)$ it's easy to see why the $R$-points $\mathbb{Z}/n\mathbb{Z}(R)$ are exactly $\mathbb{Z}/n\mathbb{Z}$.
Comment: If one is interested in more information, this is described in detail in Jantzen's book on algebraic groups.
Answer: The $n$th roots of unity are well known to be isomorphic to $\mathbb{Z}/n\mathbb{Z}$. The algebra you're looking for should be $\mathbb{C}[x]/(x^n-1)$
Comment: @leibnewtz The main problem is that when you start with an arbitrary field $k$ you don't have $n$th roots of unity. Reuns gets rid of this problem by describing exactly when the constant group scheme $\mathbb{Z}/n\mathbb{Z}$ is isomorphic to the $k$-group scheme $\mu_n$. But you can define constant group schemes regardless of base so these aren't the most general way to do it.
Comment: @leibnewtz: the name of the game here is to describe a Hopf algebra $H$ over $k$ with the property that if $A$ is a $k$-algebra with no nontrivial idempotents, then the group of algebra homomorphisms $\text{Hom}(H, A)$  (with group structure determined by the comultiplication of $H$) is always just the group $\mathbb{Z}/n\mathbb{Z}$, with algebra homomorphisms $A \to B$ inducing the identity. The group algebra of $\mathbb{Z}/n\mathbb{Z}$ does not solve this problem; instead the group we get is the group $\mu_n(A)$ of $n^{th}$ roots of unity. This group scheme is actually what is called the...
Comment: ...Cartier dual of the constant group scheme $\mathbb{Z}/n\mathbb{Z}$. In general, if $G$ is a finite group and we want to write down the corresponding finite group scheme, instead of taking the group algebra of $G$ we take what one might call the "group coalgebra" of $G$, namely $k^G$ with pointwise multiplication and comultiplication encoding the multiplication of $G$.
Comment: This doesn't represent the group $\mathbb{Z}/n\mathbb{Z}$ over an arbitrary field $k$.
Comment: @reuns This still doesn't represent the group $\mathbb{Z}/n\mathbb{Z}$ over an arbitrary field $k$...
Comment: Perhaps I'm mistaken. Should the coefficients be $\mathbb{Z}$?
Comment: $k[y,x]/(\psi_n(y),x^n-1)$ (if $char(k) \nmid n$) with $\psi_n$ the minimal polynomial of $\zeta_n$
Comment: @Eoin It would be helpful if you gave us an explanation of why this answer is incorrect
Comment: @reuns What does killing $\psi_n$ add?
Comment: @Eoin Thanks for the explanation!
Comment: @leibnewtz Sorry for my earlier brevity


How to Use If Within Input Div to show Message to User basis Database Value

Question: I am getting goof up, can someup help like
v_central_locking value can either be 0 or 1
Below is the code to display value - fetched from database
       <?php

Central Lock

                <input name="Central Lock" type="text" class="text-box" value="'.$rows->v_central_locking .'" readonly=""/>

       ?>

How to have it with If clause in div where if value is zero - it will display message Like
      if (v_central_locking==0)
      {
       echo 'Doesnt Have';
      }
       else
      {
       echo 'Yes a Feature';
      }

can someone help pls
Modified
   <?php

Central Lock

                    <input name="Central Lock" type="text" class="text-box" value="'. ($rows->v_central_locking == 0) ? 'Yes' : 'Yep' .'" readonly=""/>

     ?>

Answer: Try something like

Central Lock

    <input name="Central Lock" type="text" class="text-box" value="<?php echo ($rows->v_central_locking == 0) ? 'Nope' : 'Yep'; ?>" readonly=""/>

For reference: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
After your edit
You cannot simply put HTML code within PHP tags like that. You should add an echo and adjust your code like the following:
<?php
    echo '

Central Lock

            <input name="Central Lock" type="text" class="text-box" value="' . ($rows->v_central_locking == 0? 'Nope' : 'Yep') . '" readonly=""/>

    ';
?>

Comment: Thanks, edited my query - box is already surrounded with php tag - modified query - but its not helping - can you suggest an edit in the code


Diagonalizable vs Normal

Question: If I have real valued matrix $A$, are these two notions of being Diagonalizable and being Normal equivalent?
Comment: No. Any normal matrix is diagonalizable. The converse is not true.
Comment: @Artem Isn't $\begin{pmatrix} 0 & 1 \\ -1 & 0 \\ \end{pmatrix}$ a Normal matrix that isn't diagonalizable over the reals?
Comment: @DonAntonio I don't necessarily agree that is true. Furthermore, there have been people who argue that since OP specified real-valued, he is working with the reals as the base field. In any case, the real version is still slightly interesting to understand.
Comment: @CalvinLin, the usual meaning is "diagonalizable over the complex".
Answer: A real matrix is diagonalizable (over $\mathbb{C}$) by a unitary matrix if and only if it is normal.
But there are non-normal matrices that can be diagonalized by non-unitary matrices. For instance
$$\left[\begin{array}{cc}0 & 1\\2 & 1\end{array}\right] = PDP^{-1}$$
where
$$P = \left[\begin{array}{cc} -1 & 1\\ 1& 2\end{array}\right]$$
 and
$$D=\left[\begin{array}{cc} -1 &0\\0 & 2\end{array}\right].$$
Comment: Then what's the geometrical meanings of real diagonalizable matrices and real normal matrices?

Diagonalizable vs Normal


Why is the Belgium football team standing No. 1?

Question: I'm surprised that Belgium football team is standing No.1 in FIFA World Ranking. They have never won the World Cup. What made them standing ahead of Germany and other more well known teams?
Comment: See also http://sports.stackexchange.com/questions/3515/how-come-belgium-and-even-switzerland-are-atop-of-holland-on-fifarankings-for-wo/4217#4217
Answer: The FIFA world ranking is calculated based on results from all matches a team play: Qualifying matches, friendlies and championship matches. Matches from the last four years count, and it's weighted so that more significant matches and recent results count more. Also your opponent is weighted so that higher ranked opponents gives more points for a victory.
You can read more about it here:
wikipedia on FIFA world ranking
So why is Belgium on top?
The simple answer is that they have gotten the best results against fairly good opponents. If you look more at their results you will find that they have won their two last qualifying groups. They only lost against Argentina in 2014 WC and have performed well in their friendlies.
Belgium matches
At the same time there is no doubt that the ranking could be exploited by carefully selecting friendlies to get the highest possible ranking. I'm not claiming that Belgium have done this, but it happens and proves the difficulties in making a ranking.


Violin constantly going out of tune

Question: I bought a new violin about a month ago, and its always going out of tune. On average, it goes out of tune in about 2 days. Is this normal? Is there a good method to keep my violin tuned for long periods of time (maybe a month or two)?
Comment: I tune my violin every time I play - if I play in the morning and at night I tune twice in one day. Same with my guitars. As far as I know, that's perfectly normal.
Comment: I saw Isabelle Faust play her Stradivarius in a really hot concert hall last week, and it needed re-tuning after just one movement of Brahms' violin concerto. Definitely the result of poor air-conditioning, not a problem with the quality of the instrument.
Answer: As the comments point out, it is completely normal to re-tune multiple times in a day, or even in a performance.  In fact, every instrument in an orchestra checks tuning often. String instruments are sensitive to humidity and temperature, and to a lesser extent the bow-drag affects string tension.  Wind instruments change as the warm breath heats the physical material and changes the diameter of the bore or length of the tubing.
So pretty much everyone except the glockenspiel and vibraphone players (and cymbals...) have to retune.
EDIT
I am 50% chastened as the result of some searching thru research papers.  It was easy to find papers showing, correctly, that the air temperature strongly affects sound speed and thus note pitch as produced in a wind instrument, and that expansion/contraction effects of the instrument are miniscule by comparison.
What was difficult to find was a discussion of the variability of the musician's exhaled breath temperature.   I finally found a very nice bit of research (and I recommend reading the entire paper - if you can't access researchgate, perhaps a direct request to an author, email@example.com would work )  which states, in part,

As the air travels inside the instrument it encounters various
thermoviscous losses and consequently the temperature drops. This drop
across the instrument has been found to be high as 12C [19]. [emphasis mine]  As one
would expect, the extent of this effect depends on the instrument
itself. For example, in a cornetto using the mean temperature of the
air column as opposed to the temperature gradient along the bore
doesn't appreciably alter the pitch [20] and on the other hand, in an
experimental study of clarinets [21] a pitch difference of up to 8.5
cents was observed when the temperature gradient was replaced with an
averaged temperature. The heat diffusion is a much slower process than
audio acoustic vibrations, hence the air compression and expansion
resulting from oscillations behave less like an isothermal process and
more like an isentropic process [22], i.e. the temperature changes
will remain local, and hence it would be safer to assume a varying
temperature gradient as opposed to an averaged temperature within the
instrument.
Comment: Actually, wind instruments get higher in pitch, not lower, as they get warmer, even though the warmth increases their length.  This is because the increase in length is minimal and completely overwhelmed by the increase in pitch caused by sound traveling faster in warm air.
Comment: @ScottWallace  I'm highly skeptical of that claim, because the temperature of the air you exhaust from your lungs doesn't change during a performance (or if it does, you better call an ambulance).   BTW, I didn't make any claim as to which way the instruments went out of tune (up or down)
Comment: so why does the pitch of wind instruments go up as they get warmer?
Comment: @ScottWallace  [citation needed] . Seriously.  If you make that claim, please provide reference sources so we can review them.
Comment: well known facts: wind instruments get longer as they get warmer, and longer, ceteris paribus, means lower pitch.  But wind instruments go up in pitch as they get warmer.  Sound travels faster in warmer air. Thus, the effect of the warmer air is greater than the effect of the longer length. Do you have any other physical explanation for this?
Comment: @CarlWitthoft - I have to add an anecdote here about the speed of sound in a wind instrument.  I played recorder at a wedding once years ago just after having a good amount of champagne.  In the middle of a piece, playing the melody with no break, I felt a burp coming.  I managed to let it out slowly while playing without changing pressure much, but the pitch of the recorder went down a good half step for a couple seconds, due to the extra weight of the CO2.  Probably no one noticed but me.
Answer: Tuning multiples times per day is not uncommon (in fact most violins are in fact constantly tuned), but a violin requiring drastic retuning is most likely a result of several conditions, the most prominent being the weather. If a violin is kept in extreme cold and is introduced to warmer conditions, it will go out of tune. To prevent this from happening, try to keep your violin in a stable environment (temperature, humidity, etc.) when possible.
But no, tuning every few days is not out of the ordinary.
Answer: Violin tuning pegs are 'conical': they taper so that they can wedge into the tuning peg holes. It is the friction between the tapered peg and the  hole that stops the string from unwinding and going out of tune. When changing strings, make sure you wind the string around the peg so that it winds across to the fat side of the peg and makes contact with the side of the peg box. This prevents any lateral movement of the peg and keeps it tight in its hole. Check all your windings and make sure they are actually touching the side of the pegbox.
Comment: Somehow, I don't believe this will keep it in tune for as long as the OP would like. It'll help, but minimally. Keep it in a vacuum? (No, not a Hoover!)
Comment: Tim is right.  Yes, violins can get flat if the pegs slip.  But in my experience as an instrumentmaker, this doesn't happen all that often.  Most often, violins go out of tune because of changes in temperature, humidity, and stretching of strings.
Comment: This has nothng to do with tuning.
Comment: @Tim I don't think you meant that seriously, but – keeping it in a vacuum would actually be a horrible idea: that's the quickest way to dry out wood, and would likely make it crack in the process.
Comment: @CarlWitthoft - it actually has a lot to do with the tuning mechanism. However, it doesn't answer the question.
Comment: @Tim  well, yeah, but only pathologically.  99&44/100% of us string players have more trouble with pegs that **dont'** turn than pegs that slip :-(
Comment: @CarlWitthoft - joking apart, have you seen the geared tuners for violins (and cellos)? Once fitted, there's no visible proof they're not ordinary pegs.
Comment: @tim, I have, as well as the  cello C-peg that's "chopped off" so as not to whack us in the neck (requires separate hex key to adjust).
Comment: @CarlWitthoft - would they not be advantageous on any (stringed) instrument that needs constant tuning? They work well on guitars and basses.
Comment: @Tim, while working with students at the shallow end of the socio economic pool I have found that attention to string winding can transform a $99.99 violin into a $149.99 beauty within twenty minutes.
Comment: @Tim - geared pegs have the advantage of easy tuning and elegant appearance, and possibly (I'm not sure if it's audible) an acoustic advantage over the losses in conventional fine tuners.  Disadvantages: relatively expensive (around a hundred bucks for violin) and who know how long they will last?
Comment: @ScottWallace - that sort of price on a decent instrument (500+) seems reasonable for a vast improvement. We don't change those on guitars more that every 20 yrs minimum, so $5 a year isn't too bad. And I believe the originals can go back on if needed.
Comment: @Tim  "decent instrument $500"  ha ha you wish!  My first student-level cello was $3k.  Yes you can get them for less but you'd be better off with an orange crate.
Comment: @ScottWallace  Most top violinists I know use a fine tuner only on the top string; but nearly all cellists are fine with fully-integrated fine tuner&tailpiece assemblies (4 fine  tuners).

Violin constantly going out of tune


Safely conduct tests that require unplugging server

Question: So, basically I am testing and diagnosing my UPS's as well as the power sources (PSU) of my server. For that purpose I am powering down the server "the hard way", by unplugging it from the wall as to simulate a power loss.
This I have been doing like the way described, and has helped me find which UPS's are not working properly, as well as what PSU's need change (if the server shuts down then something needs change, else everything is ok). However, I am starting to worry that constantly unplugging my server and "killing" it the hard way may cause some damage to it or my data.
This leads me to my question: Is there an alternate way of performing these tests as to minimize the chances of damaging the server or its parts? Or there is no problem in doing what I am currently doing?
Again, I am trying to determine what power sources are defective (that is, UPS is ok but server dies anyway when unplugged). The UPS's I can test by their own as to avoid trying this method with the server, but I can't figure out how to test if my PSU's can handle fluctuations and spikes without actually trying them on a live server. Any guidance is greatly appreciated.

The server in question: HP ProLiant DL380 G7 server, with Intel Xeon. I also have it with RAID 1 level on its HDD's. It has Ubuntu 16.04.3 LTS running on its SSD's.
Comment: For anyone that is interested: I traced the problem to the PSU. Seems that "newer" PSUs need to have a UPS with 0ms transfer time (A.K.A. "on-line UPS"). Older PSUs don't need such precise transfer time. We got a proper UPS and the server no longer dies. [This answer](https://serverfault.com/a/199883/405302) and it's post helped me figure out :) Thanks to everybody
Comment: *Some background:* I noticed that when I got power surges or blackouts my server died despite being behind an UPS. This lead me to this testing and diagnosis, as I suspect something was wrong with my UPS's or my power supply units (turns out the problem seems to be with the latter).
Comment: Boot the server into BIOS, and leave it there while playing around with the power. Optionally remove the drives first, although idle disks shouldn't have any problems with unexpected power loss.
Answer: You have an HP ProLiant DL380 G7. Look at the following:
The Systems Insight Display (SID) shows the health of the internal components.

If you have an amber light on the either of the power supplies: shown on the SID or on the actual physical units, there's a problem.
You can also log into the server's ILO to check the Integrated Management Log. If you lose power suddenly, there may be an entry in the log indicating something like:
<code>- Server reset.
- Server power removed.
- Server power restored.
</code>
You have the option of not connecting both power supplies to the same UPS. Connect one to the power mains and observe the behavior.
Check the firmware on your system. G7 servers are old now, but by running Ubuntu, you're probably missing the HP reporting and management agents (they're optimized for RHEL/CentOS/VMware/Windows). You can download the full set of firmware for this model using this HP bootable DVD.
Comment: Many thanks for your answer. Indeed I have been.checking the LEDs, and when the power falls the PSU LEDs blink amber. Also, when reviving the server, they blink amber for a second before going green (specifically one PSU). Could it be further beyond my PSU and be something on the connectors the server has for such PSUs? I still am waiting for new PSUs I ordered to validate this hypothesis. Any other suggestions? I really appreciate your help
Answer: Do not unplug your UPS from the wall. I asked a similar question 9 years ago on this site and got the following answer from Evan Anderson:

The UPS is losing its electrical ground when you unplug it from the wall. While it's unlikely that anything would go wrong, the UPS designers "expect" that path to ground to remain available at all times, and if something did short during your test you might see sparks (smoke, flame, etc) when the electricity takes another path to ground. I've unplugged UPSs from the wall for testing before, but seeing a flash of "lightning" and hearing a loud "bang" coming out of a UPS during one such test gave me "religion" about not doing that again.

So if you are on a switched outlet, switch it off. If you're not on a switched outlet, consider flipping power to the breaker so that ground circuit stays connected.
As for disconnecting your servers by pulling the plugs, you shouldn't be doing any physical damage to the machines by doing that. You may corrupt non-battery-backed RAID arrays, or disrupt in-flight writes which can cause messy file systems and data loss - but your physical servers should be fine.
As for your actual problem, which is that during brownouts/blackouts/surges you still lose your servers upstream of your UPS there are a few things that might cause this:

If you have dual power supplies in your servers and one of them is on UPS and one is not (which is common enough), you may have a fault in the PSU switching inside the server
Again if you have dual power supplies, perhaps one of them is overloading and the server is shutting down for safety reasons
Depending on the type of UPS you have, it may no longer be functioning correctly. I had a site once that had constant brownouts - 20 to 30 times a day the power would drop below 200v (normally 230v) and the UPS would go into boost mode, and sometimes the voltage would spike to 250v and the UPS would go into buck mode. This shortened the life of the traditional UPS dramatically (I typically got around a year out of the UPS). We switched to a double-conversion UPS (also called an Online UPS) which solved this issue.
Comment: After some testing, seems that the problem are the UPS's... seems that they aren't supplying enough power that the PSU's require. Will try with a UPS that can handle such requirements and then inform here.
Comment: @DarkCygnus Take ewwhite's advice on board. I've known him for 5+ years and when it comes to HP stuff he's usually spot on.
Comment: So, we bought new UPS's and double checked they were appropriate for server usage, but still the problem persists... however... I now suspect it may have to do with the cable connecting one PSU to one UPS, it seems that it is not supplying enough current (the back led of one of the PSU shines less brightly than the other). Again, will update when I try it and tell you guys
Comment: Thanks a lot for this insight. After my tests I think that the problem is Option 1 (the switching), as I have tried several combinations (with, without UPS, one ppwer source with other without, etc...) and every time I experience shutdown. Also, as ewwhite indicated, I have seen the diagnostic LEDs, and when this happens the PSU LEDs blink amber for a brief moment (just when they die, and right for a moment just when pressing the power button to on). Any new suggestions based on this? Much thanks again
Comment: Will do :) thanks all for your support, will try these and if problems persist ping you or well turn it into another question. Cheers
Answer: Two notes:
One is that the best way to connect the UPS is through the dual power supply of your servers. If either the power or the UPS (battery) fails, everything stays up.
Second: except for what was said about loosing ground, it's not bad to unplug a server (if you don't care about data corruption), except for the SSD. Depending on which SSDs you may have, it may have a super capacitor to deal with it. But, losing power could damage blocks that are being erased or written.
Edit about the dual power supply: the correct way is one power supply in the wall, the other power supply through the UPS. Wrong would be to connect only one power supply, or connect them both through the UPS. If you do, failed UPS self-tests will interrupt power, and you can't turn it off to replace the battery.
Of course, one doesn't have that luxury with servers without dual PSU.
Comment: Hey Halfgaar, yes I do have SSDs as indicated on my post (at the very bottom), it is where my Ubuntu OS lives. Got 2 SSDs (for OS) and 6 HDD (raided)... and yes I usually remove the disks before attempting these tests, is that Ok also? I only conduct these tests when the server is not on use. Now, by connecting the UPSs the way you suggest, would you mind explaining how? Or better, what is the alternate way of connecting it? Thanks a lot for your help
Comment: @DarkCygnus Sorry, I missed you having SSDs. But yes, if you remove them (including disconnect power), that 100% safe. I edited my answer to describe the PSU wiring.
Comment: Thanks, much clearer now :) and yes this serves does have dual PSUs, so Ille try that you suggest. Thanks again.


lilypond : tuplet vs. times

Question: Reading some examples of lilypond codes, I sometimes see \tuplet and sometimes \times for engraving nuplets.
In the documentation, the french (using \times) and the english version (that uses \tuplet) differ on the command to use.
When I try to engrave this example (using lilypond-book), using the command \tuplet returns an error, that dissapear when I use \times...
My questions:
What is the difference between these two commands ? Which one is the right one to use? (Is the difference related to the lilypond version (v2.16 vs v2.18), or the system language?)
Answer: \tuplet is syntax introduced in version 2.18 (scroll down about 2/3 of the page when following the link).  The French documentation for version 2.18 indeed refers to \times at the top of the entry for tuplets.  This has been fixed in the documentation for version 2.19.
It is a bit unfortunate that the fix is not present in the documentation for 2.18.2.  The exact version where this has been introduced is 2.17.11.  The issue number in LilyPond's issue tracker is 3095 (omitting the link here because its current location is not supposed to be permanent).
If you need to be backwards-compatible, you should be using \times.  Once you upgrade, convert-ly should likely be able to convert to the \tuplet syntax which tends to be more logical to musicians who tend to think of trioles having 3/2 of the notes per beat rather than 2/3 of the duration.

lilypond : tuplet vs. times


How do I evaluate this:$\sum_{n=1}^{\infty}\frac{1}{n²}(e^x −1 −\frac{x}{1!} −\frac{x²}{2!}−\cdots\frac{x^n}{n!})$?

Question: How do i evaluate this sum :$$\sum_{n=1}^{\infty}\frac{1}{n²}(e^x −1 −\frac{x}{1!} −\frac{x²}{2!}−\cdots\frac{x^n}{n!})$$
Note: I 'd surprised if it is convergent
Thank you for any help.
Comment: Using Maclaurin Expansion: $$-e^x=\sum_{n=0}^{\infty}( −1 −\frac{x}{1!} −\frac{x²}{2!}−\cdots\frac{x^n}{n!})$$
Answer: The expression in parentheses converges to $0$ because $e^x=\sum\frac{x^n}{n!}$. Together with the fact that $\sum\frac1{n^2}$ converges absolutely, we conclude that your series converges as well.
Comment: this answer was my first attempt !!!!
Comment: @zeraouliarafik If that was your first attempt how come you'd be surprised if it is convergent?
Comment: sorry i posted the question with wrong way, and i mean n²(...) not 1/n² , now since it's answred i can't edit the question
Comment: @zeraouliarafik: Nitin's answer still works out basically the same if you have $n^2$ instead of $\frac{1}{n^2}$. If you use the integral form of the remainder, you can even get a closed form for the sum...
Answer: Fix $x \in \mathbb{R}$. Using the LaGrangian error term,
$$e^x = \sum_{k=0}^n \frac{x^k}{k!} + \frac{e^{c_n}\;x^{n+1}}{(n+1)!},$$
for some $c_n \in (0,x)$ or $c_n \in (x,0)$. Noting that $e^c$ is bounded in the interval, the convergence is the same as the convergence of the series
\begin{align*}
\sum_{n=1}^{\infty}\frac{x^{n+1}}{n^2(n+1)!},
\end{align*}
which converges for all $x \in \mathbb{R}$ by the ratio test.
Comment: The $c$ depends on $n$.
Comment: Made an even lazier answer.
Comment: Ah, right. But $c$ is between 0 and $x$, so it doesn't matter right? I suppose I can edit the proof by saying the final series is less than $e^x$ times the series?
Comment: Make that $\max(1,e^x)$ and you'll be fine.


Separar as informações do XML

Question: como eu faria para separar as questões conforme a disciplina de um arquivo xml no PHP? Ex.: Matemática resposta c, d e a...FIsica resposta c,d e E
<disciplina nome="Matemática">
         <questao numero="1" alternativas="A,B,C,D,E">
            <resposta>C</resposta>
         </questao>
         <questao numero="2" alternativas="A,B,C,D,E">
            <resposta>D</resposta>
         </questao>
         <questao numero="3" alternativas="A,B,C,D,E">
            <resposta>A</resposta>
         </questao>
      </disciplina>

      <disciplina nome="Física">
         <questao numero="1" alternativas="A,B,C,D,E">
            <resposta>C</resposta>
         </questao>
         <questao numero="2" alternativas="A,B,C,D,E">
            <resposta>D</resposta>
         </questao>
         <questao numero="3" alternativas="A,B,C,D,E">
            <resposta>A</resposta>
         </questao>
      </disciplina>

Answer: Use essa função para passar de xml para uma array em php
Vou fazer um update da função, pois encontrei um metodo de uma classe que não está aqui disponível. Então agora ela está completa.

/*
This function goes to the directory $pathDir, pass trough each all files inside it,
seeks for any file that math to the $searchString and reads it.
Return the content of all matched xml files within a php Array.
Ex:
We have inside the FTP the follow files genereted by a CronJob:
fileCarAudiRent2015.xml, fileCarAudiRent2016.xml, fileCarAudiSell2015.xm,
fileCarBMWRent2015.xml, fileCarBMWSell2016.xml, fileBoatWMBRent2015.xml, fileBoatWMBSell2015.xml,
fileBoatAudiRent2015.xml, fileBoatAudiSell2016.xml, ... .

We want to grab the content of all files that matches "Boat" string.
So, we need to do like this:
$arrInfo = read_XML_from_Folder_return_arrayAll("c:/Path_to_the_Folder","Boat");

We want to grab the content of all files that matches "Sell2015" string.
So, we need to do like this:
$arrInfo = read_XML_from_Folder_return_arrayAll("c:/Path_to_the_Folder","Sell2015");

We should inprove this function to match criteria like:
Give me all that has Sell AND 2015
Give me all that has Sell OR 2015
...
Give me all that has BMW AND 2015
*/

public function read_XML_from_Folder_return_arrayAll($pathDir,$searchString) {

$xml_array="";
$dir = new DirectoryIterator($pathDir); //http://php.net/manual/en/class.directoryiterator.php
foreach ($dir as $fileinfo) {
  if ($fileinfo->isFile()) {
      $fileName = $fileinfo->getFilename();
      //Macth rule
      $pos = strpos($fileName, $searchString);
      if ( $pos!== false) {//If match the sought string
        $filePath = $pathDir.$fileName;
        $xml = simplexml_load_file($filePath);
            $xml_array [] = unserialize(serialize(json_decode(json_encode((array) $xml), 1)));

           /* If needed
           $invoice_date = $xml_array["Documents"]["InvoiceDate"];
           $date = DateTime::createFromFormat('dmY', $invoice_date);//Formated date inside xml
           $year = $date->format('Y');//Desired output year
           $month = $date->format('M');//Desired output month
           */

      }//End of if ( $pos!== false)
  }
}
//Testing
echo "
";
  print_r($xml_array);
echo "
";

return $xml_array;

 }

Depois fica fácil. Faça um loop na sua array php e filtre dentro do loop.
Fonte
Comment: Funcionou... obrigado zwitterion

Separar as informações do XML