Porque não posso abrir a interface do MongoDB na porta : 28017?

Question: Instalei o mongo  na unidade C e fiz alguns testes de criação de dados e os persisti,depois consultei e lá estavam eles perfeitamente listados no prompt.
Ate ai tudo OK!
Abro o browser e digito localhost:27017 e aparece a mensagem de sinal de vida:
It looks like you are trying to access MongoDB over HTTP on the native driver port.

Mas quando tento localhost:28017 só vejo:
Esta página da web não está disponível

O que devo fazer?
Comment: Vc configurou o painel web do MongoDb para responder à porta 28017?
Comment: O que você está a tentar fazer Pena? Se quiser consultar dados via browser, deve adicionar o commando `--rest` quando executar o mongo. Depois disso pode aceder através de `http://localhost: 28017/mydb/mycollection/` e aplicar os filtros que forem necessários.
Comment: Ora essa Pena, experimenta parar o mongod e correr novamente algo assim: `mongod --dbpath /data/db --rest` ou então se não estiver a especificar nenhum argumento basta  fazer `mongod --rest`
Comment: @ThiagoLunardi Obrigado pela atenção. Como eu faria exatamente isso?Estou usando a versão 2.6.11
Comment: Nunca fiz, o caso é que, por padrão, o MongoDB configura seu websetup na porta 27017, não na porta 28017. Por isso vc recebe um 404, pois não há nenhuma aplicação web respondendo nesta porta.
Comment: @AndréVarandas Valeu amigo!!Sou iniciante no NOSQL,é que eu vi em um tutorial de instalação o cara navegando pela porta 27017 e tambem 28017,   e quando tentei fazer o mesmo, não consegui!! Ele não ensinou a fazer isso!!Onde eu digito o comando que você mencionou? Tennho dois terminais abertos um com o mongod e o outro com mongo onde eu trabalho visuallizando os dados!
Comment: @AndréVarandas Gênio, deu certo!! você poderia ter repondido a pergunta camarada!! Responda!! Arigato!,Sayonara!! –
Answer: MongoDB expõe um interface http, através do qual podemos verificar o seu status utilizando a porta 28017.
Para aceder via browser, o comando --rest deve ser passado ao mongod,
como por exemplo:
mongo --dbpath /data/db --rest
Em seguida abra o seu browser:
http://localhost: 28017/mydb/mycollection/
Importante:
Este interface nunca deverá ser utilizado em ambiente de produção.
Mais informação nessa página oficial Mongodb Http Interfaces
Answer: Edite o arquivo /etc/mongodb.conf
sudo nano /etc/mongodb.conf
acrescente a linha:
rest = true

reinicie o serviço
sudo mongod restart
Pronto. Agora a porta esta servindo REST.


How to read a csv file using pyarrow in python

Question: I have made a connection to my HDFS using the following command
import pyarrow as pa
import pyarrow.parquet as pq

fs = pa.hdfs.connect(self.namenode, self.port, user=self.username, kerb_ticket = self.cert)

I'm using the following command to read a parquet file
fs.read_parquet()

but there is not read method for regular text files (e.g. a csv file). How can I read a csv file using pyarrow.
Answer: You need to create a file-like object and use the CSV module directly.  See pyarrow.csv.read_csv
Comment: I think this function is for reading csv files from local drive, but I need to read it from HDFS. Where should I use the HDFS connection (fs in my cases)
Answer: You can set up a spark session to connect to hdfs, then read it from there.
ss = SparkSession.builder.appName(...)
csv_file = ss.read.csv('/user/file.csv')

Another way is to open the file first, then read it using csv.csv_read
Here is what I used at the end.
from pyarrow import csv
file = 'hdfs://user/file.csv'

with fs.open(file, 'rb') as f:
    csv_file = csv.read_csv(f)


What is actually involved in moving a piano?

Question: I'm aware that when moving a piano, especially a good one, care must be taken and using a proper mover is strongly recommended. But what is actually involved in moving a piano (other than lifting the thing up and making sure it can't slide around)? What makes it tricky and what damage can occur if it's not done properly?
As a side question, what counts as "moving" a piano? My neighbours have moved theirs from one wall to another in the past and I'm sure you sometimes see pianos wheeled onto stages so is literally any motion a problem or would sliding it be OK - for instance on a slippery laminate floor?
In my case, I am looking at collecting a 2nd hand piano (assuming it's OK), nothing fancy just a regular upright which has been well used but well cared for (by a music teacher). It's not expensive and I wonder if I should still get a professional - I'm not sure if anything needs doing to it before it can be transported.
Answer: Not only are pianos heavier than you probably think, but also the weight distribution is uneven. They are difficult objects to move safely.
This is what professionals do:
The piano is transported to the truck using a dolly — that is a flat trolley with big strong casters. For a grand piano, the legs get removed and the piano is balanced on its side. Uprights are generally moved whole — weakling amateurs might remove panels to make the piano lighter.
The piano is secured to the dolly with a locking strap, and a second strap known as a "hump strap" is used to pull, lift and steer from the front. Sometimes a "skid board" is used to protect the bottom of the piano from the ground.
Professional movers have rehearsed techniques for lifting the piano on and off the dolly, balancing it properly, and negotiating one or two steps. For longer flights of stairs, the piano is taken off the dolly, and lifted down.
For transportation in the truck, the piano is taken off the dolly, wrapped in padding, and strapped firmly to the side of the truck — removals trucks have fixtures in their walls, for straps. The front of an upright goes against the truck wall. The top of a grand goes against the wall. That is because against the wall is the most protected area — if something else goes flying inside the truck, it's more likely to scratch the back of the upright or the bottom of the grand.
As you can see, professionals take advantage of professional equipment — a dolly made for the purpose; a truck specially equipped for furniture removals. Improvising with other equipment is very risky - you don't want to wind up under a piano.
Source: Piano Moving Techniques. DIY Piano Moving Instruction from learntomove.com — I was surprised to find no mention of fixing/strapping the interior parts to prevent movement.
Comment: In addition to the legs they remove the pedals, the lid, the music stand, and some internal components. Each piece is carefully wrapped in padding and secured with tape.
Comment: Interesting. I've seen a dolly before when we helped a friend collect a free piano years ago - we rented a van with a lifting platform at the back. It sounds like for an upright piano of no particular value, it can be moved easily enough myself as long as access isn't a problem.
Comment: Well, follow that link, and follow the link there that says "Piano Moving Warnings". Having read that, I wouldn't move a piano myself.
Comment: If there is more than one step involved I agree with you, I need to check this out before deciding. I belirve it is flat at both ends.
Comment: The one thing I'd add to that writeup is that for exterior stairs use a ramp.  Either rent one along with the moving truck; or use a pair of 2x10 or 2x12 boards (one for the left set of wheels one for the right set).  It's much easier than trying to lift and carry something heavy up/down a flight of stairs.  (Source:  I spent a summer working for a household moving company and have helped move several upright pianos and organs in/out of my parents house.)
Answer: I assume you are talking about a grand piano.
It is possible to snap the legs off when pushing it, if a caster gets stuck.  It is rare that it happens, but you definitely want to make sure it NEVER happens to an instrument that weighs 300 pounds and costs $10,000 (or $100,000).
When professional movers move a piano from one side of a room to another, three of them pick it up an inch or so off the floor, carry it and place it down.  These are very strong people, obviously.  Six is a good number if it's just you and your friends, but be careful!
Stage pianos have special extra-large casters that if maintained well are safe for rolling the piano.  If your piano has been sitting in one spot for years, it's likely that the casters have seized up.  DON'T try to push it.
To move a piano from one house to another you need to cover it with a well-fitted blanket.  The pedal lyre and the legs come off and it goes onto a dolly resting on its left side.  Don't try this yourself if you haven't been shown exactly how to do it.
Comment: Actually, I meant a regular upright piano but your answer is very interesting so I'm glad it's there. I updated my question, sorry for the confusion.
Comment: Stage pianos often have additional strengthening to the legs too, & sometimes full cross-strutting or a trolley frame like http://www.sheargoldmusic.co.uk/grand-piano-a-frame/
Comment: What damage can you do moving an upright piano?  The answer is simple:  you can do a lot of damage to your floor!
Answer: If there's enough room, and you have enough people, no magic is involved.  If it has to be up-ended to negotiate doors and passages, a dolly, padding and experience are very useful.
Here's me and some friends transporting a piano around Colchester nearly 60 years ago.  The piano was just fine.
Comment: Love that picture!
Answer: Typically some parts are dismounted from a piano before transporting it (at least as soon as stairs are involved) to reduce the weight of the main chunk such as the front board below the keys. You may omit this if you are prepared to find new voluntaries for the next piano move, especially for older taller models. In any case afterwards a re-tuning is required.


Drupal 7 open image in colorbox when a "button" on the image is clicked, otherwise go to content

Question: I am using Drupal 7 and Colorbox module with Views 3.
In my view I have an image field. Right now based on my settings when I click the image it can either go to the content or open the image itself in Colorbox. What I want to achieve is maybe have a button (or a link?) at the bottom right corner of the image, when this button is clicked, image opens in Colorbox, if image itself is clicked, it brings you to the content (node page).
How can I achieve this?
Answer: In Drupal 7 you can achieve it by the following steps

Steps

Create a new VIEW and add the following fields
Background image : Add the image which you want to show as background image using imagestyle. Also add the link to the node using Link image to. And check Exclude from display.

Colorbox image : Add the image which you want to show inside COLORBOX using imagestyle. Dont add the link to this image and check Exclude from display

Image icon : Add the image which is used to render on the top of the background image  using imagestyle. And check Exclude from display.This image we will use in COLORBOX TRIGGER field.
Colorbox Trigger : Add this field and make Image icon field as the TRIGGER FIELD and Colorbox image as its CONTENT by use "Replacement patterns".

Custom text : Add Global: Custom text field and add the below html inside it and make sure you should replace [Background image] and [Colorbox Trigger field] using "Replacement patterns". It act like a container.

[Background image]

[Colorbox Trigger field]

OUTPUT

Note : Arrange the image icon above the background image using CSS
Comment: Thank you That's really helpful. But consider the fact that image size is always varying from image to image, and in this solution the image icon doesn't sit on the image with simple css. How can I solve this? Maybe I can give the image dimensions to the "image-wrapper" div. How I can achieve that? Thanks
Comment: YES, you should maintain proper image dimension. By using **Image Style** you can achieve it. You can go through [Working Image Styles](http://www.drupalgardens.com/documentation/working-image-styles) article
Comment: No what I meant was, I actually want my images to look in different sizes. So I scale them say by 400x400 (not Scale and Crop). In that case, the fullscreen button does not align with the image automatically because the div containing them is 300px, image is 200px, and the fullscreen button is at the end of 300pixels so 100px away from the image
Comment: First of all, for me if all the background images are in different sizes then it will look little bit of odd. If you want like that then you can add proper CSS, which will allow your button to be on bottom left only.
Comment: Thank you, I solved it with few CSS tricks (e.g. inline-block, text-align:center etc.) that I didn't fully understand before. Sorry for my CSS ignorance :)
Comment: That's great.. Enjoy :)

Drupal 7 open image in colorbox when a “button” on the image is clicked, otherwise go to content


C# Application with Jazzy UI

Question: I currently have a C Shell with a native browser (IE) Embedded Can i anyhow use WPF /WCF in this ?
 I am talking total Client Side not a launcher app ?
Wanted something cool and Jazzy with respect to UI
Comment: You wanted something *Jazzy*? Could you please give your definition of this adjective?
Comment: I'm confused exactly what you want? Do you want to develop a WPF application?
Comment: I dont want to create a WPF Application. I want to use WPF in my existing C Application which is embedding a browser.
Answer: A dotnet desktop application is always preferred for WPF and WCF. This can be done using C But it will be too much code and without any guarantee if the code will properly function or not.
So best is to create the dotnet application rather than C Application.

C# Application with Jazzy UI


Generating function for $\sum_{n=0}^{\infty} n^{p} x^n$

Question: I am trying to derive the generating function for $H(x,p) = \sum_{n=0}^{\infty} n^p x^n$
I am trying to solve it with the following logic:
(Edited now, trying a new framing)
Base case:
$$H(x,0) = \sum_{n=0}^{\infty} x^n = \dfrac{1}{1-x}$$
And
$$H(x,p) = x \dfrac{\partial}{\partial x} H(x,p-1)$$
Implying
$$H(x,p) = \left(x \dfrac{\partial}{\partial x}\right)^p \dfrac{1}{1-x}$$
Comment: So, you know that $H(x, p)$ is given by applying $x \frac{d}{dx}$ $p$ times to $\frac{1}{1 - x}$. So you want to know how to do this. It's easy to apply $\frac{d}{dx}$, which helps. It turns out that you can write $\left( x \frac{d}{dx} \right)^p$ uniquely as the sum of operators of the form $x^a \left( \frac{d}{dx} \right)^b$, and the effect of these on generating functions is easy to understand. So the problem is figuring out what coefficients are involved here.
Comment: So my current approach is going nowhere, basically? I wouldn't have ever recognized this "unique sum of operators" thing. My difficulty is that I can't see the differentiation as anything other than a function acting on $H(x,p-1)$ specifically and so I don't know how to peel that out of the fact that $x$ is being multiplied by it externally... and then all of this gets nested.
Comment: @user6596353 Are you Ok with our answers? Thanks.
Answer: Hint. An approach similar to what you are looking for. One may recall the general formula

$$
\sum_{n=0}^\infty f(n)x^n=\frac1{1-x}\sum_{n=0}^\infty \frac{f^{(n)}(0)}{n!}\:\omega_n\left(\frac{x}{1-x} \right), \quad |x|<1, \tag1
$$

with the polynomials $$
\omega_n\left(x \right)=\sum_{k=0}^n \begin{Bmatrix}n\\k\end{Bmatrix}k!x^k \tag2
$$ where $\displaystyle \begin{Bmatrix}n\\k\end{Bmatrix}$ are the Stirling numbers of the second kind.
The identity $(1)$ holds true for a vast class of regular functions $f$. A proof of $(1)$ can be found in Boyadzhiev's paper here.
Applying $(1)$ to $f(x)=x^p$, gives directly

$$
\sum_{n=0}^\infty n^px^n=\frac1{1-x}\:\omega_p\left(\frac{x}{1-x} \right), \quad |x|<1. \tag3
$$

Observe that we have
$$
\left(x \frac{d}{dx} \right)^p\frac1{1-x}=\frac1{1-x}\:\omega_p\left(\frac{x}{1-x} \right).\tag4
$$
Answer: Here's one way of describing the answer. First, the Stirling numbers of the second kind $S(m, k)$ have the property that
$$n^m = \sum_k S(m, k) (n)_k$$
where $(n)_k = n(n-1) \dots (n-(k-1))$. Second, the generating function of $(n)_k$ turns out to be relatively straightforward to write down: it is
$$\sum_n (n)_k x^n = k! \frac{x^k}{(1 - x)^{k+1}}.$$
You can derive this by repeatedly differentiating $\frac{1}{1 - x}$. It follows that
$$\sum_n n^m x^n = \sum_k S(m, k) k! \frac{x^k}{(1 - x)^{k+1}}.$$
This is in fact equivalent to a claim about how the differential operator $\left( x \frac{d}{dx} \right)^n$ expands, as mentioned in the comments.


Pure significance of line integrals of vector fields

Question: I can understand how the line integral of a scalar function has pure-mathematical significance, representing an area beneath a curve. But is there a pure significance to the line integral of a vector field? The only understanding I have of this is the physical example of work done on a moving particle. Thanks for any insight.
Answer: In general, the vector line integral of a vector field $\mathbf F : \mathbb{R}^n \to \mathbb{R}^n$ along a smooth oriented curve $C$ is a measure of how much the field $\mathbf F$ "flows" along the curve $C$. That is, if $\int_C \mathbf F \cdot d\mathbf s > 0$, the field $\mathbf F$ has a net flow with $C$, while if $\int_C \mathbf F \cdot d\mathbf s < 0$, the field $\mathbf F$ has a net flow against $C$. This is a physical interpretation you can give to the line integral of a vector field.
Comment: Isn't It same as the work done by this force in moving
a particle along a smooth curve C.
Comment: @puka: That's correct! It's also the interpretation in the OP. I think the OP was looking for a non-physical interpretation, hence this answer.
Comment: Thank you I am new to this subject.. Your answer is important for me
Answer: We may perform line integrals of vector fields around closed loops to gather information about sources of those fields.  This is true in electrostatics, where the line integral of the magnetic field about a closed loop produces an electric current within that loop.  In electrodynamics, line integrals of electric and magnetic fields about a closed loop produces the time rate of change of magnetic and electric flux, respectively, through that loop.
Comment: These are all applications.
Answer: Taking a line integral of a vector field along a curve is the same as integrating the corresponding $1$-form along that curve. So I guess it's an example of something quite pure, although this alone doesn't demonstrate significance.


How to make a self signed certificate openssl generated 4096 bit encrypted ssl certificate as trusted in ubuntu 10.04?

Question: I have an Apache server (2.4.3) with php5 and MySQL.
I generated a self-signed certificate, which I get a warning about, as the certificate is not trusted.
How do I resolve this?
Comment: Clarification needed - do you want to make *your* browser(s) trust the certificate, or make it a trusted certificate for the visitors to your website?
Answer: Instead of using a self-signed certificate, would you be open to getting a free SSL certificate from startssl.com?  That's what I've been doing for my personal web sites.
If that's not an option, you'll want to import either your self-signed certificate or the CA that you used to sign that certificate into your browser and set it to be trusted.  The method for doing this is browser-specific.
The page at http://tech.kaazing.com/documentation/jms/3.3/security/p_tls_clientapp.html has a section called "To Import Self-Signed Certificates into a Web Browser" that explains how to import certificates into several browsers.


How do I understand Pythagorean theorem

Question: 1) I understand the formula
$$\frac{BC}{AB}=\frac{BH}{BC},\ \frac{AC}{AB}=\frac{AH}{AC}$$
But I can't understand the formula is obtained
$$BC^2=AB\times BH \ \text{and}\ AC^2=AB\times AH$$
Why if somebody multiplies $AB * BH = AC^2$?

2) How is the formula obtained?
$$\frac{\sqrt{AB^2-AC^2}}{AC}=\sqrt{1-\left(\frac{AC}{AB}\right)^2}$$
I understand first part, but I can't understand second part
Comment: very much thanks for your help everyone
Answer: Each equation of the second pair is obtained from an equation in the first pair by "cross-multiplying,"  or equivalently getting rid of the denominators.
For example, start from $\frac{BC}{AB}=\frac{BH}{BC}$. Multiply both sides by $(AB)(BC)$. We get $(BC)(BC)=(AB)(BH)$.
Similarly, from $\frac{AC}{AB}=\frac{AH}{AC}$, by multiplying both sides by $(AB)(AC)$ we get $(AC)(AC)=(AB)(AH)$.
To finish, take the two equations $BC^2=(AB)(BH)$ and $AC^2=(AB)(AH)$ and add. We get
$$BC^2+AC^2=AB(BH+AH)=(AB)(AB)=AB^2.$$
Remark: As to your question 2, the quoted formula is wrong.  For example, let $AB=5$ and $AC=4$. For these values, the the left-hand side of your expression is equal to $\frac{3}{4}$. The right-hand side is equal to $\frac{3}{5}$.
Added: It turns out that OP wants to prove the correct
$$\frac{\sqrt{AB^2-AC^2}}{AB}=\sqrt{1-\left(\frac{AC}{AB}\right)^2}.\tag{1}$$
Rewrite the left side of (1) as $\sqrt{\frac{AB^2-AC^2}{AB^2}}$. Now divide term by term. We have $\frac{AB^2}{AB^2}=1$  and $\frac{AC^2}{AB^2}=\left(\frac{AC}{AB}\right)^2$, so we obtain the right-hand side of (1)/
The context is that if $\alpha$ is the angle at $A$, then
$\sin\alpha=\frac{BC}{AB}= \frac{\sqrt{AB^2-AC^2}}{AB}$. So on the left-hand side of (1) we have $\sin\alpha$, and on the right-hand side we have $1-\cos^2\alpha$.
Comment: What do you mean by second formula? Specifically, in which line of the answer is it? And nowhere in my answer is there an $AC$ in the denominator. I only did the calculation for one of the equations. But if it will make you more comfortable, I will type the other also.
Comment: sorry for the confusion,I am referring to the second formula in the question, $\frac{\sqrt{AB^2-AC^2}}{AC}=\sqrt{1-\left(\frac{AC}{AB}\right)^2}$,  I thought your answer helps in understanding the second one as well
Comment: I will write a remark about the second formula.
Comment: I think OP wanted to write $\frac{\sqrt{AB^2-AC^2}}{AB}=...$, but instead of AB he wrote $AC$, if the denominator is $AB$ then LHS=RHS
Comment: Possible. But if that had been OP's intent, the equality would be trivial, and OP would not have asked about it.  So maybe the typo came earlier, in the typing of the problem OP was asked to solve.
Comment: sorry. I got second formula from other book and didn't change the letters. The sense of second formula was obtained second part. I meant $sin$   $a = \frac{\sqrt{BC^2-AC^2}}{BC}=\sqrt{1-\left(\frac{AC}{BC}\right)^2}=\sqrt{1 - cos^2 a}$ I can't understand how from first part equation is getting second equation
Comment: The equality of the two expressions you now give is trivial, just square both sides. But you probably meant to type something else. So here goes. As to the sine of the angle $\alpha$ at $A$, using the labelling in your picture, it is $\frac{BC}{AB}$. By the Pythagorean Theorem we proved in the answer, we have $BC^2=AB^2-AC^2$, so $BC=\sqrt{AB^2-AC^2}$. Then $\sin\alpha=\frac{\sqrt{AB^2-AC^2}}{AB}$. By easy algebra (bring the bottom $AB$ inside the square root sign as $AB^2$) we get an equation like the one mentioned in the post, except the $AC$ on bottom left is $AB$.
Comment: All before $\sin\alpha=\frac{\sqrt{AB^2-AC^2}}{AB}$ I understand but after that I can't understand. Мy thoughts were so $\sqrt{\frac{AB^2 - AC^2}{AB^2}} = \sqrt {\frac{(AB - AC)(AB + BC)}{AB^2}}$ That's all I can't see how get $\sqrt{1 - (\frac{AC}{BC}^2)}$ Why $1 - (\frac{AC}{BC}^2)$
Comment: It is too hard to type in a comment. I will add to the answer. About $10$ minutes!
Comment: You are welcome.

How do I understand Pythagorean theorem


Parslet Alternatives Not parsing whole string

Question: I have the following specs
  it "parses a document with only an expression" do
    puts parser.document.should parse("[b]Hello World[/b]")
  end
  it "parses a document with only text" do
    puts parser.document.should parse(" Hello World")
  end
  it "parses a document with both an expression and text" do
    puts parser.document.should parse("[b]Hello World[/b] Yes hello")
  end

For the following Parslet Parser
class Parser < Parslet::Parser

rule(:open_tag) do
  parslet = str('[')
  parslet = parslet >> (str(']').absent? >> match("[a-zA-Z]")).repeat(1).as(:open_tag_name)
  parslet = parslet >> str(']')
  parslet
end

rule(:close_tag) do
  parslet = str('[/')
  parslet = parslet >> (str(']').absent? >> match("[a-zA-Z]")).repeat(1).as(:close_tag_name)
  parslet = parslet >> str(']')
  parslet
end

rule(:text) { any.repeat(1).as(:text) }

rule(:expression) do
  # [b]Hello World[/b]
  # open tag, any text up until closing tag, closing tag
  open_tag.present?
  close_tag.present?
  parslet = open_tag >> match("[a-zA-Z\s?]").repeat(1).as(:enclosed_text) >> close_tag
  parslet
end

rule(:document) do
  expression | text
end

The first two tests pass just fine, and I can see by puting them out to the command line that the atoms are of the correct type. However, when I try to parse a document with both an expression and plain text, it fails to parse the plain text, failing with the following error
Parslet::UnconsumedInput: Don't know what to do with " Yes hello" at line 1 char 19.

I think I'm missing something regarding defining the :document rule. What I want is something that will consume any number of in sequence expressions and plain text, and while the rule I have will consume each atom individual, using them both in the same string causes failure.
Comment: For RSpec, you generally use #should, and you probably don't want #puts.
Comment: It is using should, I just had some puts statements snuck in whilst I was experimenting.
Comment: Gotcha -- didn't see that.
Answer: What you were looking for is something like this...
require 'parslet'

class ExampleParser < Parslet::Parser
  rule(:open_tag) do
    str('[') >>
      match["a-zA-Z"].repeat(1).as(:open_tag_name) >>
    str(']')
  end

The open_tag rule doesn't need to exclude the ']' character as the match only allows letters.
  rule(:close_tag) do
    str('[/') >>
      match["a-zA-Z"].repeat(1).as(:close_tag_name) >>
    str(']')
  end

same here
  rule(:text) do
    (open_tag.absent? >>
      close_tag.absent? >>
        any).repeat(1).as(:text)
  end

If you exclude the open and close tags here.. you know you are only dealing with text.
Note: I like this technique of using "any" once you have excluded the things you don't want, but bare it in mind if you are refactoring later as your exclusion list may need to grow.
Note2: You could simplify this further as below..
  rule(:text) do
    (str('[').absent? >> any).repeat(1).as(:text)
  end

.. if you don't want any square brackets in your text at all.
  rule(:expression) do
    # [b]Hello World[/b]
    open_tag >> text.as(:enclosed_text) >> close_tag
  end

This becomes much simpler as the text can't include a close_tag
  rule(:document) do
    (expression | text).repeat
  end

I've added in the repeat you missed (as pointed out by matt)
end

require 'rspec'
require 'parslet/rig/rspec'

describe 'example' do
  let(:parser) { ExampleParser.new }
  context 'document' do
    it "parses a document with only an expression" do
      parser.document.should parse("[b]Hello World[/b]")
    end
    it "parses a document with only text" do
      parser.document.should parse(" Hello World")
    end
    it "parses a document with both an expression and text" do
      parser.document.should parse("[b]Hello World[/b] Yes hello")
    end
  end
end

RSpec::Core::Runner.run([])

Hope this give you some tips on using Parslet. :)
Answer: For your document rule you want to use repeat:
rule(:document) do
  (expression | text).repeat
end

You'll also need to change your text rule; currently if it starts matching it will consume everything including any [ that should start a new expression. Something like this should work:
rule(:text) { match['^\['].repeat(1).as(:text) }

Comment: I ended up coming to the same conclusion, ended up moving the expression | text decision into another rule called section and document called section.repeat(1)


time needed to move along a parametric curve with the speed specified by position

Question: Can someone please guide me to a resource that gives the time needed to move along a parametric curve, where the speed is specified by the position?
To be more specific, I have a 2D parametric curve $(x(u),y(u))$ with parameter values ranging from $u_{min}$ to $u_{max}$. I also have a function $s(u)$ (defined for the same $u$-values), that specifies the speed of the moving object along the curve. I would like to find the time it takes for a moving object to move along the curve.
Comment: Does the parameter u stand for time?
Comment: No, the parameter is not for time, it is just a general parameter to describe the curve.
Answer: Let $t$ denote time, $\ell$ denote arc length measured from $(x(u_{\min}), y(u_{\min}))$, and assume $u = \tau(t)$ expresses the parameter $u$ as a strictly increasing function of time. The chain rule gives
$$
s(\tau(t)) = \ell'(t) = \sqrt{x'(\tau(t))^{2} + y'(\tau(t))^{2}}\, \tau'(t),
\tag{1}
$$
or in Leibniz notation,
$$
s(u) = \sqrt{x'(u)^{2} + y'(u)^{2}}\, \frac{du}{dt}.
\tag{2}
$$
Assuming the speed $s$ is non-vanishing, rearranging (2) and integrating gives the time function in terms of the parameter $u$:
$$
t - t_{\min} = \int_{u_{\min}}^{u} \frac{\sqrt{x'(\xi)^{2} + y'(\xi)^{2}}}{s(\xi)}\, d\xi.
$$
In particular, the travel time for the entire curve is
$$
t_{\max} - t_{\min} = \int_{u_{\min}}^{u_{\max}} \frac{\sqrt{x'(\xi)^{2} + y'(\xi)^{2}}}{s(\xi)}\, d\xi.
$$


How to disable vertical / horizontal mouse movement in pygame?

Question: I want to prevent an object from moving vertically on the surface when moving the mouse around while horizontal movements will still be allowed.
How do I do that?
I have managed to let the object move around freely using:
<code>            if event.type == pygame.MOUSEMOTION:
            x, y = event.pos
</code>
But don't know how disable y from responding and allow only x to move.
Any advice will be appreciated.
BTW - I have read similar questions but nothing was related specifically to this issue.
Comment: Replace y with another letter, tada!
Answer: I don't remember much of Pygame, so I might be missing something, but it looks kinda obvious:
<code>if event.type == pygame.MOUSEMOTION:
    x = event.pos[0]
</code>
Answer: Hey Hi You can use this:
<code>#first  get the pos of mouse :
mousex, mousey = pygame.mouse.get_pos()
#then set the position:
pygame.mouse.set_pos(anyconstantvalue,mousey)
#make sure you set a constant for as ive mentioned above.
#this will allow you to move only in y direction. You can do the vice versa for x direction.
</code>


WordPress seems to have killed my Google Compute micro server by using too much memory

Question: Basically I booted a micro server on Google Compute running Debian 8 Jesse and installed MySQL and Apache2 on it just to run a little test site. I'm not developing the theme myself so I don't have any code - I just uploaded a theme I got on themeforest that uses WPBakery to build the pages.
I noticed from the beginning that it was slow - which was fine because this was just a little test server so that my client can see it. I was planning to move it to their current hosting once it's done. However I started to notice that when I was doing a lot of edits it would freeze up occasionally and I would get "Out of Memory" errors in my ssh terminal. Which was again fine - it's just a test site I needed for a couple days to customize the theme. They would usually resolve themselves.
However once the server got stuck and I had to reboot it. That should have been my first sign to at least snapshot the disk. But once it came back up everything was fine and it was even noticeably faster. I figured something got out of hand in the WP backend and restarting the server solved the issue.
I used it for another day or two - then it suddenly stopped working again. But this time I couldn't connect with ssh any more. I rebooted it using the Google Compute GUI but nothing didn't work at all. The usage graph is peaked - and when I log the serial output I get this:
Feb 25 12:47:05 test-wrs systemd[1]: Looping too fast. Throttling execution a little.

And it outputs this about every second or every other second. When I watch the output during boot it looks like it starts shortly after Apache boots. But there's some other messages about a failure above - I'm not really sure what is causing it.
Feb 25 12:44:48 test-wrs systemd[1]: Started ACPI event daemon.
Feb 25 12:44:48 test-wrs systemd[1]: Started System Logging Service.
Feb 25 12:44:48 test-wrs systemd[1]: Started Expand the root partition and filesystem on boot.
Feb 25 12:44:48 test-wrs systemd[1]: Started /etc/rc.local Compatibility.
Feb 25 12:44:48 test-wrs systemd[1]: systemd-logind.service: main process exited, code=exited, status=1/FAILURE
Feb 25 12:44:48 test-wrs systemd[1]: Failed to start Login Service.
Feb 25 12:44:48 test-wrs systemd[1]: Unit systemd-logind.service entered failed state.
Feb 25 12:44:48 test-wrs systemd[1]: Started LSB: Start and stop the mysql database server daemon.
[  OK  ] Started Permit User Sessions.
Feb 25 12:44:48 test-wrs systemd[1]: Started LSB: Start NTP daemon.
Feb 25 12:44:48 test-wrs systemd[1]: Started LSB: Apache2 web server.
Feb 25 12:44:48 test-wrs systemd[1]: dbus.service: main process exited, code=exited, status=1/FAILURE
Feb 25 12:44:48 test-wrs systemd[1]: Unit dbus.service entered failed state.
Feb 25 12:44:49 test-wrs systemd[1]: Started Permit User Sessions.
Feb 25 12:44:49 test-wrs systemd[1]: Time has been changed
Feb 25 12:44:49 test-wrs systemd[1]: systemd-logind.service has no holdoff time, scheduling restart.
Feb 25 12:44:50 test-wrs systemd[1]: Looping too fast. Throttling execution a little.
Feb 25 12:44:51 test-wrs systemd[1]: Looping too fast. Throttling execution a little.
Feb 25 12:44:52 test-wrs systemd[1]: Looping too fast. Throttling execution a little.
Feb 25 12:44:54 test-wrs systemd[1]: Looping too fast. Throttling execution a little.

And I have no idea what to do here. I read that this is sometimes cause by overuse of memory which would correlate with the issues I had before - so I tried snapshotting the disk and booting it on a higher RAM server but it does the same thing no matter how high I set the RAM. And I can't ssh in to investigate more.
Does anyone have an idea what the issue might be or how to resolve it? I'm stuck and I'd really like to not have to start from scratch again and remake all the stuff I did before. If I can at the least get a dump of the MySQL database I'd be happy - but the database isn't configured to accept remote connections because I had no reason to do that. So I have to get into it somehow.
Answer: As to why your setup goes out of memory, we can only speculate. The fact, that the issue does not disappear with a bigger VM, suggests, that this is caused by some configuration or setup issue.
You might try to run the Wordpress setup preconfigured by Google, which can be found under "Deployment Manager" "Cloud Launcher". You can run them on any size of VM and from experience I can assure you that the basic installation does not go out of memory.
To recover your database, you could do the following:
1. shut down the VM from Developers Console
2.take a snapshot of the disk
3. attach the snapshot as additional disk to a working VM (choose option: create a new disk -from snapshot)
Perform above steps in Developers Console, and do not forget to click the "save" button in the end.
Now click the "ssh" button of the new VM and
4. mount this additional disk on the command line :
sudo mount /dev/sdb1 /mnt
Note: you could do these steps from the VM you spin up via Cloud Launcher, and copy the files directly to this VM.
Comment: Mounting as an additional disk was a good idea - wish I thought of that. I seem to have been able to recover the data so thanks!


validate form with checkform session?

Question: How to validate form value ?
step my code working

fill user like "aaaa" in input create user. and click "Check user" button
fill name and last name in input
click "OK" button

Why checkform wiill show "Please enter User name." ??
test_1.php
    <?PHP
    session_start();
    session_destroy();
?>

<form id="ff" name="form_check_user" method="post" action="test_2.php" ENCTYPE = "multipart/form-data">
Create User : <input type="text" name="user"/>
    <input type="submit" name="check_user" value="check user" />
</form>

<form name="finished" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);">
    Name : <input type="text" name="name"/>
    Last Name : <input type="text" name="last_name"/>

    <input type="submit" name="submit" value="OK" />
</form>

test_2.php
<?PHP
    session_start();
     $_SESSION["check"] = $_POST['user'];
?>

Answer: That is because you are accessing an undefined constant on your session variable like this..
if ("<?php echo $_SESSION[check];?>"  == "") { // See it is just check , you need to wrap it around quotes.

It should be
if ("<?php echo $_SESSION['check'];?>"  == "") {

validate form with checkform session?


Jquery function calling php file not working

Question: Please find my code below...This is basically 2 files javascript and php file.
I am trying to call the php file from the javascript. But I get a 500 internal server error when the jquery function is called.
When I checked chrome web developer tools, I can see that the execution is stopping in one of the jquery library functions. But I could be wrong in that judgement since I am not totally familiar with developer tools.
Could you please let me know whats going wrong?
validation.js
function validateName(){
var uname=name.val();

$.post('validate.php',{names:uname},function(data){

if(data!=0){

name.removeClass("valid");
nameInfo.removeClass("valid");
name.addClass("error");
nameInfo.addClass("error");
nameInfo.text("This name is already registered");
state=true;
}else
{
name.removeClass("error");
nameInfo.removeClass("error");
name.addClass("valid");
nameInfo.addClass("valid");
nameInfo.text("Name is available");
state=true;
}
});

return state;
}

$( "#send" ).click(function() {
var all = $("form").serialize();
$.ajax({
url: 'insert.php',
type:'POST',
data: all,
dataType: "text",
success: function (response) {
if (response==1){
document.location.href="/view.html";
}else{
alert("you have errors");
}
}
});

insert.php
<?php

$name=$_POST['name'];
$email=$_POST['email'];
$pass=$_POST['pass1'];

mysql_connect("localhost","root","root") or die("we couldnt connect");
mysql_select_db("swiftyfood");
mysql_query("INSERT INTO userCredentials(userid,name,password) VALUES('',
'$name','$pass1')");
echo 1;
?>

Validate.php
<?php
echo "hello";
ini_set('display_errors', 1);
error_reporting(E_ALL);

$name=$_POST['names'];
$email=$_POST['emails'];
$pass=$_POST['passws'];

if ($name!=""){
mysql_connect('localhost','root','root') or die("we couldnt connect");
mysql_select_db("swiftyfood");
$username=mysql_query("select name from userCredentials where
name='$name'");
$count=mysql_num_rows($username);
if (count!=0){
echo 0;
}else{
echo 1;
}
?>

image of chrome developer tools.
Comment: A 500 error indicates that you sent something bad to the PHP and it reacted by failing. Look at your PHP error logs for more insight to the problem.
Comment: [Little Bobby](http://bobby-tables.com/) says [your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe!
Comment: Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html).
Comment: Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat).
Comment: I don't see the variable `pass1` being defined anywhere. Did you mean to write `pass` instead?
Comment: All of your PHP files are returning a `500` error. What do the logs say about it?
Comment: Always check the error logs - it will give you exact line numbers, telling you what you did wrong. Basic problem solving.
Answer: Here's the issues I've found:
insert.php
Change $pass1 to $pass
mysql_query("INSERT INTO userCredentials(userid,name,password) VALUES('',
'$name','$pass')");

validate.php
You're missing the closing } for 'if ($name != "") {'
if ($name!=""){
    mysql_connect('localhost','root','root') or die("we couldnt connect");
    mysql_select_db("swiftyfood");
    $username=mysql_query("select name from userCredentials where
name='$name'");
    $count=mysql_num_rows($username);
    if (count!=0){
        echo 0;
    }else{
        echo 1;
    }
} // This was missing


How to prove that $\lim_{n\to \infty}\sin(n!)$ does not exists?

Question: The continued fraction of $\pi$ has not yet be known.  I could not see the distribution of the $\{\frac{n!}{2\pi}\}$ where $\{x\}=x-\lfloor x \rfloor$.
Is there any idea how to find two convergent subsequences with different limits?
Comment: Duplicate of a question that was never adequately answered in the first place.
Comment: @PrithiviRaj: I'm pretty sure the idea you had when you posted that hint is missing the main problem here.
Comment: Hint: $-1\le \sin(n!) \le 1$
Comment: I think the best bet here is to use the Cauchy Convergence criterion.
Comment: @Hurkyl Hmmm... I dont follow the primary answer, sadly.  And it isnt even the same question, but close.  Im still leaning toward the Cauchy convergence. Pick the right trig identities and the right choices of m,n>N, it should simplify... maybe?
Answer: This answer to a closely related problem implies that, while the limit almost surely does not exist, current mathematical knowledge is unlikely to be capable of proving it.
Answer: I think I can show that
the only possible limit is zero.
I'll show my ideas
and hope that
they might be useful.
If $L = \lim_{n \to \infty} \sin(n!)
$ exists,
then,
for large enough $n$,
$(n+1)! \approx n!+2k_n\pi
$
where $k_n$
is an integer that
depends on $n$.
Then
$k_n
\approx \frac1{2\pi}((n+1)!-n!)
= \frac1{2\pi}nn!
$.
Similarly,
$k_{n+1}
\approx \frac1{2\pi}((n+1)!-n!)
= \frac1{2\pi}(n+1)(n+1)!
$
so
$\begin{array}\\
k_{n+1}-k_n
&\approx \frac1{2\pi}((n+1)(n+1)!-nn!)\\
&= \frac1{2\pi}n!((n+1)(n+1)-n)\\
&= \frac1{2\pi}n!(n^2+n+1)\\
&= \frac1{2\pi}n!(n^2+n)+\frac1{2\pi}n!\\
&= \frac1{2\pi}nn!(n+1)+\frac1{2\pi}n!\\
&\approx k_n(n+1)+\frac1{2\pi}n!\\
\end{array}
$
so
$\frac1{2\pi}n!
\approx k_{n+1}-(n+2)k_n
$.
Therefore
$n!/(2\pi)$
is close to an integer,
so $\sin(n!) \approx 0$.
Therefore the only possible limit
is zero.
If we can choose $n$
so that
the fractional part of
$\frac1{2\pi}((n+1)!-n!)
\approx \pi/2
$,
then
$\sin(n!)$ and
$\sin((n+1)!)$
will not be close
so the limit can not exist.
This last, of course,
does not depend on the limit being zero.
I don't know
where to go from here,
so I'll stop.
Comment: I know there are lots of problems with my attempt. I just wanted to put some ideas out there.
Comment: There is a complication here; this argument attacks the issue of whether $n!$ converges to a point in the circle $\mathbb{R} / 2 \pi$. The limit of $\sin(n!)$, unfortunately can exist in more general situations, such as if $n!$ bounces between two angles with the same sine.
Comment: A more serious issue lies with the claim $\frac{1}{2\pi} n n! (n+1)$ should approximate $k_n (n+1)$; why must the error between $k_n$ and $\frac{1}{2 \pi} n n!$ be asymptotically $o(\frac{1}{n})$?


How to filter the xcodebuild command line output?

Question: Running xcodebuild from the console will bring you very verbose output and I wasn't able to locate any options for limit its output in order to display only warnings and errors.
I'm looking for a way to capture the xcodebuild output and filter it. It would prefer a Python solution that will work with pipes but I'm open to other approaches as long they are command line based solutions.
Are any tools that are already able to do this?
Answer: Use xcodebuild -quiet.
According to the xcodebuild man page:

-quiet : Do not print any output except for warnings and errors.

Bonus: No other tools necessary! (Although I also like xcodebuild | xcpretty)
I build with Travis CI, which complains after 4 MB of logs. This argument solved the problem.
Comment: This should be marked as correct answer. Thank you!
Comment: Unfortunately, works only for Xcode 8+. For previous Xcodes see answer by @rosejn.
Answer: There's a Ruby gem called xcpretty.
It filters the output of xcodebuild and also provides different formatters and coloring.
UPDATE: As Mike Hardy correctly states in the comments to this answer, xcpretty is no longer maintained.
Comment: please vote up this answer, this tool is awesome and solve the problem much better than grep
Comment: xcpretty is abandoned and no longer maintained. `-quiet` is the way
Comment: This tools is fantastic! Why I haven't discovered it before?!
Comment: xcpretty is a useful tool to be used in conjunction with xcodebuild.
Comment: @Koraktor- Can I use it with ANT exec task (for xcodebuild) as an argument?
Comment: @RashmiRanjanmallick Provably, but I'm not an Ant user.
Comment: Ok. Let's keep aside the ANT thing. How to use this for command line builds via xcodebuild archive?
Comment: XCPretty is really cool but sometimes crashes with error "NON-ASCII symbol".
Comment: @MikeHardy [`xcbeautify`](https://github.com/tuist/xcbeautify) might be what you want.
Comment: indeed! Even xcbeautify was abandoned temporarily but now it has new maintainer(s) and is what I am currently using. It looks like it should keep working for a while
Answer: This isn't sufficient for me.  Piping to /dev/null will just show you that a build failed, but you don't see the reason(s) why.  Ideally we could see just the errors and/or warnings without all of the successful compiler commands.
This basically does the job:
xcodebuild | grep -A 5 error:

Comment: or  `egrep '^(/.+:[0-9+:[0-9]+:.(error|warning):|fatal|===)' -`  to also get lines saying what xcodebuild is about to do.
Answer: To only see the error output messages, redirect the standard output to /dev/null (a special file that works as a black hole) like this:
xcodebuild > /dev/null
If you want to capture the error output into a file, you can do:
xcodebuild 2> ./build_errors.log
Comment: If you try this on a build server, make sure the build agent has permissions to that path. What happened to me is that build kept going and timed out, without warning about the permissions issue in GitLab.
Answer:
-quiet is the best way to do it at now.
Comment: quiet is too quiet for me. xcpretty is dead. xcbeautify is the new tool that does this wonderfully and is well-maintained
Answer: There's a Swift command line tool https://github.com/thii/xcbeautify that can also format xcodebuild output.
Comment: Nice! Was looking for something since xcpretty was abandoned. xcbeautify is great, thank you
Answer: I love xcpretty for looking at as a human, but I had a need to find build errors in an automated setting for propagation elsewhere, and I wanted to be sure I captured just the relevant information. The following sed command serves that purpose:
xcodebuild | sed -nE '/error:/,/^[[:digit:]] errors? generated/ p'

Output:
main.c:16:5: error: use of undeclared identifier 'x'
    x = 5;
    ^
main.c:17:5: error: use of undeclared identifier 'y'
    y = 3;
    ^
2 errors generated.

Answer: I am building an expo project and there are a lot of warnings that come from libraries which I don't want to see. I was able to filter out the warnings with this command.
set -o pipefail \
&& xcodebuild build -workspace app.xcworkspace -scheme app \
CODE_SIGN_IDENTITY="" \
CODE_SIGNING_REQUIRED=NO \
CODE_SIGNING_ALLOWED=NO \
| xcpretty \
| grep --line-buffered -v -F "[-W" \
| grep --line-buffered -v -F "*" \
| grep --line-buffered -v -F "^" \
| grep --line-buffered -v -F ";" \
| grep --line-buffered -v -e "^$" \
| grep --line-buffered -v -F "@" \
| grep --line-buffered -v -F ")" \
| grep --line-buffered -v -F "/" \
| grep --line-buffered -v -F "}" \
| grep --line-buffered -v -F "{" \
| grep --line-buffered -v -F "\\" \
| grep --line-buffered -v -F "#" \
| grep --line-buffered -v -F ","

I'll admit it's a little sloppy but I couldn't get any of the other solutions to work. The -quiet option still printed hundreds of warnings I had no ability to resolve.
What is strange is that when I compile on the command line on the build machine I wasn't getting the warnings but when I compiled in my CI build I would get the warnings. Very annoying. I wish apple would provide a way to silence warnings for xcodebuild
Comment: when you have warnings you don't like in pods you don't control (like libevent, in react-native / expo builds), you want to actually disable them since they are basically out of scope for you. You can do that in a podfile postinstall, like this https://github.com/invertase/react-native-firebase-authentication-example/blob/f21b0bba63e299535e2d35a41d98cb3d3b45075e/template/ios/Podfile#L33
Answer: I have been bitten by xcpretty swallowing way too much information in a CI environment, making it pretty hard to debug the error. -quiet hides output in a way that's a bit too aggressive, so I put together this one-liner and called it xcquiet.sh. It only hides specific lines, while preserving enough of the original output and not swallowing any other unexpected log entries.
Answer: if you want to remove warnings use
xcodebuild <command> | sed -e '/warning:/,/\^/d'

if you want to suppress warnings while using xcpretty try this
xcodebuild <command> \
    | sed -e '/warning:/,/\^/d' \
    | xcpretty -s

Answer: You should use xcbeautify with the quiet (warnings and errors) or quieter (only errors) options.
Example from their site, adapted to warnings and errors:
set -o pipefail && xcodebuild [flags] | xcbeautify --quiet

Answer: We run detox build command and it threw too many logs in CI.
-quite parameter failed with hiding logs.
The best solution is to hide and save logs in file:
npx detox build -c ios &> detox_build.log


Criar novo arquivo descartando linhas do XML atual C#

Question: Tenho um arquivo XML como este:
<?xml version="1.0" encoding="UTF-8"?>
<Message>
   <MessageId>
      <ServiceId>SolicitaLogon</ServiceId>
      <Version>1.0</Version>
      <MsgDesc>Solicitação do Desafio de Logon</MsgDesc>
      200601001987
      <FromAddress>TJ</FromAddress>
      <ToAddress>PGE</ToAddress>
      <Date>2011-10-20</Date>
   </MessageId>
   <MessageBody>
      <Resposta>
         <Mensagem>
            <Codigo>0</Codigo>
            <Descricao>Mensagem processada com sucesso</Descricao>
         </Mensagem>
         <Desafio>4557830751418350620</Desafio>
      </Resposta>
   </MessageBody>
   <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
   </Signature>
</Message>

Quero ler este arquivo descartando o que se encontra entre a tag resposta. Estou fazendo assim, mais agradeço se existir uma forma melhor:
//carrega o mesmo arquivo, e adiciona o desafio criptografado
XmlDocument x = new XmlDocument();
string CaminhoCompletoArquivoConfirmacao = PathPadrao + "confirmaLogon.xml";
x.Load(CaminhoCompletoArquivoConfirmacao);
var todosOsNos = x.SelectNodes("//*");
for (int i = 0; i < todosOsNos.Count; i++)
{
  var element = todosOsNos[i];
  string ElementoCompleto = element.Name + element.InnerText;

  if (element.Name == "Resposta" && element.Name == "Mensagem" && element.Name != "Codigo" && element.Name != "Descricao")
  {
    EscreveXMLIndividual(ElementoCompleto, "ConfirmaLogonNovo.xml");
  }

}

Answer: Talvez você possa uma outra forma para isso. Como quer simplesmente manipular o xml, um arquivo xslt é bem apropriado para isso.
O arquivo teria essa estrutura:
<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:output indent="yes" />

    <xsl:template match="/">

        <xsl:element name= "Resposta">

            <xsl:copy-of select="/Message/MessageBody/Resposta/node()"/>
            </xsl:copy-of>
        </xsl:element>

    </xsl:template>
</xsl:stylesheet>

Pra processar o xslt você pode usar um código assim por exemplo:
System.Xml.Xsl.XslCompiledTransform xlst = new System.Xml.Xsl.XslCompiledTransform();
xlst.Load(@"c:\meuArquivoXslt.xslt");

System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter("resultado.xml", null);
xmlWriter.Formatting = System.Xml.Formatting.Indented;
xlst.Transform(CaminhoCompletoArquivoConfirmacao, xmlWriter);

xmlWriter.Close();


How to change language of Oracle Client 12c Release 2

Question: I have installed Oracle Client 12c Release 2 on my windows.
I want to change its language to Japanese, not English.
When I have some errors, I would like it shows error in Japanese.
I have set Region, language, datetime format before the install and installer shows in Japanese but then after finised, my code still shows messages in English. Installer have no choice for which language I would like to install product.
I have search google for this problem but I have no idea. Some people told me to change NLS value but I can't find it in regedit because it is oracle client not oracle database home (i think so).
Please help me, thank you so much.
Answer: Try this one:
alter session set nls_language = 'JAPANESE';

select 1/0 from dual;

ORA-01476: 除数がゼロです

Answer: The NLS_LANG environment variable determines the language of the user interface and the globalization behavior for components such as SQL*Plus, exp, and imp. It sets the language and territory used by the client application and the database user session. It also declares the character set for entering and displaying data by the client application.
The NLS_LANG environment variable uses the following format:
NLS_LANG=language_territory.characterset

In this format:
language specifies the language used for displaying user interface, error messages, sorting, day names, and month names
territory specifies the conventions for default date, monetary and numeric formats
characterset specifies the encoding of the database client, which is the character set for data entered or displayed by a client program
In most cases, this is the Oracle character set that corresponds to the Windows ANSI Code Page as determined by the System Locale.
The NLS_LANG parameter on Windows can be set
in Registry under the subkey corresponding to a given Oracle home,
as an environment variable.
When you install Oracle Database components and the NLS_LANG parameter is not yet set in the Registry subkey of the target Oracle home, Oracle Universal Installer sets the NLS_LANG parameter to a default value derived from the operating system locale for the current user.
For example:
Japanese - JAPANESE_JAPAN.JA16SJISTILDE
English (United Kingdom) - ENGLISH_UNITED KINGDOM.WE8MSWIN1252
English (United States) - AMERICAN_AMERICA.WE8MSWIN1252
Please refer here for more information : Installing and Using Oracle Components in Different Languages


Send Email to admin when user register?

Question: I tried to to send email to admin when user register to my application
I tried these code :
$admin = Admin::where('is_admin', 3)->get();

Mail::send('emails.notfyNewUser', $data  ,  function ($message) use($admin) {

  $message->from('firstname.lastname@example.com','test');

  $message->to($admin->email);

  $message->subject('test');

});

And got this error :

Property [email] does not exist on this collection instance.

And this is my collection result via dd for $admin :
Image
Comment: Possible duplicate of [Property \[title\] does not exist on this collection instance](https://stackoverflow.com/questions/41366092/property-title-does-not-exist-on-this-collection-instance) Please read here: [Why not upload images of code when asking a question](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question).
Answer: The problem is that you have 2 admins inside your collection, and the property admin is within each of those models.
You can solve it by changing your query, for something like this:
$admin = Admin::where('is_admin', 3)->first();

Or, if you want to send an email for both admins, use a foreach loop:
foreach($admin as $a) {
    Mail::send('emails.notfyNewUser', $data  ,  function ($message) use($a) {

    $message->from('email@example.com','test');

    $message->to($a->email);

    $message->subject('test');

    });
}

Hope it helps.
Comment: Glad that i can help you! :)

Send Email to admin when user register?


Equation without parantheses

Question: I'm doing some exercises on KhanAcademy and I saw an equation something like this:
$y=-x^2$
If $x$ is equal to $-4$, the equation becomes:
$y=--4^2$
How do I calculate this equation?
I thought of these options:
$y=-(-4)^2 = -(16) = -16$
$y=(--4)^2 = (4)^2 = 16$
What is the correct way to do this?
Comment: the first way is correct
Answer: $y=-x^2$
If $x=-4$, then $y=-(-4)^2=-16$
Comment: Hi Adi. Nice to see you while it is snowing. :-)
Answer: Your first way is correct.
Think of $y = -x^2$ as $y = -(x^2)$.
Comment: When I used to teach I would tell students to think of $y = -x^2$ as $y = -1 \cdot x \cdot x$
Comment: @DaveL.Renfro You could also think of it as $-1*x^2$ and apply order of operations, but hey, you're the one who actually taught students this stuff.
Comment: What I like about $-1 \cdot x \cdot x$ is that it allows you to remind students lots of things, such as the coefficient is the number $-1$ and squaring means multiply by itself. You also don't have to create extra parentheses that weren't there to begin with, and which you'd only know were there if you already knew the correct interpretation. But the order of operations issue is also useful, and I've used it as well in viewing $-x^2$ as $-1 \cdot x^2$ as you suggested.
Comment: @DaveLRenfro Fair enough.
Answer: The important thing is that $y=-x^2$ should be read as $y=-(x^2)$  Then if you want to substitute $-4$ for $x$, you get $y=-((-4)^2)$.  The minus sign that comes with the $x$ needs to get squared, but not the one that came with the initial equation.
Answer: Think of $-x$ as the unique solution to the equation $x+y=0$, solving for $y$. Then, we want to solve $4^2+y = 0\Rightarrow 16+y=0\Rightarrow y=-16$. Of course from then on just remember that exponentiating goes first, but this is a kind of justification.
In fact, this is the definition of $-x$.

Equation without parantheses


Why does nslookup not return what I am expecting from my bind server? (RPZ configured)

Question: Prior to this question I was looking for some help in finding a way to return a different response to querying clients based on their IP Address. The question was answered here: How can I selectively override some A records on a Bind DNS Server?
I have followed what the accepted answer was, and now running into issues.
When I run:
nslookup faq.test.com

I expect this:
root@dev:/etc/bind# nslookup vaultofsatoshi.com
Server:     172.16.225.132
Address:    172.16.225.132#53

Non-authoritative answer:
Name:   faq.test.com
Address: 192.168.1.1

However, I am getting this:
root@dev:/etc/bind# nslookup faq.test.com
Server:     172.16.225.132
Address:    172.16.225.132#53

** server can't find faq.test.com: NXDOMAIN

I should mention, querying google.com or any other website works and returns everything fine, it is just the ones that I override that it fails. I've included my configuration files below, any help would be appreciated.
/etc/bind/named.conf
include "/etc/bind/named.conf.options";
include "/etc/bind/named.conf.local";
include "/etc/bind/named.conf.default-zones";

/etc/bind/named.conf.options
options {
    directory "/var/cache/bind";

    forwarders {
        126.96.36.199;
        126.96.36.199;
    };

    response-policy {
        zone "development-overrides";
    };

    auth-nxdomain no;    # conform to RFC1035
    listen-on-v6 { any; };
    allow-query { trusted; };
    allow-recursion { trusted; };
    recursion yes;
    dnssec-enable no;
    dnssec-validation no;
};

/etc/bind/named.conf.local
include "/etc/bind/rndc.key";

acl "trusted" {
    172.16.225.132;
    127.0.0.1;
};

include "/etc/bind/zones.override";

logging {
    channel bind_log {
        file "/var/log/named/named.log" versions 5 size 30m;
        severity info;
        print-time yes;
        print-severity yes;
        print-category yes;
    };
    category default { bind_log; };
    category queries { bind_log; };
};

/etc/bind/named.conf.default-zones
// prime the server with knowledge of the root servers
zone "." {
    type hint;
    file "/etc/bind/db.root";
};

// be authoritative for the localhost forward and reverse zones, and for
// broadcast zones as per RFC 1912

zone "localhost" {
    type master;
    file "/etc/bind/db.local";
};

zone "127.in-addr.arpa" {
    type master;
    file "/etc/bind/db.127";
};

zone "0.in-addr.arpa" {
    type master;
    file "/etc/bind/db.0";
};

zone "255.in-addr.arpa" {
    type master;
    file "/etc/bind/db.255";
};

/etc/bind/development-overrides
$TTL 1H
@                       SOA LOCALHOST. test.com (1 1h 15m 30d 2h)
                        NS  LOCALHOST.

support.test.com     A   192.168.1.1
faq.test.com         A   192.168.1.1

; do not rewrite (PASSTHRU) OK.DOMAIN.COM
*               A   rpz-passthru.

Answer: The last line in the RPZ zone does not look syntactically valid.
The syntax for an RPZ zone is the same as for regular zones, it only has special semantics for RPZ.
With that in mind it's clear that an A record can't possibly have rpz-passthru. as it's value. An A record can only ever have an IPv4 address as its value.
If you look at the RPZ documentation you will find that the special RPZ directives (like rpz-passthru.) use the CNAME record type.
named-checkconf -zj and/or reading the logs is generally helpful. I would assume that, when using the zone data from the question, the RPZ zone will fail to load and there should be errors about that (I would expect an error about "bad dotted quad" or something along those lines).
As a separate note, I don't believe that last line is really needed, it appears to just (try to) explicitly define what the default behavior would have been.


VBA Windows 7 style buttons

Question: I'm pretty sure this question has been asked a lot around the web and I've read a lot of the questions and their "answers" on several forums but I've never seen a clear answer so I'd like to know:
Is is possible, to use Windows 7 style buttons

in Excel VBA or do I have to use these grey things looking like they come from

?
I dont want to use images, I mean importing these "ActiveX Controls", I think thats their name.
Comment: Translation: If you knew enough programming to be able to do it, you'd know that you don't want to.
Comment: *do I have to use these grey things looking like they come from Windows 2000* - I'd think they're actually from Win95. If you want *shiny and new*, you can make your UI with WPF/XAML in a COM-visible .net class library (.dll), and use *that* from your VBA code. Depending on your coding style this *may* mean serious architectural changes (i.e. if you're used to implement all the logic in the buttons' `Click` handlers...)
Comment: i would love to know that as well.
Comment: Do you want to use them in a userform or in a sheet?
Comment: In a userform of an add-in
Answer: I am unaware of a solution where you can make use of the "Windows 7 style buttons". Yet, I would like to note that programming does not require you to use the "Developer" tab exclusively. In other words: just because you want a button doesn't mean that you have to use just that from the Developer tab. In fact, almost any shape within Excel can be assigned a macro.
The easiest way to get a button similar to the "Windows 7 style button" is to Insert a Rectangle or a Rounded Rectangle from the Shapes menu. The "fancy" grey coloring can be easily achieved when you click on that shape and then on the Format tab for that shape select one of the predefined grey-scale shape style. These buttons look extremely similar to what you want and can be easily assigned a macro by right-clicking on these shapes.
Comment: ++ A button on a worksheet is actually stored in the worksheet's `Shapes` collection; this solution is by far the simplest, and you can get pretty neat results with effects and drop-shadows.
Comment: What do you mean with "shapes menu"?
Comment: `Insert` --> `Illustrations` --> `Shapes` --> `Rounded Rectangle` or `Rectangle`
Answer: Buckle up, you're in for a ride.

First, create a new C# (or VB.NET.. whatever rocks your boat) class library, and add a new WPF UserControl, and design your UI:
<UserControl x:Class="ComVisibleUI.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" d:DataContext="ViewModel1"
             d:DesignHeight="200" d:DesignWidth="300">

    <Grid Background="White">

        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="32" />
        </Grid.RowDefinitions>

        <TextBlock Text="actual content here" Foreground="DimGray" HorizontalAlignment="Center" VerticalAlignment="Center" />

        <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Margin="2">
            <Button Width="128" Command="{Binding Command1}">
                <TextBlock Text="Button1" />
            </Button>
            <Button Width="128" Command="{Binding Command2}">
                <TextBlock Text="Button2" />
            </Button>
        </StackPanel>

    </Grid>
</UserControl>

Build the project.
Then, add a new Form, dock a WPF Interop ElementHost control, and you should be able to add your WPF UserControl1 (whatever you called it) as the hosted WPF control.
The WPF control uses data bindings to hook up Command1 and Command2 (and everything else, really - read up on the Model-View-ViewModel pattern), so you'll need a class to implement the managed code part. If your logic is all VBA then this should be pretty slim:
public class ViewModel1
{
    public ViewModel1()
    {
        _command1 = new DelegateCommand(ExecuteCommand1);
        _command2 = new DelegateCommand(ExecuteCommand2);
    }

    private readonly ICommand _command1;
    public ICommand Command1 { get { return _command1; } }

    public event EventHandler ExecutingCommand1;
    private void ExecuteCommand1(object parameter)
    {
        ExecuteHandler(ExecutingCommand1);
    }

    private readonly ICommand _command2;
    public ICommand Command2 { get { return _command2; } }

    public event EventHandler ExecutingCommand2;
    private void ExecuteCommand2(object parameter)
    {
        ExecuteHandler(ExecutingCommand2);
    }

    private void ExecuteHandler(EventHandler eventHandler)
    {
        var handler = eventHandler;
        if (handler != null)
        {
            handler.Invoke(this, EventArgs.Empty);
        }
    }
}

A DelegateCommand is a very nice little thing that's all over Stack Overflow, so don't hesitate to search if you have any questions:
public class DelegateCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;

    public DelegateCommand(Action<object> execute, Func<object,bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public event EventHandler CanExecuteChanged;
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute.Invoke(parameter);
    }

    public void Execute(object parameter)
    {
        _execute.Invoke(parameter);
    }
}

The WinForms form will need to assign the WPF control's DataContext - expose a method to do that:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void SetDataContext(ViewModel1 viewModel)
    {
        hostedWPFControl.DataContext = viewModel;
    }
}

Other than that, there shouldn't be any code in here.

WPF likes the MVVM pattern, WinForms likes MVP (lookup Model-View-Presenter). The WPF part being hosted in WinForms, we'll make a presenter - that's the object the VBA code will use:
[ComVisible(true)]
public interface IPresenter1
{
    void Show();
}

Yes, that's just an interface. Hold on, we need another:
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[Guid("18F3B8A8-EC60-4BCE-970A-6C0ABA145705")]
[ComVisible(true)]
public interface IPresenterEvents
{
    void ExecuteCommand1(object message);
    void ExecuteCommand2();
}

The IPresenterEvents interface is your "event sink" interface, that the VBA code will need to implement, but I'll get to it. First we need to implment the actual presenter:
public delegate void Command1Delegate(string message);
public delegate void Command2Delegate();

[ComSourceInterfaces(typeof(IPresenterEvents))]
[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
[Guid("FAF36F86-7CB3-4E0C-A016-D8C84F6B07D7")]
public class Presenter1 : IPresenter1, IDisposable
{
    private readonly Form _view;

    public Presenter1()
    {
        var view = new Form1();
        var viewModel = new ViewModel1();
        viewModel.ExecutingCommand1 += viewModel_ExecutingCommand1;
        viewModel.ExecutingCommand2 += viewModel_ExecutingCommand2;

        view.SetDataContext(viewModel);

        _view = view;
    }

    public event Command1Delegate ExecuteCommand1;
    private void viewModel_ExecutingCommand1(object sender, EventArgs e)
    {
        var handler = ExecuteCommand1;
        if (handler != null)
        {
            handler.Invoke("Hello from Command1!");
        }
    }

    public event Command2Delegate ExecuteCommand2;
    private void viewModel_ExecutingCommand2(object sender, EventArgs e)
    {
        var handler = ExecuteCommand2;
        if (handler != null)
        {
            handler.Invoke();
        }
    }

    public void Show()
    {
        _view.ShowDialog();
    }

    public void Dispose()
    {
        _view.Dispose();
    }
}

Now, go to the project's properties, and check that "Register for COM interop" checkbox, then build the project; in the [Debug] tab, select start action "Start external program", and locate the EXCEL.EXE executable on your machine: when you press F5, Visual Studio will launch Excel with the debugger attached, and then you can open up the VBE (Alt+F11), add a reference to the .tlb (type library) that you just built (you'll find it in your .net project directory, under \bin\debug\theprojectname.tlb, assuming a debug build), and that should do it.
There are a number of issues here, that I'll come back to fix later:

The Dispose() method isn't exposed, and won't be explicitly or implicitly called at any point, which is... dirty.
While everything seems like it's working from the C# debugger's point of view, I couldn't get the darn VBA handlers to run. That's probably a big problem if you intend to implement the logic in VBA, not just bring up the UI. OTOH you have access to .net code, might as well implement the presenter logic in the presenter itself, in C#/VB.NET, and then you don't need to get these event handlers to work.

Anyway, I've added this code to ThisWorkbook:
Option Explicit
Private WithEvents view As ComVisibleUI.Presenter1

Public Sub DoSomething()
    Set view = New ComVisibleUI.Presenter1
    view.Show
End Sub

Private Sub view_ExecuteCommand1(ByVal message As Variant)
    MsgBox message
End Sub

Private Sub view_ExecuteCommand2()
    MsgBox "Hello from WPF!"
End Sub

And when I run ThisWorkbook.DoSomething from the immediate window (Ctrl+G), I get this:

In theory (at least according to MSDN), that's all you need to do. As I said these event handlers aren't getting called for some reason, but hey, you get your shiny buttons! ...and all the power of WPF to design your UI now :)
Comment: Holy o.O Thanks for the efforts, I'll try this in few days and let you know if it worked

VBA Windows 7 style buttons


Query with using max-width in relative units for Flexbox display

Question: I am trying to display 4 photos and biography of team members in a row to fit wrapper container using display flex. It works when I use max-width for each img to 360px but does not work when I use max-width in % relative unit. Anyone know why? I want to use relative units in all my projects and I just can't wrap my head around this.

John Doe

CEO & Founder

                        <button>Contact</button>

Jane Doe

Architect

                        <button>Contact</button>

Mike Ross

Architect

                        <button>Contact</button>

Dan Star

Architect

                        <button>Contact</button>

    #people{
        display:flex;
        flex-wrap: wrap;
        justify-content: space-between;
        flex-basis:100%;
    }

   #people div img {
        max-width: 360px;
    }

The above code achieves the results. But if I want to change max width in #people div img {} to a relative % unit, does anyone know how I do this. I am using an online template and trying to reconstruct it myself (hence I'm asking, if I had to create something like this myself for a real project I wouldn't understand this issue). Thanks!
Comment: Provide a working code snippet that reproduce the issue.
Answer: I think you were referring to this. You need to add the property of flex:1; to #people child classes i.e .person, thus making it flexible (flex-grow:1, flex-shrink:1, flex-basis:auto). And then set the width of the image to 100% which will resize relative to the viewport width.

#people {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.person{
flex:1;
}

.person img {
max-width:100%;
}

John Doe

CEO & Founder

    <button>Contact</button>

Jane Doe

Architect

    <button>Contact</button>

Mike Ross

Architect

    <button>Contact</button>

Dan Star

Architect

    <button>Contact</button>

Comment: @user8322222 No, problem mate. Mark the answer up if it did. Cheers


Is the polynomial $x^5+5x-10$ is solvable by radicals over $\Bbb Q$?

Question: I have tried many ways.This polynomial has exactly one real and four complex roots and it is in Bring-Jerrard form, the solvability of which is about finding $\varepsilon, e$ and $c$ to equate some rational expressions with $5$ and $-10$.But this is very much calculative and I could not find any way. I know it will not be solvable if the Galois group is isomorphic to $A_5$ or $S_5$ but how to show that! Please help to find way.
Comment: I have vague memories of a relationship between number of roots of $x^5 + 5x - 10$ in $\mathbb{F}_p$ for $p$ prime as $p$ varies, and the Galois group of the splitting field of $x^5 + 5x - 10$.  In a quick check, it looks like I get at most three roots for each case of $7 \le p \le 61$ which suggests the Galois group is "probably" one of the smaller ones.
Comment: I understand that the Galois group has a 5 cycle but there are 4 complex roots how it can have a transposition? It has a double trabaposition but how it has a transposition bcz I know a 5 cycle and a transposition would generate S5.Please make me understand bit clearer!
Comment: @rain1 Doesn't the dihedral group of order 10, considered as a subgroup of $S_5$ via its action on the vertices of a regular pentagon, have a 5-cycle and an element of (2)(2) type?
Comment: ? polgalois(x^5 + 5*x - 10)

%1 = [120, -1, 1, "S5"]
Comment: discriminant is 32050000, not a square. so it is not A_5.
Comment: Yes the polynomial is irreducible mod 3, which proves the galois group has a cycle of (5) in it (a 5-cycle). Together with the complex conjugation map having a (2)(2) type you must have S_5.
Comment: Looking at https://groupprops.subwiki.org/wiki/Subgroup_structure_of_symmetric_group:S5 the only proper subgroup there with a single orbit (necessary since the polynomial is certainly irreducible) and not contained in $A_5$ (cannot be with a non-square determinant) would be the "GA(1,5) in S5" entry $\langle (1,2,3,4,5),(2,3,5,4) \rangle$.  If that's the Galois group then https://groupprops.subwiki.org/wiki/General_affine_group:GA(1,5) says it's solvable.
Answer: Let's recall the following.

Theorem (Dedekind): If an irreducible polynomial $f(x)$ factors $\bmod p$ into factors with degrees $d_1, d_2, \dots$, then the Galois group of $f$ contains an element of cycle type $(d_1, d_2, \dots)$.

Theorem (Frobenius / Chebotarev): Every cycle type in the Galois group occurs this way, with density proportional to its density in the Galois group.

Furthermore, transitive subgroups of $S_5$ (and I think maybe also $S_6$?) are determined up to conjugacy by the cycle types of their elements, so factorizations mod a prime eventually identify all Galois groups of irreducible quintics. The complete list of transitive subgroups of $S_5$ (up to conjugacy) is

$C_5$
$D_5$
The Frobenius group $x \mapsto ax + b, a \in \mathbb{F}_5^{\times}, b \in \mathbb{F}_5$
$A_5$
$S_5$.

Using WolframAlpha we find that $f(x) = x^5 + 5x - 10$ is

irreducible $\bmod 3$, so the Galois group contains a $5$-cycle (but this already follows from transitivity),
a product of an irreducible quadratic and cubic $\bmod 7$, so the Galois group contains a permutation of cycle type $(2, 3)$

and we can stop here: already $S_5$ is the only transitive subgroup of $S_5$ containing an element of cycle type $(2, 3)$.
Comment: Hmm... or from my results just on number of roots in $\mathbb{F}_p$, there are exactly three roots mod 31 which would imply the Galois group must contain a transposition.
Comment: Yep, that's also enough.
Comment: Thanks. can you please tell me the cubuc and quadratic factors in mod 7?
Comment: Here's the WolframAlpha query: https://www.wolframalpha.com/input/?i=factor+x%5E5+%2B+5x+-+10+mod+7

It's $(x^2 + 2x + 5)(x^3 + 5x^2 + 6x + 5) \bmod 7$.
Comment: Ohh thanks a lot for your help.


CakePHP seems to ignore foreign key

Question: I have three tables that I'm trying to query. Right now CakePHP is only pulling data from Visits and Guests, it's incorrectly joining Rooms as I'll explian.
Visits
id   |  guest_id   |   room_id   |   arrival_date

Guests
id    |    name   |  user_id

Rooms
id    |    user_id   |  description

I'm trying to get info on all three things when querying for a visit
$visits = $this->paginate('Visit', array(
            'arrival_date >=' => $date,
            'room.user_id' => $user_id
            )
        );

Here are the relationships I have in my models
Visit model
public $hasOne = array(
    'Guest' => array(
        'foreignKey' => 'id'
    ),
    'Room' => array(
        'foreignKey' => 'id'
    )
);

Room model
public $belongsTo = array(   //user creates a room
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

public $hasMany = array(
    'Visit' => array(
        'foreignKey' => 'visit_id',
    ),
);

On every single query when I use a sql_dump it shows the join of Rooms as
LEFT JOIN `TestReservations`.`rooms` AS `Room` ON (`Room`.`id` = `Visit`.`id`)

It should be Room.id = Visit.room_id
I accidentally changed the hasOne relation in my room model to room_id and I noticed it joined as "Room.room_id = visit.id". This foreign key is clearly being set through this, so why isn't the one in the visit model?
Answer: Your tables are setup incorrectly for that kind of relationship, respectively your relationship configuration is incorrect for your database schema.
In a has-one relationship, the other table contains the foreign key, ie the guests and rooms tables would need a visit_id column for this to work (though I don't think this is what you want, you should probably go for a differnt relationship instead).
See http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone

foreignKey: the name of the foreign key found in the other model. This is especially handy if you need to define multiple hasOne relationships. The default value for this key is the underscored, singular name of the current model, suffixed with '_id'. In the example above it would default to 'user_id'.

Likewise with your Room model, in a has-many relationship the other model contains the foreign key too, ie in the configuration the foreign key should be room_id instead of visit_id (visit_id doesn't even exist according to your schema).
Your database schema currently reflects the following relationships:

Visit belongsTo Guest, Room
Guest hasMany Visit
Room hasMany Visit
Guest belongsTo User
Room belongsTo User
User hasMany Guest, Room

I don't know about the specific needs of your application, so I can't really make further suggestions for your schema (that would be something for a new question), but generally I'd say your schema looks OK so far. Changing it so that Visit would have hasOne relations to Room and Guest is something I'd definitely discourage, a visit is something specific to a guest and a room, but it's not exclusive, so it's correct that the visits table holds the foreign keys, the other way around it would be just plain wrong because a room and a guest could then only be associated with a single visit. So having that in mind, leave your tables as they are, and change to the reflected relationships for your CakePHP models as listed above.
Note that you don't have to explicitly define the foreign key in the relationship configuration, when following the CakePHP conventions for your database schema, the correct key based on the model name is generated automatically.
Comment: Thanks for the help, sorry for the delayed response. I unexpectedly had to run out of town for the night. Would you suggest re-creating the tables or is this OK? I want to become better at sticking to "proper ways" of tackling problems, so I'd really appreciate your input. Thanks again

CakePHP seems to ignore foreign key


How to format a Python string to resemble a dictionary using .format()?

Question: I have a python variable containing the string A and another one containing the string B.
I want to generate the string which represents the dictionary containing the aforementioned two strings as a key value pair. How can I do it? Using nested curly brackets inside a string literal seems not to work. But I need that notation to use .format()
>>> x = "A"
>>> y = "B"
>>> assert(eval('\{"{}": "{}"\}'.format(x, y)) == str({x: y}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '"{}"

Comment: Weird question.  What's wrong with `repr({x:y})`?
Comment: Escape with double braces `{{"{}": "{}"}}`
Answer: You can escape curly braces by adding double curly braces i.e {{ and }}.
To generate the string:
>>> x = 'A'
>>> y = 'B'
>>> dict_str = "{{'{}': '{}'}}".format(x,y)
>>> dict_str
"{'A': 'B'}"


Sum of two independent exponentially distributed random variables

Question: Suppose that the time between calls from your aunt Debie has an exponential
distribution with a mean time of 3 days. What is the probability that you will get two calls in less than 3 days?
So trying to solve this I tried to calculate the probability
$P(X_1+X_2\lt3)$ where $X_1 =$ days to first call and $X_2 = $ days to second call. My attempt to solve...
$$X_1+X_2 \lt 3$$
$$X_1 \lt 3-X_2$$
$$\frac{1}{9}\int_{0}^3\int_{0}^{3-X_2} e^\frac{-x_1+x_2}{3} dx_1dx_2 = 1$$
The probability isn't likely 100% so where did I make my mistake?
Comment: Exponential density with mean $3$ is $\frac13e^{-x/3}$, not $e^{-x/3}$.
Comment: thanks for reminding me, forgot to add my $\frac{1}{9}$ in there
Comment: Next, please explain why you think the RHS is 1.
Comment: Pretty sure $x_2$ should also have a minus sign in the exponent...
Comment: Your mistake seems to be in the integration.  Plus the joint pdf is $\tfrac 1 9 \mathsf e^{-\frac{(x_1+x_2)}{3}}$ (or $\tfrac 1 9\exp\big(-\frac{x_1+x_2}{3}\big)$ to be clearer).
Comment: If you are familiar with the relationship berween the exponential and the Poisson, ou may be able to find a quicker solution.
Comment: Thank you Graham Kemp, that negative was what made it work! If you could post that into an answer I'll give it to you.
Answer: For clarity, what you need to integrate is:
$$\mathsf P(X_1+X_2\leq 3) = \frac 1 9 \int\limits_0^3 e^{-y/3}\left(\int\limits_0^{3-y} e^{-x/3}\operatorname d x\right)\operatorname d y$$
Just take it one step at a time.


How do I get a hold of the session object in my form handler?

Question: I have build a form in D8 and on submit I want to save the form values into a session, so that I can access them 3, 4,.... page requests later.
In D7 I just used
<code>$_SESSION['key'] = $value
</code>
I have a feeling, in D8 and symfony, this is (very) bad practice. How should I solve this?
At the moment I'm using the following chunk of code, but I don't know if this is the correct way:
<code>$session = new Session();
$session->set('name', 'value');

$name = $session->get('name');
</code>
Answer: The conversion to the Symfony session component is not yet complete, therefore you still have to access the session using the superglobal.
Follow https://www.drupal.org/node/1858196 and its sub-issues, if you like to stay up to date regarding this issue.


KVM live migration between Intel and AMD processors

Question: When using KVM for virtualisation on Redhat (RHEV), is it possible to live migrate VMs between AMD and Intel boxes?  In particular, I'm interested in Opteron 6100 and Intel Xeon 5200 series.
There was an AMD demo in 2008, but I can't find out whether it's now available now or not.  On this Red Hat docs page I see no requirement for the same CPU.
Answer: KVM lets you specify the kind of CPU 'exposed' to the VM by choosing the specific subset of features it announces to the BIOS.  If you use -cpu host, it simply exposes the same features as the host; but there are other more 'generic' subsets, like -cpu qemu64.  If you use the same on different machines, you can freely migrate between them.
Comment: sure; the trick is to expose only a common subset of features. that's the whole idea of `-cpu quemu64` see the FAQ: [Does KVM support live migration from an AMD host to an Intel host and back?](http://www.linux-kvm.org/page/FAQ#Does_KVM_support_live_migration_from_an_AMD_host_to_an_Intel_host_and_back.3F)
Comment: have you ever tried migrating amd>intel and vice versa?
Comment: Well, this will not work in RHEV
Comment: @Javier Is there any performance overhead to use `-cpu qemu64`?
Comment: not exactly "overhead", but applications won't use any modern facilities, vector registers, or hashing instructions, or things like that.   I haven't used that in a looong time, so it's very likely many applications won't start because they need SSE or MMX.
Answer: No, you cannot migrate between different CPU vendors. with RHEV, you should not be able to place an Intel and AMD hosts in the same cluster (migration domain)
No virtualization platform allows cross vendor migrations today, normally you get blocked during the setup stage, so you don't get crashed VMs.
Comment: I can confirm this is the case with RHEV.  I believe they have CPU baselining planned in the future since it's technically possible to do with KVM, but right now you can't add a cluster of mixed hosts.  There are issues with different TSC implementations, processor feature sets, etc which I believe they're still working on.
Answer: I think migration should work OK as long as you are using 64-bit (and otherwise identically set up) distributions in both boxes. But if the other box runs some other version of RHEV or has 32-bit version installed, then there are problems waiting for you.
(Both boxes running a 32-bit distribution should work OK, too. It's only if you mix up 32 and 64 bits, then there are problems)
Answer: I dont thing so it will migration done in AMD and Intel box it has identically same architect, it will show you its migrating but it will zombi status. And both box has to be RHEV version
Answer: If you use a HVM based virtual environment then yes.  Your CPU's must support Virtual Hardware requirements.  If you look at KVM documentation you can do it - and those CPU's do support it.
Answer: Yes, you can live migrate across platforms. I'm currently experimenting with this using KVM in Arch Linux. It works


Product of Smooth Covering Maps a Smooth Covering Map? ( J.Lee, 2-12)

Question: I am trying to review my differential Geometry. In J.Lee's Smooth Manifolds, there is an exercise in which one has to show that the product of smooth covering maps is a smooth covering map.
A smooth covering map is a smooth cover $\pi: M' \rightarrow M$, where
$M, \, M'$ are smooth manifolds, and in which every $p$ in $M'$ has a neighborhood $U_p$ in $M$ such that $p|_{p^{-1}} (U_p) \rightarrow U_p$ (i.e., the restriction of $p$ to the inverse image of $U_p$ is a diffeomorphism) . I think this exercise is straightforward, (basically we just use the fact that the product of diffeomorphisms is a diffeomorphism) but I am kind of rusty, and would appreciate your inputs.
Now, we need to show that , given covers $p_1:M' \rightarrow M$ and $p_2:N' \rightarrow {N}$ that for any pair $(p,q)$ there is a neighborhood $W$ of $(p, q)$ such that $p_1 \times p_2 |_{p_1^{-1} \times p_2^{-1} (W)} : p_1^{-1} \times p_2^{-1} (W) \rightarrow W$ is a diffeomorphism.
But we know that for $p$ in $M$ there is a $U_p$ with $p_1|_{p_1^{-1} (U_p)} : p_1^{-1} (U_p) \rightarrow U_p$ and for any $q$ in $N$ there is a $U_q$ with $p_2|_{{p_2}^{-1} (U_q)} : p_2^{-1} (U_q) \rightarrow U_q$
such that both are diffeomorphisms. Then the product map is a diffeomorphism automatically, isn't it, i.e., isn't the map:
$$(p_1, p_2)|_{(p_1^{-1} \times p_2^{-1}) (U_q)} : (p_1^{-1} \times p_2^{-1}) (U_q) \rightarrow U_p \times U_q$$ a diffeomorphism?
We know that if $f = (f_1(x_1,\ldots,x_n),f_2(x_1,\ldots,x_n))$ is differentiable with derivative $(f_1',f_2')$ and$f_1^{-1}$ and $f_2^{-1}$ are each differentiable (by the assumption of diffeomorphism), then  I think the differentiable inverse here is given by the identities fof-1=Id.
I imagine there may be some issue in showing that the above is true for manifolds, and not just for subsets of $\mathbb{R}^n$. Other than that, is my setup correct?
Basically, I am curious as to whether this problem comes down to the fact that the
product of diffeomorphisms is a diffeomorphism.
Thanks.
Comment: Hey, don't apologize, I'm just trying to help you get your question answered.   I formatted your question into a cleaner style, but I don't know your subject, so it's quite likely I butchered some of what you are trying to ask.  However, I think I made it into a presentable start; I think if you edit my TeX job, you can get the hang of the notation and can fix whatever I screwed up.  Good luck.
Comment: Sorry, it's my first post, I did not find the reference for TeX,but I will look it up now and will rewrite it; sorry.
Comment: Hope this is better, sorry.
Comment: You're never going to get anyone to read that if you don't TeX it.
Comment: I tried to fix some of the notation but it still isn't optimal you'll have to make some improvements yourself.
Answer: You're right. To prove this you may use the fact that you have an atlas for $M_1\times M_2$ (it's the assumed differential structure of the exercise) whose elements are of the form $(U_1\times U_2,\varphi_1\times\varphi_2)$, with $(U_1,\varphi_1)$ being in an atlas for $M_1$ and $(U_2,\varphi_2)$ being in an atlas for $M_2$.
In fact, given the diffeomorphisms $f_1:M_1\to M_1'$ and $f_2:M_2\to M_2'$ you have for every $(p_1,p_2)\in M_1\times M_2$ smooth coordinate charts $(U_1\times U_2,\varphi_1\times\varphi_2)$ and $(V_1\times V_2,\psi_1\times\psi_2)$, with $(p_1,p_2)\in U_1\times U_2$ and $(f_1(p_1),f_2(p_2))=(q_1,q_2)\in V_1\times V_2$. So, the smoothnes of
$$(\psi_1\times\psi_2)\circ(f_1\times f_2)\circ(\varphi_1\times\varphi_2)^{-1}= (\psi_1\circ f_1\circ\varphi_1^{-1})\times(\psi_2\circ f_2\circ\varphi_2^{-1})$$
and
$$(\varphi_1\times\varphi_2)\circ(f_1\times f_2)^{-1}\circ(\psi_1\times\psi_2)^{-1} = (\varphi_1\circ f_1^{-1}\circ\psi_1^{-1})\times(\varphi_2\circ f_2^{-1}\circ\psi_2^{-1})$$
come from the smoothness of
$$\psi_1\circ f_1\circ\varphi_1^{-1},$$
$$\psi_2\circ f_2\circ\varphi_2^{-1},$$
$$\varphi_1\circ f_1^{-1}\circ\psi_1^{-1},$$
and
$$\varphi_2\circ f_2^{-1}\circ\psi_2^{-1}$$
as in Euclidean spaces.
Comment: I think that this can be made into a complete argument, but you have to be a bit more careful: The maps $f_{1}$ and $f_{2}$ are *not* diffeomorphisms. You should start with neighborhoods $U_p$ and $U_{q}$ such that $f_{1}^{-1}(U_p)$ can be written as a disjoint union $U_{p}^i$ of open sets diffeomorphic to $U_p$ via $f_{1}$, similarly for $U_{q}$. Then your argument shows that the restriction of $f_{1} \times f_{2}$ to $U_{p}^{i} \times U_{q}^{j}$ is a diffeomorphism onto $U_{p} \times U_{q}$ for all pairs $(i,j)$.
Comment: you´re right. But my intention was only to show that a product of diffeomorphisms is a diffeomorphism. I suppose that he have already grasped how to solve the exercise.


Display total count number of view all node create by user

Question: how can i create views of number of total viewed statistic of all node by create by user.
for example:
uid=1
total:2500
today:500
yesterday:1000
last week: 5000
last month: 15000
Answer: Node View Count module allows to count node views. It records each view of node with user uid and time-stamp. So now you can know how many times a user viewed node by day, week, month and etc.
You can integrate this module with views and you can use it to create different statistics pages, output new not viewed nodes for user and many more.


Modify the image preview area after upload in Drupal 7

Question: I am new to Drupal. I wanted to have table less render view of images after upload at editing window. I found lots of help content, but they are hard to understand. Currently i have following view:

But i need following view with drag-n-drop sorting facility:

I am using File Resumable Upload to upload images. Can anyone tell me what i should do.
Comment: Hello and welcome. Please see help center. Image-based questions are listed on the "don't" list. Whilst your question is not exactly image only, it does not show how you have tried to do this, and where you got stuck, so people may perceive it as "do my work for me" question. I guess that's why you got downvotes.
Comment: I got it. I will post the question in right way as you suggested. Thank you very much. @Mołot
Answer: You can use Draggable Views. For content view displays you have to use a display and a sort block. Pointers can be found here.
Edited 'here' link
Answer: Firstly, the module 'views' that you tagged in your question won't be interacting at the edit stage unless you have something else in play that you haven't mentioned.
This sounds like a primarily CSS question... since you need the display altered at the edit stage, you should be able to tinker with the css to change the effected classes and id's to suit your display needs.
Also, if you don't intend to use the alternate text, you should be able to remove that directly from the field management screen.


some pop-up text while hover in svg path

Question: I want some sample text while hover in svg path, can anyone tell me the easiest way please
Here is my css code:

Here is my Html SVG code:
<svg width="210mm" height="297mm" viewBox="0 0 744.09448819 1052.3622047">
    <path name="path1" class="available" d="m 97.42857,852.3622 c 0,72.14286 0.71429,72.14286 0.71429,72.14286 l 55,23.57143 -0.71429,-95 z"/></path>
    <path name="path2" class="available" d="m 97.42857,809.50506 c 0,42.85714 0,43.57143 0,43.57143 l 55,-0.71429 0,-43.57142 z"/>
    <path name="path3" class="available" d="m 97.21429,766.3622 c 0,42.85714 0,43.57143 0,43.57143 l 55,-0.71429 0,-43.57142 z"/>
</svg>

Answer: The easiest way is to use title elements which UAs turn into tooltips.

<svg width="210mm" height="297mm" viewBox="0 1000 744 500">
    <path fill="red" d="m 97.42857,852.3622 c 0,72.14286 0.71429,72.14286 0.71429,72.14286 l 55,23.57143 -0.71429,-95 z">
      <title>sample text 1</title>
    </path>
    <path fill="blue" d="m 97.42857,809.50506 c 0,42.85714 0,43.57143 0,43.57143 l 55,-0.71429 0,-43.57142 z">
      <title>sample text 2</title>
    </path>
    <path fill="green" d="m 97.21429,766.3622 c 0,42.85714 0,43.57143 0,43.57143 l 55,-0.71429 0,-43.57142 z">
      <title>sample text 3</title>
    </path>
</svg>
Comment: @iamcastelli you can't use pseudo with SVG
Comment: how can we apply css for that text? can you suggest me please
Comment: You can't, but that wasn't a requirement stated in the question.
Comment: yeah, but now I want to apply css in that popup, so is there any other way to write !?
Comment: You would use `pseudo` elements the `before` and `after`. Style the elements however you like, then update the content `css` attribute with the value. Note, you lose auto positioning of the tooltip with plain css.


NASA World Wind Documentation for C#

Question: I have just started working on NASA world Wind Application in C#. But I am not be able to find documentation or tutorials for C# WW application. Please tell me if there is any help or documentation for NASA C# World Wind.
Answer: I found this, it doesn't look like full documentation, but it's something, http://issues.worldwind.arc.nasa.gov/confluence/display/WWNET/Home;jsessionid=843B4699FE2945F2A9A363F9D87A1294.
I noticed that some of the links just go to blank pages, but not all of them.
Answer: Part of the problem might be that NASA no longer has funding to support the C# version as of last year as indicated by a post from their forum. This might be why you're hard pressed to find information.
http://forum.worldwindcentral.com/showthread.php?t=25201

NASA World Wind Documentation for C#