Help identifying cadences and modes in iidim7 - i - vidim - vsus4

Question: I'm a beginner when it comes to modes and cadences, and I want to understand them better to improve my song-writing as a metal guitarist. While fiddling with my guitar today, I "wrote" this progression in the key of E minor (or the E Aeolian mode, if I'm right):
ii half-dim 7 --> i (Em) --> vi dim --> v sus 4

Could someone tell me what type of cadence occurs between the bars 1 and 2,
and also between the bars 3 and 4?
If I understand correctly, only the modes have changed, because I have only used
notes from the key/scale of E minor. But what modes are these?
Why does the vi dim --> v sus4 feel like it has been resolved? I thought tension is resolved only when we return to the root/home chord.

(P.S. I feel I've heard this progression before, maybe someone knows where it's from? :) )
Comment: @aditya That chord is usually called "half-dim" or minor 7 b5.
Comment: Just to be sure, with "ii dim 7" do you mean F# A C with Eb or E?
Comment: Hi musicamante! With ii dim 7 I meant the notes F# C E A, not Eb. I can't find the right name for this chord, apparently
Comment: Please use the [Contact Us](/contact) form to have your accounts merged, to regain full control over your posts.
Answer: This progression lends itself to a variety of interpretations, all similar, but varying in technical detail. This progression, even more so than others, is highly dependent on context -- chord voicings, melody, and what happens before and after.
ii7 - i (F#7b5 - E minor)
ii moving to i as a cadence does not itself have a specific name.
However, it is related to a plagal cadence, iv - i. Although not a plagal cadence it provides a similar sound. And iv - i is built in: the iv chord = A C E, and the ii7 chord is the same but with the addition of F#. We could consider the chord as Am6 rather than F#m7b5.
A somewhat different interpretation comes into play if the E minor chord is voiced with B as the lowest pitch. In that case, it might be considered a "cadential 6-4 chord", heading toward the V chord at the end of the progression.
vidim - Vsus4
vi moving to V also doesn't have a special name. The usual interpretation is that vi is functioning as a predominant moving to the dominant.
However, the "vi dim" chord "doesn't exist." That is, a diminished chord built on the sixth scale degree, C, would be spelled C Eb Gb, with the latter three tones being alien to E minor.
Instead, I think one of two things is happening:

Cdim is actually D#dim7 with the fifth omitted. That makes the chord viio7 in E minor. The reason, then, it sounds like a cadence moving to Vsus4 is that Vsus4 is actually isus2. Vsus4 = BEF#, and isus2 = EF#B: i.e., it is, in fact, a cadence ending on the (ambiguous) i chord!
Also possible is that both the "C diminished" chord and the "B sus4" chords are a single chord: B7b9sus4(omit7). Written in root position, this chord doesn't appear to make sense: BD#EF#C. But with better voicing -- for example, BECD#F# or EBD#F#C -- it becomes a V chord with the E anticipating the (unresolved) resolution to Emin. This is very Mozartean, placing the tonic below a dominant chord (before proceeding to the tonic chord). (Note: in Mozart's case, the "dominant over tonic" chord is likely a suspension from an actual dominant, where the bass resolves first followed by a delayed resolution of the rest of the chord.)

overall mode
The progression is solidly in E minor and uses pitches only from the E harmonic minor scale. However, it's an ambiguous E minor due to the absence of a strong cadence confirming the key.
Comment: Thanks for the answer! I am slightly confused about the semantics: I thought the 'vi' of an E minor scale would be the note C (not C#). I played C dim and hence assumed it is "vi dim". Is this correct? I have not used C# in any of the four chords, so any mistake would be in my (lack of) knowledge of semantics. One can argue the notes belong to the E harmonic minor scale: 1 2 b3 4 5 b6 7 (there's no D anywhere).
Would this change your answer?
Comment: @aditya Dumb mistake on my part. Just to clarify before I update, is it a diminished triad or a fully diminished seventh chord?
Comment: I play the C minor triad with a flatted fifth: C Gb C Eb. I am not including a B or Bb so it isn't a seventh.
Comment: @aditya I've updated to address Cdim rather than C#dim. Please let me know whether or not the revised post makes sense and answers your question.
Comment: Thanks for the update! Why does `vi dim` not exist in E minor if both Eb and Gb are part of the E  harmonic minor scale (7th and 2nd)? About voicings: I always associated `i sus2` (played `R 5 9`) as a slightly dissonant chord. Can voicing (`R 5 9` to `5 9 5 R`) as `V sus4` really change a 'tense' chord to a resolved one? What can I do to understand why/how that happens?
Comment: @aditya In music theory "Eb" is not part of the key of E minor, but "D#" is. The pitches are what are known as "enharmonic equivalents", but the theoretical difference is essential to the analytical interpretation. To your other question, the name of a chord is dependent on the role it plays in the music, not so much the voicing. But the role in this case is ambiguous, which is why I offered two interpretations: one as a tonic chord and one as a dominant. These concepts are covered in an undergraduate-level music theory course; I'm not sure where else the might be addressed.
Comment: Thanks for the clarification! I think my questions in this thread have been answered.


Trouble understanding the bounds for marginal probability integrals

Question: Say we have a question such as this:

$f(x,y)= C\;\;\; 0<x<1,\; y>0,\; y<2x\;\;\;$ and $0$ otherwise.

I can calculate that $C=1$ from evaluating $$\int_0^1\left( \int_0^{2x}C \; dy \right) dx=1$$.Now to calculate the marginal I get $$f_X(x)=\int_0^{2x}dy=2x$$ However for $f_Y(y)$ I'm not sure which one of these two I would use and why: $$\int_{\frac{y}{2}}^1 dx=1-\frac{y}{2}\;\;\; OR \;\; \int_0^1dx=1$$ Does the marginal always have to contain the parameter? I'm thinking the second one since I already used the inequality $y<2x$ in the previous marginal? Or is it just completely separate, like you don't care you already used it, just that $x$ is between $\frac{y}{2}$ and 1? Sorry for all the questions :)
$\textbf{EDIT:}$
Also say I want to find the conditional probability $P(X>\frac{1}{3}|Y=1/2)$ is this zero? As a continuous probability distribution is zero at every point. I know I'd have to calculate the conditional probability distribution $f_{X|Y}$.
Answer: For $y\in(0,2)$:
$$f_{Y}\left(y\right)=\int f_{X,Y}\left(x,y\right)dx=\int_{0}^{\frac{1}{2}y}f_{X,Y}\left(x,y\right)dx+\int_{\frac{1}{2}y}^{1}f_{X,Y}\left(x,y\right)dx=$$$$\int_{0}^{\frac{1}{2}y}0dx+\int_{\frac{1}{2}y}^{1}1dx=1-\frac{1}{2}y$$

Edit concerning your edit.
Normally for a fixed $y_{0}$ as the conditional PDF $f_{X\mid Y=y_{0}}$
one takes the function that is prescribed by: $$x\mapsto c^{-1}f_{X,Y}\left(x,y_{0}\right)$$
where $c:=\int f_{X,Y}\left(x,y_{0}\right)dx$.
Doing that here with
$y_{0}=\frac{1}{2}$ we find $c=\int f_{X,Y}\left(x,\frac{1}{2}\right)dx=\int_{\frac{1}{4}}^{1}dx=\frac{3}{4}$
so that $f_{X\mid Y=\frac{1}{2}}$ is prescribed by $x\mapsto\frac{4}{3}$
if $x\in\left(\frac{1}{4},1\right)$ and $x\mapsto0$ otherwise. Based
on that we find $$P\left(X>\frac{1}{3}\mid Y=\frac{1}{2}\right)=\int_{\frac{1}{3}}^{\infty}f_{X\mid Y=\frac{1}{2}}\left(x\right)dx=\frac{4}{3}\int_{\frac{1}{3}}^{1}dx=\frac{8}{9}$$
But it must be admitted that this is somehow "questionable".
On the set $\left\{ \left(x,y\right)\mid y=\frac{1}{2}\right\} $
we could change the values of the original PDF almost as much as we
like without affecting its functionality as PDF for the original
distribution. This because the set has Lebesguemeasure $0$. The only
demands are that it stays a nonnegative and measurable function. However,
if we do things like that then we can end up with a totally different
conditional PDF $f_{X\mid Y=\frac{1}{2}}$.


How to enable/disable a Button depending on the selection's type in WPF?

Question: I want to trigger a button's enabled state, according to the type of the current selection.
E.g. I have a treeview that displayes parents and their children. If the selection is on a 'parent' item, the button 'btnShowParentData' is enabled.
I've done this via ValueConvertion:
<code><Button name="btnShowParentData" IsEnabled="{Binding ElementName=tree, Path=SelectedValue, Converter={StaticResource ParentSelectedConv}}" />
</code>
I look for a more elegant way. I don't want to create a ConverterClass for each selection type.
Answer:
I don't want to create a ConverterClass for each selection type.

You can have properties on the converter to parameterize it.
Comment: With your appraoch: Of what type would be the parameter? A simple string that is compared against typeof(ParentClass).Name?
Comment: Make it a `Type` and compare it directly, in XAML you can easily get `typeof(Class)` using `{x:Type ns:Class}`. (If the property is of type `Type` you don't even need `x:Type`, it gets converted automatically from the string)


How to add new int value to an existing one in a sql database through textboxes?

Question: I have a TextBox where I would ask the user to input a score which then gets stored in a database table column (Team1) on button click. Then, the button will also take you to a new page with a new TextBox where a new score can be entered also on button click, however, I want the new score to be added to the previous score in the same column (Team1).
code behind button 1
private void Btn_TeamSPage2_Click(object sender, RoutedEventArgs e)
{
    this.NavigationService.Navigate(new TeamS2());

    SqlConnection conne = new SqlConnection(@"Data Source=LAPTOP-S2J1U9SJ\SQLEXPRESS;Initial Catalog=Unit4_IT;Integrated Security=True");

    conne.Open();

    string insertQuery = "insert into T_Score(Team1) " +
        "values(@Team1)";
    SqlCommand com = new SqlCommand(insertQuery, conne);

    com.Parameters.AddWithValue("@Team1", Txt_Score.Text);

    com.ExecuteNonQuery();

    conne.Close();

}

Answer: Could you query the database to get the existing value of the field and the use an update instead of an insert if the select comes back with a a row of data?
You could also write a stored proc in your db that you could call from the C# code to add the vale to the DB's column


$f,g\in C_c^k(\mathbb R) \Rightarrow f*g\in C_c^{2k}(\mathbb R)$

Question: If $f,g\in C_c^k(\mathbb R)$ für $k\in\mathbb N$, is $f*g\in C_c^{2k}(\mathbb R)$. I think this is not true. How can I prove it?
Comment: compute the derivative of $f\ast g$ (the statement is actually correct)
Answer: Let us develop the proof of the statement methodically:
Firstly, $$f \ast g \in C(\mathbb R)$$ for $f, g \in C_c(\mathbb R)$. This follows from the dominated convergence theorem (or the theorem of the continuity of parameter integrals, which is in fact a corollary of the dominated convergence theorem). Moreover, one has $f \ast g \in C_c(\mathbb R)$ due to the fact that $\operatorname{supp} f \ast g \subseteq \operatorname{supp} f + \operatorname{supp} g$. In particular, the set on the right hand side is compact as $+ \colon \mathbb R \times \mathbb R \to \mathbb R$ is continuous and $\operatorname{supp} f$ and $\operatorname{supp} g$ are compact. Thus, it follows that also $\operatorname{supp} f \ast g$ is compact as a closed subset of a compact set.
Next it follows from the dominated convergence theorem (or the theorem of the differentiability of parameter integrals, which is another corollary of the dominated convergence theorem) that $$f \ast g \in C^1_c(\mathbb R) \qquad (f \in C^1_c(\mathbb R), \,g \in C_c(\mathbb R)).$$ This observation serves then as the base case of an induction over the order of regularity $k \in \mathbb N$. Thus, by induction, one obtains $$f \ast g \in C^k_c(\mathbb R) \qquad (f \in C^k_c(\mathbb R), \, g \in C_c(\mathbb R)).$$ Now there are (at least) two ways to deduce your desired statement. Either you prove with the dominated convergence theorem that
$$f \ast g \in C^{k + 1}_c(\mathbb R) \qquad (f \in C^k_c(\mathbb R),\, g \in C^1_c(\mathbb R))$$
and use induction over $\ell \in \mathbb N$ to obtain
$$f \ast g \in C^{k + \ell}_c(\mathbb R) \qquad (f \in C^k_c(\mathbb R),\, g \in C^\ell_c(\mathbb R))$$
or you use the argument below. Then the statement follows as the special case where $k = \ell$. However, one can use the another (more elegant) approach to prove the base case $\ell = 1$ and the induction steps. I just write it down for $\ell = 1$ since generalizing it is straightforward:
Let $f \in C^k_c(\mathbb R)$ and $g \in C^1_c(\mathbb R)$. Then integration by parts yields
\begin{align*}
f \ast g (x) &= \int_{\mathbb R} f(y) g(x - y) \, \mathrm d y \\
&= \biggl[F(y) g(x - y) \biggr]_{y = -\infty}^{y = \infty} - \int_{\mathbb R} F(y) g'(x - y) \, \mathrm d y = - F \ast g'(x)
\end{align*}
for all $x \in \mathbb R$, where $F \colon \mathbb R \to \mathbb R, \, F(x) := \int_{-\infty}^x f(y) \, \mathrm d y$. For each $h \in C^1_c(\mathbb R)$ one has that $\operatorname{supp} H, \operatorname{supp} h' \subseteq \operatorname{supp} h$ and since we know that $g' \in C_c(\mathbb R)$ and $F \in C_c^{k + 1}(\mathbb R)$ by the fundamental theorem of calculus, we can conclude that $f \ast g = -F \ast g' \in C_c^{k + 1}(\mathbb R)$ by what we have already shown.
The idea behind that argument is that you can shift regularity of functions in a convolution from one side to another by means of integration by parts and this is often very useful to get control over terms of poor regularity. In particular, if you have $f \in L^1_{\operatorname{loc}}(\mathbb R)$ (which is the bare mininum of regularity when you want all convolutions with functions of compact support to exist), then you have
$$f \ast g \in C^\infty_c(\mathbb R) \qquad (g \in C_c^\infty(\mathbb R)).$$
So convolutions with regular functions make even badly behaved functions regular. This idea of regularization is the back bone of the theory of distributions and the abstract reason that the heat equation is regularizing initial distributions in an abitrarily short time span $t > 0$ to smooth functions. This is namely just the result of the smoothness of the heat kernel. I hope things got a little bit more clear :-)


Why can't I populate and return my array created with rb_ary_new?

Question: I'm not able to insert values into a Ruby array, and retrieve them later.
I put the results of different lines that I tried inside the first function. The results are:
VALUE rStraightCards;

static VALUE check_for_straight() {
    stuff...

    if (begin_straight != NOT_FOUND) {
        for (i = begin_straight; i >= end_straight; i--) {
           // this gives me a segmentation fault when I call straight_cards()
            rb_ary_push(rStraightCards, i);

            // these lines give me an empty ary when I call straight_cards()
            // RARRAY_PTR(rStraightCards)[i] = i;
            // RARRAY_PTR(rStraightCards)[INT2NUM(i)] = INT2NUM(i);
        }
    }
}

VALUE straight_cards() {
    return rStraightCards;
}

void Init_straight_count() {
    rStraightCards = rb_ary_new2(NUM_CARDS);
}

Answer: Both arguments for rb_ary_push are supposed to be of type VALUE but you're pushing an int (probably):
VALUE
rb_ary_push(VALUE ary, VALUE item)
{
    rb_ary_modify(ary);
    return rb_ary_push_1(ary, item);
}

Try this:
rb_ary_push(rStraightCards, INT2NUM(i));

I think it is worth noting that VALUE will usually be defined like this:
typedef uintptr_t VALUE;

So the usual warning flags for int-to-pointer conversions won't catch this sort of error.
Comment: Hi mu, sorry I left out of my question the fact that I had tried rb_ary_push(rStraightCards, INT2NUM(i)); and it returned the stack dump.  I edited my question now that I have pinpointed the nature of the problem.
Comment: @Jeremy: I don't know what you mean by "This returns a stack dump", do you mean that it is segfaulting? And `Qnil` is already a `VALUE` (`(VALUE)RUBY_Qnil` in particular) so pushing that onto an array should be okay.
Comment: Hmm, actually I had misdiagnosed my error.  It was an unrelated line of code that I had in there for debugging :(


Prove that a particle is traveling on a plane from its velocity and acceleration in space

Question: We have a particle that travels in 3d space. It is given that $a(t)=-r(t)$.
First I need to prove that: $$\frac{d}{dt}(\underline r \times \underline v)=0$$ This is easily done:
$$
\frac{d}{dt}(\underline r \times \underline v)=r(t) \times r''(t)+r'(t) \times r'(t)=0
$$
Then I need to prove that the vector $\underline r \times \underline v$ is a constant. This leads immediately from the previous fact:
$$
\frac{d}{dt}(\underline r \times \underline v)=0 \Rightarrow \int \frac{d}{dt}(\underline r \times \underline v)dt=0 \cdot t+C=C.
$$
Then I need to prove that $\underline r \times \underline v$ is perpendicular to $\underline r$:
$$
\vec{r}\cdot (r \times v)=v(r\times r)=v \cdot0=0
$$
From this I need:
1) to prove that the particle is moving on a plane
2) find on which plane and with what normal vector.
3) find a point that the particle passes
For this I made this sketch:

My guess is that:
1) normal vector is $r\times v$ which is $\overrightarrow{BD}$ in the picture.
2) The plane is defined by the normal vector and any point on the curve.
3) the particle definitely passes through the origin $(0,0,0)$.
Yet this doesn't really make sense because one could think that every particle always travels on the same plane.
Comment: A particle doesn't have to obey the law of $\frac{d}{dt} (\vec{r} \times \vec{v}) =0$ , this happens only sometimes. Do you have any more facts given in the question that you didn't show us? Because if not, your proof is invalid.
Comment: That is an important detail, why would it be a general truth? take for example $r(t)=(t,t^2,t^3)$ then $a(t)=(0,2,6t)\neq -r(t)$. Almost any given $r(t)$ won't satisfy the equation you just wrote
Comment: Ok, just making sure you're aware of the identity and not just guessing that it is a valid one :) . I will now answer your question fully in the answers section
Comment: @OfekGillon there're no additional facts given. This is from a calculus course I suppose we're not interested in the problem from the physical perspective. It does say that $a(t)=-r(t)$ but I assume this is a general truth.
Comment: @OfekGillon I thought it always holds. Added the detail to the post. thanks.
Comment: Your welcome. Another thing, can you explain this part in your proof?
$\vec{r}\cdot (\vec{r} \times \vec{v}) = \vec{v} \cdot (\vec{r} \times \vec{r})$
Comment: @OfekGillon this is an identity that was taught to us.
Answer: I'll define for convenience $\vec{r}\times \vec{v}$ as $\vec{L}$
You proved that $\frac{dL}{dt}=0$ and hence $\vec{L}$ is constant.
That means there is a constant vector which is always perpendicular to $\vec{v}$, and that means the motion is restricted to a plane ($L$ is the vector perpendicular to the plane). That answers too the normal vector part in question (b).
So your guesses were correct but you thought that every particle has the property of $r(t) = -a(t)$, which is only right for a particle attached to a spring.
Comment: No, for $r(t)=(\cos t , -\sin t , 0)$ this doesn't happen
Comment: OK, now I can say that the answer is the origin. Here is an explanation:
Suppose $L = (L_x , L_y , L_z)$ and $r=(x,y,z)$ , then we know that $L_x x + L_y y + L_z z = 0$ because $\vec{L} \cdot \vec{r} = 0$. Here I defined a plane that passes through the origin (substituting $x=y=z=0$ solves the equation) and the motion is restricted to it (because $L$ is constant)
Comment: So the normal vector is $\overrightarrow L$ right? And the the particle has to pass through the origin?
Comment: I thought that $a=-r$ always because in our book they say that because $F=ma$ then $a$ and $r$ have opposite directions. Then they say that $r \times a=0$
Comment: So when they ask about a point that the particle passes through, what point do they mean?
Comment: Do you have any initial values for the position and velocity?
Comment: No I don't have any other details
Comment: Are you sure you're not missing anything that looks trivial?
Comment: After clarifying the problem details with our teacher, I need to say through which point the plane goes through
Comment: $L$ is the normal vector to $r$. The scalar product of any vector and its normal vector is $0$. Does this mean that every plane goes through $0$?
Comment: Also what if $r=(0,5,0)$ and $L=(5,0,5)$?
Comment: Yos, you can try and check that if a particle is moving on a plane that doesn't go through the origin, $L$ isn't conserved :)
Comment: What is "conserved"? Do all planes pass through origin?
Comment: Constant with respect to time. For example, conservation of energy means that energy is constant in time
Comment: Or are you saying that if $(0,0,0)$ solves $L \cdot r$ then the plane passes through origin? We can also find infinitely many more points then right? (permutations of a zero within three coordinates with all numbers)


I need a strongloop example wrote in javascript without angular

Question: I want to have a strongloop example only using javascript without angular.
There's no complete working example without angular for now.
I want to simply include the browser.bundle.js in my index.html, then sync data from/to server side. In fact, I'm trying to replace pouchdb in my program since the couchdb seems not success in open source community.
I can't follow up this document correctly:
Running Loopback in the browser

create browser-app.js with the content from Running Loopback in the browser
copy past the content to browser-app.js
npm install loopback loopback-boot
browserify browser-app.js -o app.bundle.js Then I got error: Error: Cannot find module 'loopback-boot#instructions' from '/Users/simba/Projects/traveller-app/client/node_modules/loopback-boot'
Comment: What specifically do you need an example for?  As I understand it, StrongLoop is a REST API framework for Node.JS.  Do you need examples of how to get something to work in StrongLoop?  Do you need examples of how to use JavaScript to interact with a RESTful API...?
Comment: Yes, I need write a client in phonegap. I want to simply include the browser.bundle.js in my index.html, then sync data from/to server side. In fact, I'm trying to replace pouchdb/couchdb in my program since the couchdb seems not success in open source community.
Answer: There are few steps for this but its pretty simple.

Bootstrap your application via slc loopback.
Delete server/boot/root.js.
Uncomment two lines in server/server.js, it should look like:
...
// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:
var path = require('path'); //this line is now uncommented
app.use(loopback.static(path.resolve(__dirname, '../client'))); //this line is now uncommented
...

Create index.html in the client dir (ie. client/index.html) with your contents.

That should get you a basic set up with just a basic front-end working. Let me know if you have any more issues.
Comment: Thanks, then I know how to host index.html for now.
Comment: Still, I can't follow up this document. http://docs.strongloop.com/display/LB/Running+LoopBack+in+the+browser
1. create browser-app.js with the content from strongloop
2. copy past the content for browser-app.js
3. npm install loopback loopback-boot
4. browserify browser-app.js -o app.bundle.js
Then I got error:
Error: Cannot find module 'loopback-boot#instructions' from '/Users/simba/Projects/traveller-app/client/node_modules/loopback-boot'
Comment: Take a look at this example, https://github.com/strongloop/loopback-example-full-stack/blob/c06a292ef95060f20339b18afab4467f36435997/client/lbclient/build.js


Redirect a view page to another view page with arguments in the url

Question: I have a custom view with button in the main tab placed in the local_task tab bar area (Outcomes). I have sub local_task navigation items under that as well that are regular drupal views. (See below)
View | Edit | Outcomes
                     Outcomes Viewer | Custom View | Another Drupal View
When you click on Outcomes you are taken to the Custom View tab or the Default for that custom view. However I want to redirect the Outcomes tab to go to the Outcomes Viewer tab. The Custom View tab is the /default for the menu, so it is s separate link and should work.
However, you can not use /%/ in a redirect. Does anyone have any ideas on how to do this. I have tried the basics but am lost on how to make it work.
Thanks!
Comment: While this probably could have been done with some php. I ended up building a small custom module and implement hook_menu() to balance out the buttons path and order.
Answer: So, solving this took a few different directions to figure this one out.
The problem was I needed to redirect a view with an argument in the url (node/%/outcomes) to a new sub-button so there was an actual button. (Yes this is also a UX issue that the user needed to have the button)
So, I created a new panel page and in the content area I created new custom content. I used the module, php filter, this way I can use the PHP input for the wysiwyg. Then I pasted this code to redirect.
<code>global $base_url;
header("Location: %node/:nid");
</code>
That redirected and kept the argument so everything would work fine.
Hope that helps someone!


Localizar registro no MySQL por caractere específico

Question: Tenho uma banco chamado completo, cuja tabela dados é:
        id  cpf          nome
         1  38831370570  joao da silva
         2  27283620508  maria joaquina
         3  94470661945  carlos eduardo

Gostaria de 'Filtrar' todos CPFs q contenham determinado dígito na nona posicao, com base nisto:

"Para determinar em qual estado brasileiro um CPF foi emitido, é necessário obter o último algarismo do CPF, ignorando os dois dígitos de controle / verificadores. Um exemplo de como determinar este número é o CPF nº XXX.XXX.XX6-XX. Em destaque vemos o último número válido do CPF, ignorando os dígitos verificadores."

Quero buscar no banco todos CPFs do Rio de Janeiro, por exemplo, de acordo com esta relação:
 1. Distrito Federal, Goiás, Mato Grosso do Sul e Tocantins;
 2. Pará, Amazonas, Acre, Amapá, Rondônia e Roraima;
 3. Ceará, Maranhão e Piauí;
 4. Pernambuco, Rio Grande do Norte, Paraíba e Alagoas;
 5. Bahia e Sergipe;
 6. Minas Gerais;
 7. Rio de Janeiro e Espírito Santo;
 8. São Paulo;
 9. Paraná e Santa Catarina;
 10.Rio Grande do Sul.

Answer: Você vai usar SUBSTRING, que retorna um número especifico de caracteres.
No exemplo abaixo adiciono o SUBSTRING(cpf,9,1), que vai retornar o nono caractere e vai comparar com o número do estado desejado:
SELECT * FROM dados WHERE SUBSTRING(cpf,9,1) = '8'

No exemplo acima, serão retornados os CPFs de São Paulo. Você troca o número 8 pelo número do estado que você quiser.
Comment: A resposta agora está correta, fica sempre a sugestão de complementar com um [SQL Fiddle](http://sqlfiddle.com) para valorizar a resposta com uma demonstração.
Comment: Grato Amigo Me ajudou
Comment: @LeoCaracciolo qual erro está retornando ?
Comment: @LeoCaracciolo que bizarro, Oo agora eu to confuso, será que o cara me positivou errado?
Comment: E @LeoCaracciolo sua resposta está incorreta, ele quer o 9° digito sendo o numero do estado, o seu está puxando o ultimo, o 11°. Vou abrir no banco aqui.
Comment: @LeoCaracciolo O seu não está retornando nada porque não existe nenhum digito '8' na nona posição em nenhum dos registros da sua tabela :)
Comment: @LeoCaracciolo Porque tem número '8' na 11° posição, mas o correto é ter na nona, o seu está certo, basta por "SELECT * FROM dados WHERE SUBSTRING(cpf,9) = '8'"
Comment: É , ai depende do digito que você por, se colocar "SELECT * FROM dados WHERE SUBSTRING(cpf,9) = '5'" no seu banco vai retornar resultados pq existe '5' na nona posição.
Comment: @LeoCaracciolo Você tem razão, vou editar minha resposta.
Comment: Estava confundindo com a substring do Javascript também... mas obrigado pela correção.
Answer: Pode usar a função MID que retorna um número especificado de caracteres de uma string, dados uma posição e um comprimento iniciais.
 SELECT * FROM dados where MID(cpf,9,1) = 7;

Lista com 8 CPFs de exemplo

Resultado da query, mostrando apenas CPFs cuja 9ª posição é igual a 7:
No SQL Fiddle
No meu servidor:

Outra opção é a função   substr SELECT * FROM dados where substr(cpf,-3,1) = 7; SQL Fiddle
Comment: Grato Amigo Me ajudou


Rewrite htaccess file for more than one variable

Question: I have the following htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteRule ^archive/([^/]+)$ news?url=$1
RewriteRule ^cars/([^/]+)$ carbrands?brand=$1

This works fine but now I want to add something to the last rule so that it works with one and two variables.
I tried to do this by modifying the last rule to this:
RewriteRule ^cars/([^/]+)/([^/]+)$ carbrands?brand=$1&model=$2

So the code has to work to open just the page about the car brand but it should also work when I try to access the page of a car model of that car brand. Examples:
example.com/cars/bmw(.php)
example.com/cars/bmw/3-series(.php)

My modified rule only works for:
example.com/cars/bmw/3-series(.php)

How can I make this work for the car brand webpage too?
Comment: `^cars/([^/]+)(?:/([^/]+))?$`
Answer: If you don't mind having the "model" be blank, you can try:
RewriteRule ^cars/([^/]+)(?:/([^/]+|)$ carbrands?brand=$1&model=$2 [L]

Or, you'll need two rules:
RewriteRule ^cars/([^/]+)/([^/]+)$ carbrands?brand=$1&model=$2 [L]
RewriteRule ^cars/([^/]+)$ carbrands?brand=$1 [L]

one for each number of params.


In grails 4.0.5, moving datasource definition to runtime.groovy causes DB not to be created during tests

Question: I need to move the configuration of the datasource to runtime.groovy, because that configuration code need to access some of my classes.
In previous versions of grails, this was not an issue. However i find that if I move the environments block, and the default datasource block to runtime.groovy, Hibernate will not create the database, and my functional tests fail, obviously.
This is the configuration that I removed from application.yml:
hibernate:
    cache:
        queries: false
        use_second_level_cache: false
        use_query_cache: false

dataSource:
    pooled: true
    jmxExport: true
    driverClassName: org.h2.Driver
    username: sa
    password: ''

environments:
    development:
        grails.plugin.console.csrfProtection.enabled: false
        dataSource:
            dbCreate: create-drop
            url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    test:
        dataSource:
            dbCreate: update
            url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    production:
        hibernate:
            jdbc:
                use_get_generated_keys: true

Which in my runtime.groovy looks like this:
hibernate {
    cache {
        queries = false
        use_second_level_cache = false
        use_query_cache = false
    }
}

dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "org.h2.Driver"
    username = "sa"
    password = ""
}

environments {
    development {
        dataSource {
            dbCreate = "create-drop"
            url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
        }
    }
    test {
        dataSource {
            dbCreate: "update"
            url: "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
        }
    }

    production {
        hibernate {
            jdbc {
                use_get_generated_keys = true
            }
        }

        dataSource {
//production datasource setup irrelevant
        }
    }

I tried combinations, keeping some of it in application.yml, some of it in application.groovy, all of it in runtime.groovy. Keeping the test and dev sections in application.yml, and the runtime-specific environments in runtime.groovy, does not work either.
Nothing seems to work.
I can't leave it like this because my production mode needs to be able to connect a secrets store to set up the production datasource.
Is there some hidden switch I am missing with the newer versions of grails?
Additional notes, the following commands do work (server starts up):
./grailsw -Dgrails.env=dev run-app
./grailsw -Dgrails.env=test run-app
./gradlew shell -q

The tests fail complaining about missing tables when i run this:
./grailsw -Dgrails.env=test test-app

The tests that are failing are inheriting from GebSpec, as they are full functional tests that need to run against the controllers.
So it seems like Hibernate is not properly initializing when running functional tests, if I move the configuration away from application.yml?
Thanks
FINAL UPDATE
There is a typo in my code, as Jeff pointed it out. Thanks Jeff!
Answer: The config you show for your runtime.groovy should be in grails-app/conf/application.groovy (does not need to be runtime.groovy).  The problem with your config is you have this:
test {
    dataSource {
        dbCreate: "update"
        url: "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
    }
}

You have colons where you should have equals signs, like this:
test {
    dataSource {
        dbCreate = "update"
        url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
    }
}

Comment: The file at https://github.com/jeffbrown/luismunizdsconfig/blob/59c681442afcbb1d0a44331601ba3e97c892c5f2/grails-app/conf/application.groovy appears to work fine.
Comment: You can run `./gradlew iT` in that project to run the `GebSpec`.


Python error. FileNotFoundError: [Errno 2] No such file or directory:

Question: Running a python code but getting a weird error in regards to finding the working directory and file to run the script. FileNotFoundError: [Errno 2] No such file or directory: Please let me know if you have any suggestions or know how I may be able to fix the error.
Comment: The file or directory doesn't exist. You need to make it exist.
Comment: show us the code and a full stack trace
Comment: We need to see the code.
Comment: yes, I think you are missing a "\" symbol in your folder path. Try use the inline code to outline problem and put more details in the question, so people will be able to help you.
Answer: You need to add a "\" to the end of your folder path.
folder_path = 'T:\04. Testing\3. Wear Testing\TESTS\CKUW\180604 OP STRAPLESS\Survey Response Data\
Comment: You would join them using [**`os.path.join`**](https://docs.python.org/3/library/os.path.html#os.path.join).
Comment: OP is not using `os.path.join` but simply concatenating two strings, thus missing a back slash
Comment: @A.B. yes, but using `os.path.join` is the correct way to do it.


Direct limit commutes with direct sums in the category of abelian groups

Question: I want to show that direct limit commutes with direct sums in the category of abelian groups. (I need this when studying algebraic topology)
 To do this, I first need a concise setting to start a proof, but I got stuck with this.
Let $\{G_\alpha , f_\alpha^\beta \}$ and $\{H_i,g_i^j\}$  be directed systems of abelian groups, with directed index sets $A$ and $I$, respectively. Then we have to  show that the direct sum of the direct limit groups of these two directed systems are isomorphic to the direct limit group of the system $\{G_\alpha \oplus H_i, f_\alpha^\beta \oplus g_i^j \}$.
My question is

Actually I'm not sure that my assertion is true. Is it true?
Is my setting valid?
If 1 is true,  then it seems to be this isomorphism is natural. Is it right?

Thanks in advance
Answer: Denote the direct limit of $\left\{G_\alpha , f_\alpha^\beta \right\}$ as $G$, and the direct limit of $\left\{H_i,g_i^j\right\}$ as $H$. Then we claim that $G\oplus H$ is the direct limit of $\left\{G_\alpha \oplus H_i, f_\alpha^\beta \oplus g_i^j \right\}$. And your questions are answered by this claim.
The morphisms $G_\alpha\oplus H_i\rightarrow G\oplus H$ are induced by the morphisms $G_\alpha\rightarrow G$ and $H_i\rightarrow H$.
Suppose there is a compatible system of morphisms $G_\alpha\oplus H_i\rightarrow M$. Since $\operatorname{Hom}(G_\alpha\oplus H_i,M)\cong\operatorname{Hom}(G_\alpha, M)\oplus\operatorname{Hom}(H_i, M)$, this induces compatible systems of morphisms $G_\alpha\rightarrow M$ and $H_i\rightarrow M$. Then by the universal property of the direct limit, these morphisms factor through $G_\alpha\rightarrow G$ and $H_i\rightarrow H$. This immediately implies that the morphisms $G_\alpha\oplus H_i\rightarrow M$ factor through $G_\alpha\oplus H_i\rightarrow G\oplus H$. Therefore $G\oplus H$ is the direct limit of $\left\{G_\alpha \oplus H_i, f_\alpha^\beta \oplus g_i^j \right\}$ as claimed.

Hope this helps.
Comment: Does this result also hold true if we have a direct sum of an infinite number of abelian groups?


For a goal while there's a change of players, who gets the +1/-1?

Question: In hockey, there is a stat where players get +1 when their team scores while they are on the ice, and -1 when the opposite team scores when they are on the ice. (Cant remember the exact name of the statistic, if someone could inform me)
If a goal happens while there are not the expected number of players on the ice (like during a change of players, there is, at some point (for like a second) 4 or 6 players on the ice) who gets the +1/-1 in their stats?
Is it the outgoing player of the change? The incoming player? or does every player that has their skates on the ice at the precise moment the puck goes in gets the +1/-1?
Answer: The exact name of the statistic is called plus-minus.  Nothing fancy here for the name.  It does get complicated when players are changing as you may have 6 players on the ice at the same time.  For this reason, the player ending his shift should be credited with the plus whereas the player coming onto the ice should remain even, even though they are on the ice at the same time.  Note that this happens within split seconds and it is hard to know.  But in the NHL, this statistic is often reviewed to make the appropriate changes on the score sheet.

When an even-strength or shorthanded goal is scored, every player on the ice for the team scoring the goal is credited with a "plus." Every
  player on the ice for the team scored against gets a "minus."
A player's overall total is calculated by subtracting the minuses from
  the pluses. A high plus total is taken to mean that a guy is a good
  defensive player.
But it's a very broad measurement and there has always been
  disagreement over how useful a statistic it is.

Power play goals are not used in calculating plus-minus.
Shorthanded goals are used in calculating plus-minus.
Penalty shot goals are not used in calculating plus-minus.


Javascript - .push() multiple objects from for loop into multidimensional array

Question: I'm running a function that needs to push 16 objects into the i position of a multidimensional array.
I am able to push all the data into var = videoData using videoData.push(videoItem) but I need to end up with a multidimensional array where each nested array contains 16 objects.
//variables
videoData       = [],
countries       = ["GB", "ES", "PT", "VN", "ID"],
tags            = ["?tags=english", "?tags=spanish", "?tags=portugues", "?tags=vietnam", "?tags=indonesia"]

//function
function runTask(){
    for(var i = 0; i < countries.length; i++){
        axios({
            method: "get",
            url: api_url + tags[i],
            headers: {
                "Content-Type": "application/json"
            },
        })
        .then(function(response) {
            var sixteenVideos = response.data
            for(var x = 0; x < 16; x++){
                var videoItem = {
                    "keys": {
                        video: "vid" + [x+1]
                    },
                    "values": {
                        url: sixteenVideos[x].slug,
                        thumb: sixteenVideos[x].image,
                        title: sixteenVideos[x].title,
                        desc: sixteenVideos[x].description
                    }
                }
                videoData[i].push([videoItem]);
            }
            console.log(videoData);
        }).catch(function(error) {
            console.log(error);
        });
    }
}

I expect to end up with...
var videoData = [[vid01, vid02....vid16], [vid01, vid02... vid16]]

Comment: What is the current output? Is it something like  `[vid01,[vid01...]...]`?
Comment: No, it errors at the moment. It shows ```TypeError: Cannot read property 'push' of undefined```
Comment: That means that whatever `videoitem` is, is undefined. Are you sure you are properly getting the data? What is you `console.log(response);`? Also you are pushing an array of objects like that. Just do `.push(videoItem);`.
Comment: The answer below from Alex Gray works :)
Comment: don't forget to use `const`, `let`, or `var` when declaring variables
Answer: For loop works synchronously, when executing async operations inside for loop, by the time the promises are resolved for loop finished it's execution. So value of i will have the value from the last loop iteration in every resolved promise.
I don't think for loop is really needed here, it can be simpler to create a function that takes a tag and returns a promise which resolves to an array of 16 elements, it may look something like as follows:
var videoData = [];
var countries = ["GB", "ES", "PT", "VN", "ID"];
var tags      = ["?tags=english", "?tags=spanish", "?tags=portugues", "?tags=vietnam", "?tags=indonesia"];

var tasks = tags.map(runTask);
Promise.all(tasks).then(result => {
  console.log(result)
});

function runTask(tag) {
  return axios({
    method: "get",
    url: api_url + tag,
    headers: {
      "Content-Type": "application/json"
    },
  }).then((response) =>
    response.data
      .slice(0, 16)
      .map((video, index) => ({
        "keys": {
          video: "vid" + [index + 1]
        },
        "values": {
          url: video.slug,
          thumb: video.image,
          title: video.title,
          desc: video.description
        }
      }))
  ).catch(err => {
    console.log(err)
  })
}

Answer: You want to use a loop similar to this to build your multi dimensional array
function runTask() {
  var videoData = [];
  for (var i = 0; i < 6; i++) {
    var country = "Country -" + i;
    var countryArray = [];
    for (var x = 0; x < 16; x++) {
      var videoItem = country + ", Video -" + x;
      countryArray.push(videoItem);
    }

    videoData.push(countryArray);
  }
}

Answer: There's a lot of issues with your current code. I'm going to start from scratch in hopes that you can see a better way to approach this. First, axios has many low-level features that you shouldn't concern yourself every time you fetch json. Start with something like fetchJson -
const fetchJson = (url = "") =>
  axios
    ( { method: "get"
      , url
      , headers: { "Content-Type": "application/json" }
      }
    )
    .then(res => res.data)

Now when we write fetchVideos, we can depend on fetchJson and jump right into what we need to do with the parsed response -
const apiUrl =
  "https://my.api/"

const fetchVideos = ({ country = "", tag = "" }) =>
  fetchJson(apiUrl + tag)
    .then(apiVideos => apiVideos.map(videoFromApi)) // convert each video
    .then(videos => ({ country, videos })) // build response

Instead of relying on separate arrays of countries and tags, fetchVideo takes an object input such as -
fetchVideos({ country: "GB", tag: "?tags=english" })
  .then(console.log, console.error)

And it will output an object such as -
// { country: "GB", videos: [ v1, v2, v3, ... ] }

This prevents the need to use crude indexes to link values together. And we kept fetchVideos high level by depending on another function videoFromApi. This function will convert the API's video response data into the desired shape for our application -
const videoFromApi =
  ( { slug = ""
    , image = ""
    , title = ""
    , description = ""
    }
  , id = 0
  ) =>
    Object.assign
      ( { keys: { video: `vid${id + 1}` } }
      , { values:
          { url: slug
          , thumb: image
          , title: title
          , desc: description
          }
        }
      )

Now to tie this all together, we define an array of requests and use Promise.all to fetchVideos for each request. NB, this allows us to know precisely when all API fetches have completed so that our program can move to the next step -
const requests =
  [ { country: "GB", tags: "?tags=english" }
  , { country: "ES", tags: "?tags=spanish" }
  , { country: "PT", tags: "?tags=portugues" }
  , { country: "VN", tags: "?tags=vietnam" }
  , { country: "ID", tags: "?tags=indonesia" }
  ]

Promise
  .all(requests.map(fetchVideos))   // fetchVideos for each request
  .then(console.log, console.error) // then log the output, or error if incurred

// [ { country: "GB", videos: [ v1, v2, v3, ... ] }
// , { country: "ES", videos: [ v1, v2, v3, ... ] }
// , { country: "PT", videos: [ v1, v2, v3, ... ] }
// , { country: "VN", videos: [ v1, v2, v3, ... ] }
// , { country: "IN", videos: [ v1, v2, v3, ... ] }
// ]

To see a functioning demo, expand the snippet below and run it. axios has been mocked along with randomVideos so that we can simulate an API request -

const apiUrl =
  "https://my.api/"

const requests =
  [ { country: "GB", tags: "?tags=english" }
  , { country: "ES", tags: "?tags=spanish" }
  , { country: "PT", tags: "?tags=portugues" }
  , { country: "VN", tags: "?tags=vietnam" }
  , { country: "ID", tags: "?tags=indonesia" }
  ]

const fetchJson = (url = "") =>
  axios
    ( { method: "get"
      , url
      , headers: { "Content-Type": "application/json" }
      }
    )
    .then(res => res.data)

const fetchVideos = ({ country = "", tag = "" }) =>
  fetchJson(apiUrl + tag)
    .then(apiVideos => apiVideos.map(videoFromApi))
    .then(videos => ({ country, videos }))

const videoFromApi =
  ( { slug = ""
    , image = ""
    , title = ""
    , description = ""
    }
  , id = 0
  ) =>
    Object.assign
      ( { keys: { video: `vid${id + 1}` } }
      , { values:
          { url: slug
          , thumb: image
          , title: title
          , desc: description
          }
        }
      )

// mocks
const axios = async (req = {}) =>
  ({ data: randomVideos(4) })

const randomVideos = (n = 0) =>
  Array.from(Array(n), randomVideo)

const randomVideo = (_, id) =>
  ( { url: `videourl/${id}`
    , image: `images/v${id}.jpg`
    , title: `Video: ${id}`
    , description: `This is video ${1}.`
    }
  )

// run demo
Promise
  .all(requests.map(fetchVideos))
  .then(console.log, console.error)

// [ { country: "GB", videos: [ v1, v2, v3, ... ] }
// , { country: "ES", videos: [ v1, v2, v3, ... ] }
// , { country: "PT", videos: [ v1, v2, v3, ... ] }
// , { country: "VN", videos: [ v1, v2, v3, ... ] }
// , { country: "IN", videos: [ v1, v2, v3, ... ] }
// ]
Answer: Well, you can't do this "videoData[i].push" because the position on the array doesn't exist. Yo could solve this using an auxiliar array like this:
videoData = []
videoDataAux = []

and than:
for(var x = 0; x < 16; x++){
            var videoItem = {
                "keys": {
                    video: "vid" + [x+1]
                },
                "values": {
                    url: sixteenVideos[x].slug,
                    thumb: sixteenVideos[x].image,
                    title: sixteenVideos[x].title,
                    desc: sixteenVideos[x].description
                }
            }
            videoDataAux.push([videoItem]);
        }
videoData[i]=videoDataAux


Theming contact page form

Question: How to add in Drupal 8 a custom (suggestion) default contact page template ?
Thank you
Answer: Way 1: Use drupal template suggestion:
You can enable the template suggestions by following changes as mention in
https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates
Once you have the suggestions enabled you can see, drupal suggests few template possiblities for any page, you can use any of the suggested template.
https://cl.ly/1f2T0x1a1F2n
Way2: Declare custom template suggestions
Or you can customd define template based on any logic by implmenting hook_theme_suggestions_page_alter().
Example:
https://sqndr.github.io/d8-theming-guide/theme-hooks-and-theme-hook-suggestions/theme-hook-suggestions.html
Comment: glad it helped you!

Theming contact page form


Can you use $R^2$ and regression to estimate cause and effect?

Question: Does $R^2 * \mbox{slope}$ provide an estimation of cause and effect? For example, if $R^2$ of miles driven and coffee consumed is $x\%$ and the slope of the coffee-and-miles dataset is $y$ (miles/coffee), can you say "$z$ of each cup of coffee drunk is related to the number of miles driven"?
Comment: You are confusing me with using $R^2$ (proportion of data variability explained by the model, not the size of a cause) and estimated marginal effect represented by the slope coefficient (even in a pairwise regression without intercept term) in this strange (non-sensible?) fashion. If you are interested in impacts you may consider beta-coefficients or elasticity coefficients that really do have acceptable interpretation.
Answer: Regression gives you, essentially, a correlation. Correlation is not causality -- or else global warming would be caused by a decline in global number of pirates.
Comment: The regression only tells you the strength of the possible association, it says precisely nothing about causation.  It can't even tell you the direction of the causal relationship.  In this case, there are multiple confounding variables, so interpreting the regression in this way is very risky and should be accompanied by plenty caveats.
Comment: Okay, so let's take warming and pirates.  For example's sake, If the correlation between warming and pirates observed is -.8, (those predominantly tropical swashbucklers just can't seem to stand the heat), the r^2 is 64%.  Let's say the slope of the datasets is something like 1:-10.  Can you say "Of the 10 fewer pirates we saw in a year where the avg temp increased 1 degree, the retirement of about 6 of those brigands could be related to the temperature increase"
Comment: How are there more than one slope? If you regress pirates on global temperatures and find a coefficient of -10, then, for every one degree increase in global temperatures, the number of pirates falls by 10. If the global temperature increase by 0.5 degrees last year, then we expect that there were 0.5*(-10) more (or 5 fewer) pirates.


Strip BBCode via RegEx

Question: I am trying to setup a regex that will detect [quote]???[/quote] and will remove it.
This is what I have but it is not working:
$post['body'] = preg_replace("/\[quote\](.+?)\[\/quote\]/is", '', $post['body']);

Can anyone point me in the right direction?
I also want to remove any line brakes before or after the [quote]???[/quote].
Comment: Just figured it out: `$post['body'] = preg_replace("/\[quote\](.+?)\[\/quote\]/is", '', $post['body']); $body = trim(rtrim($post[0]['body']));`
Answer: Here's my test with your script:
$text = "I am trying to setup a regex that will detect [quote]???[/quote] and will remove it.\r\nThis is what I have but it is not working:";
$sentences = preg_replace("/\[quote\](.+?)\[\/quote\]/is", '', $text);
echo '
'.print_r($sentences, true).'
';

And my Output:
I am trying to setup a regex that will detect  and will remove it.
This is what I have but it is not working:

You can see: [quote]???[/quote] is removed.
I think your problem is anywhere else. Check the Value of $post['body']!
Maybe it is a misspelling and you meen $_POST['body']?
Answer: Just figured out my own issue.
$post['body'] = preg_replace("/\[quote\](.+?)\[\/quote\]/is", '', $post['body']);
$body = trim(rtrim($post[0]['body']));
Comment: trim() will remove spaces on both sides of a string. So there is no need to add another rtrim.

Strip BBCode via RegEx


Creating custom *.domain.com domains for sign-ups

Question: I am curious as to how, for example Beanstalk and Server Density, create custom domains (e.g. custom.beanstalkapp.com, custom.serverdensity.com) for each sign-up. I would like to do something similar so that clients and their staff access the web-app at their own sub-domain. Each app either uses LDAP or our own native user storage depending on client choice and would share a common API.
Does each custom domain share the same web app code base?
Taking this further what if I wanted to allow a completely custom domain as you can get with bit.ly pro. I'd imagine in this case the customer would point the A record for their domain to our web servers and then we would have to programatically edit our Apache configuration to add a new virtual host for that domain?
In this application the API is written in Java (using Restlet) with the front-end written in GWT. The data layer is built in MongoDB.
Answer: You can use wildcard dns and name based virtual hosts in apache to accomplish the subdomain bit.
Comment: and then parse the domain name in your code to serve the proper data for the requested domain
Answer: You want a web server where you can programatically change the configuration notably for the virtual hosts.
This will most likely mean that you will want an embeddable server to have full control of what goes on instead of hacking on a stand-alone server.  That is the first step.  Do that first.
Comment: Does this mean using something like Jetty?
Comment: @Christopher, I have found Jetty to be very useful, but I do not know if it is easy to do what you ask for as I have not done something like that.  The jetty mailing lists are very helpful, I would suggest you have a look at the doucmentation and if stuck, ask on the lists.


Conditional expectation for maximum function

Question: I have a discrete-time Markov chain queuing problem.
Packets (computer packets, that is) arrive in the intervals. $A_n$ denotes the number of arrivals in the interval $(n - 1, n)$, where $n \ge 1$, and the $A_n$ are independent and identically distributed. The probability mass function is $P(A_n = j) = \dfrac{1}{4}$ for $j = 0, 1, 2, 3$.
The packets first enter a buffer that can hold $K = 4$ packets. If the amount of packets arriving is greater than $K = 4$, then any surplus is terminated. One packet is dispatched per unit time (assuming there are packets waiting to be dispatched in the buffer), where unit time is, as I said, $n = 1, 2, \dots$. For time $n$, the packets are dispatched after the new entrance of packets $A_n$, but before the arrivals at the next time, $A_{n + 1}$.
$X_n$ is the amount of packets in the buffer at time $n$. This is before any packets have been dispatched. So we have that $X_n$ is a MC and has state space $\{ 0, 1, 2, 3, 4 \}$. We assume that the queue is empty at the beginning (that is, that $X_0 = 0$).
The $p_{i,j}$ are the elements of the transition matrix $P$.
Let $Y_n$ be the number of packets lost during the $n$th time slot.
So we have that
$$Y_{n + 1} = \begin{cases} \max\{ 0, A_n - K \}, & X_n = 0 \\ \max\{0, X_n - 1 + A_{n + 1} - K\}, & X_n > 0 \end{cases}.$$
I am trying to find $E[Y_{n + 1} \vert X_0 = 0]$.
I do not understand how to do this. Thinking about how conditional expectation is done, my understanding is that the expressions should look something like $E[ A_n - 4 > 0 \vert X_0 = 0 ] P(A_n - 4 > 0 \vert X_0 = 0)$, or something. But, honestly, I have no idea how to do this.
I would greatly appreciate it if people would please take the time to clarify this.
The solution is said to be $\dfrac{1}{4}p^{(n)}_{0, 3} + \dfrac{3}{4}p^{(n)}_{0, 4}$, where $p^{(n)}_{i, j}$ are the values of the $n$th-step transition matrix. It's not so much the solution itself that I'm interested in; rather, I'm interested in the calculations and reasoning that leads to the solution.

With regards to the transition matrix, the textbook presents the example as follows:

Let $A_n$ be the number of packets that arrive at the switch during the $n$th slot. Let $X_n$ be the number of packets in the buffer at the end of the $n$th slot. Now, if $X_n = 0$, then there are no packets available for transmission at the beginning of the $(n + 1)$st slot. Hence all the packets that arrive during that slot, namely $A_{n + 1}$, are in the buffer at the end of that slot unless $A_{n + 1} > K$, in which case the buffer is full at the end of the $(n + 1)$st slot. Hence $X_{n + 1} = \min\{ A_{n + 1}, K \}$. If $X_n > 0$, one packet is removed at the beginning of the $(n + 1)$st slot and $A_{n + 1}$ packets are added during that slot, subject to capacity limitations. Combining these cases, we get
$$X_{n + 1} = \begin{cases} \min\{ A_{n + 1} \}, K & \text{if} \ X_n = 0 \\ \min\{ X_n + A_{n + 1} - 1, K \} & \text{if} \ 0 < X_n \le K. \end{cases}$$
Assume that $\{ A_n, n \ge 1 \}$ is a sequence of iid random variables with common pmf
$$P(A_n = k) = a_k, k \ge 0.$$
Under this assumption, $\{ X_n, n \ge 0 \}$ is a DTMC on state space $\{ 0, 1, 2, \dots, K \}$. The transition probabilities can be computed as follows. For $0 \le j < K$,
$$\begin{align} P(X_{n + 1} = j \vert X_n = 0) &= P(\min\{ X_{n + 1}, K \} = j \vert X_n = 0) \\ &= P(X_{n + 1} = j) \\ &= a_j \end{align}$$
$$\begin{align} P(X_{n + 1} = K \vert X_n = 0) &= P(\min\{ A_{n + 1}, K \} = K \vert X_n = 0) \\ &= P(A_{n + 1} \ge K) \\ &= \sum_{k = K}^\infty a_k. \end{align}$$
Similarly, for $1 \le i \le K$ and $i - 1 \le j < K$,
$$\begin{align} P(X_{n + 1} = j \vert X_n = i) &= P(\min\{ X_n + A_{n + 1} - 1, K \} = j \vert X_n = i) \\ &= P(A_{n + 1} = j - i + 1) \\ &= a_{j - i + 1}. \end{align}$$
Finally, for $1 \le i \le K$,
$$\begin{align} P(X_{n + 1} = K \vert X_n = i) &= P(\min\{ X_n + A_{n + 1} - 1, K \} = K \vert X_n = i) \\ &= P(A_{n + 1} \ge K - i + 1) \\ &= \sum_{k = K - i + 1}^\infty a_k. \end{align}$$
Combining all these cases using the notation
$$b_j = \sum_{k = j}^\infty a_k,$$
we get the transition probability matrix
$$P = \begin{bmatrix} a_0 & a_1 & \dots & a_{K - 1} & b_K \\ a_0 & a_1 & \dots & a_{K - 1} & b_K \\ 0 & a_0 & \dots & a_{K - 2} & b_{K - 1} \\ \vdots & \vdots & \ddots & \vdots & \vdots \\ 0 & 0 & \dots & a_0 & b_1 \end{bmatrix}.$$
Comment: How are the $X_n$'s distributed? Do they have any relation to any other variables?
Comment: @DinosaurEgg Please see my edit. Does that clarify?
Comment: Could you check if the solution you wrote is indeed correct? The solution I got has one more term. Thanks
Comment: @DaviBarreira I have copied it correctly, but it is possible that the solution is erroneous. Feel free to post your answer, so that we can all review it and discuss (what could very well be an error in the provided solution).
Comment: Ok. I will revise and post it.
Comment: @DaviBarreira Thank you. It is not uncommon for authors to have incorrect solutions for more-involved problems such as these, so, as I said, that could very well be the case.
Comment: I revised and I got it wrong. I think your solution is indeed correct.
Comment: Unortunately i could not undestrand the sequence of events (dispatcing and entrance) and the instants at which transition probabilities are determined. Anyway, the answer follows from the law of total expectation.
Answer: So $X_n$ is a Markov chain with state space $\{0,1,2,3,4\}$ and $X_0=0$. Let us determine the transition matrix:
When $X_n \leq 1$, then $X_{n+1}=A_{n+1}$, because you dispatch the potential packet in the buffer before getting another one.
When $X_n \geq 2$, then $X_{n+1} = \min(4,X_n-1+A_{n+1})$.
So, writing everything out, the transition matrix (I'm considering the probability distributions of the $X_k$ as column vectors) is:
$P=\begin{bmatrix}
0.25 & 0.25 & 0    & 0    & 0\\
0.25 & 0.25 & 0.25 & 0    & 0\\
0.25 & 0.25 & 0.25 & 0.25 & 0\\
0.25 & 0.25 & 0.25 & 0.25 & 0.25\\
0    & 0    & 0.25 & 0.5  & 0.75\\
\end{bmatrix}$
Now, depending on the values of $X_n$ and $A_{n+1}$, we split into different cases:
$X_n \leq 2$: $Y_{n+1}=0$ (one packet is dispatched so there remains at most one, and at most three are added so none need to be dismissed)
$X_n = 3$: $Y_{n+1} = 1$ if $A_{n+1}=3$ and $0$ otherwise (explanation is similar to that below)
$X_n = 4$: then we dispatch one packet, (three remain) and add $A_{n+1}$ of them, and dismiss all the packet but four: thus the number of packets dismissed is $0$ if $A_{n+1} \leq 1$, $1$ if $A_{n+1} = 2$, and $2$ if $A_{n+1}=3$.
Having written this all out, we can write:
$\mathbb{E}[Y_{n+1}|X_0=0] = \mathbb{E}[Y_{n+1}1(X_n \geq 3)|X_0=0]$ (as $Y_{n+1}1(X_n \leq 2)=0$) and then split by linearity over the values of $A_{n+1}$ and $X_n$:
$\mathbb{E}[Y_{n+1}|X_0=0]=\mathbb{E}[1(X_n=3,A_n=3)+(A_{n+1}-1)^+1(X_n=4)|X_0=0]$.
Now, $\sigma(A_{n+1})$ and $\sigma(X_0,\ldots,X_n)$ are independent, so by the properties of conditional expectations, $\mathbb{E}[1(X_n=3,A_n=3)|X_0=0] = \mathbb{E}[1(A_n = 3)]\mathbb{E}[1(X_n=3|X_0=0)] = P(A_{n+1} = 3)P(X_n=3|X_0=0)=\frac{1}{4}p^{(n)}_{3,0}$ (I'm using column vectors to be applied to transition matrices, hence possibly the index reversal).
Similarly, $$\mathbb{E}[(A_{n+1}-1)^+1(X_n=4)|X_0=0] = \mathbb{E}[(A_{n+1}-1)^+]\mathbb{E}[1(X_n=4)|X_0=0] = \frac{1}{4}\left((0-1)^++(1-1)^++(2-1)^++(3-1)^+\right)p^{(n)}_{4,0} = \frac{3}{4}p^{(n)}_{4,0},$$ which shows the final formula:
$$\mathbb{E}[Y_{n+1}|X_0=0] = \frac{1}{4}p^{(n)}_{3,0}+\frac{3}{4}p^{(n)}_{4,0},$$ which we wanted to show.
Comment: Ok, I have edited my post with the textbook example of the transition matrix. How is this consistent with the matrix you presented?
Comment: Also, I don't understand your notation. What is meant by $1(X_n \geq 3)$ in  $\mathbb{E}[Y_{n+1}1(X_n \geq 3)|X_0=0]$?
Comment: $1(X_n \geq 3)$ (for instance) is the random variable that is $1$ when $X_n \geq 3$, and $0$ when $X_n < 3$.
Comment: For the transition matrix, mine is the transpose of yours (since $a_j=0.25$, $j < K=4$ and $b_4=0$). Indeed, in your transition matrix $T$, $T_{i,j}=P(X_{n+1}=j|X_n=i)$. In my transition matrix $P$, $P_{i,j}=P(X_{n+1}=i|X_n=j)$.
Comment: Hmm, so how exactly do we calculate what I'm looking for? You wrote that $\mathbb{E}[Y_{n+1}|X_0=0] = \mathbb{E}[Y_{n+1}1(X_n \geq 3)|X_0=0]$, but this just says that $\mathbb{E}[Y_{n+1}|X_0=0] = \mathbb{E}[Y_{n+1}1(X_n \geq 3)|X_0=0] = \mathbb{E}[Y_{n+1}|X_0=0]$ when $X_n \ge 3$. You left out precisely the calculations that interested in, no?
Comment: No: I split $Y_{n+1}$ according to the values of $X_n$. That line just says that we need only consider the terms when $X_n \geq 3$.
Comment: What is $\mathbb{E}[1(X_n=3,A_n=3)+(A_{n+1}-1)^+1(X_n=4)|X_0=0]$ supposed to mean? Is there a typo in here?
Comment: No: that's just an equivalent expression for $Y_{n+1}$. $1(X_n=3,A_{n+1}=3)$ is $1$ when $X_n=A_{n+1}=3$ and $0$ otherwise. $(A_{n+1}-1)^+1(X_n=4)$ is just a means to have a neat expression for $X_n=4$: no loss if $A_{n+1} \leq 1$, one if $A_{n+1}=2$, two when $A_{n+1}=3$.


Hide Views with custom module

Question: Hi I would like to create a custom module where I can do extra checks on a view and if those checks are not pass deny access. I'm not sure what hook to implement to achieve this.
Comment: Do you menu or module?
Comment: I'm sorry, custom module.
Answer: You need to implement two Views hooks: hook_views_api() and hook_views_plugins(). Have a look at views_views_plugins() in Views' /includes/plugins.inc file for an example implementation of the plugin hook; specifically, look at the plugins in the 'access' key.
Beyond that, look at the views_plugin_access* files in /plugins/ for examples of actual implementations.
Comment: I haven't done too much of this so please bear with me. So I create:
Comment: I haven't done too much of this so please bear with me. So I create the hook_views_api() which is essentially the version then I create MODULENAME.views.inc with the views_views_plugin() with the access section that has a handler to my custom plugin? I'm not really sure what to do with the handler? Just return t('Unrestricted'); if validation doesn't pass?
Comment: To be honest I can easily achieve what I want in the tpl file but I know this is not the drupal way and would like to do it correctly.
Comment: Never mind I was able to achieve what I wanted in template.php. Creating a module for this simple task seemed to create extra work that didn't need to be done.

Hide Views with custom module


EM algorithm special case

Question: I'm considering a collection of Bayes Factors, $\mbox{BF}(j)$, $j=1, ..., J$, so that the overall evidence against $H_0$ is represented by the overall Bayes Factor
 $$\frac{P(x|H_0 \mbox{ false})}{P(x | H_0 \mbox{ true})} = \sum_{j=1}^{J} w_j \mbox{BF}(j)\,,$$
where $\sum_{j=1}^Jw_j = 1$.
I now have access to a restricted set data from which I would like to estimate the optimal weights $w_j$: I can to compute the Bayes Factors $\mbox{BF}_i{(j)}$ for each observation $i=1, ..., n$ and for each $j=1, ..., J$, and I can form:
$$\prod_{i=1}^n \sum_{j=1}^{J} w_j \mbox{BF}_i(j)\,.$$
So the problem consists in finding weights that maximize this expression. I was wondering if we could consider this as a likelihood and compute a sort of EM algorithm, similar to that used for Gaussian mixtures.
However, as far as I understand, since I already have the $\mbox{BF}_i(j)$ computed, I wouldn't need to optimize the means and variances for each mixture(?)
...and in this case, I don't see how to apply the EM algorithm anymore.
I would be very grateful if somebody could help me on this.
Is the EM approach a good option? If yes, how exactly should I apply it? If no, is there a simple other strategies that guaranties $0 \leq w_j \leq 1$ $\forall j$ and $\sum_{j=1}^Jw_j = 1$ ?
Many thanks in advance!
Comment: I do not understand the rationale for an average of Bayes factors. Is there any case this is equal to a true Bayes factor? Can you provide an illustration when this naturally occurs? Thank you.
Comment: The denominator is the same for all Bayes Factors. It corresponds to the global null hypothesis.
Comment: Without going into too much detail, in my case, $j$ represents a partition of a set of variables involved in the model into different functions: some are directly associated with the quantity of interest, some are indirectly associated with it and finally, some are not associated. Here, the average is over all possible partitions and represents the overall evidence against the null ($H_0$: all the variables are unassociated).
Answer: If you treat the function to maximise$$\prod_{i=1}^n \sum_{j=1}^{J} w_j \mbox{BF}_i(j)$$as a pseudo-likelihood, this likelihood is a formal mixture where only the weights $w_j$ are unknown. Hence you can apply EM for that purpose (of finding a local optimum). The algorithm is as follows:

Start with an arbitrary value of $\mathbf{w}^{(0)}=(w_1,\ldots,w_J)$
Given the current value of the parameter $\mathbf{w}^{(t)}$, derive the expectations (E) of the latent variables $z_{ij}$ as$$\mathbb{E}_{\mathbf{w}^{(t)}}[Z_{ij}|x_i]=\dfrac{w_j^{(t)}BF_i(j)}{\sum_{k=1}^J w_j^{(t)}BF_i(j)}$$
Update the weights from $\mathbf{w}^{(t)}$ to $\mathbf{w}^{(t)}$ as
$$w_j^{(t+1)}=\dfrac{\sum_{i=1}^n \mathbb{E}_{\mathbf{w}^{(t)}}[Z_{ij}|x_i]}{\sum_{k=1}^J \sum_{i=1}^n \mathbb{E}_{\mathbf{w}^{(t)}}[Z_{ik}|x_i]}$$
Increase $t$ to $t+1$ and get back to Step 2. unless $\mathbf{w}^{(t)}=\mathbf{w}^{(t)}$

The justification for this representation comes from writing the mixture$$ \sum_{j=1}^{J} w_j \mbox{BF}_i(j)$$as the marginal of$$w_j^{z_{ij}} \mbox{BF}_i(j)^{z_{ij}}$$where $\mathbf{z_i}=(z_{i1},\ldots,z_{iJ})$ is a multinomial $\mathcal{M}(1;\mathbf{w})$, i.e. with only one component equal to one and all others equal to zero.
Comment: (+1) The EM algorithm here has nothing to do with a Gaussian density, it is merely an optimisation algorithm. The $BF_i(j)$ are numbers that we interpret as values of densities to apply EM, but even the normalisation you mention makes no sense because there is no reason whatsoever the Bayes factor is integrable in the observation... I said "pseudo" in that sense that we use an algorithm originally designed for a mixture of densities towards a different purpose, if with the same validation.
Comment: Ok, I got it now. Your help was more than useful. The algorithm is implemented and converges quickly towards what seems to be a global maximum (several starting points tested). Thank you very much!

EM algorithm special case


How can I store references to Java objects in Neo4j?

Question: How can I store references to Java objects in Neo4j?
Comment: Only [OODB](http://en.wikipedia.org/wiki/Object_database)s use to store object references, other databases don't do that. In Neo4j you would rather use a relationship to connect the entities. What is it you're trying to achieve?
Answer: Neo4j basically stores primitives like integers and strings. See the full reference on what can be stored in the apidocs for setProperty.
Answer: I managed to store objects into neo4j by first marshaling them to an XML (I'm using Xstream for that) and then unmarshaling when querying.


Code running in one theme but not the other

Question: I am using the Mobile Theme module to switch between my themes, in my primary theme's page-front template I have some PHP code including a select statement, it queries tables created by a contributed module. The code works fine in my primary theme but in the mobile theme, the PHP returns nothing. What could cause this change from one Theme's page-front to another? None of this code relies on template.php, but I copied that over in case.
Answer: Themes are highly cached. That's a reason why you should avoid logic in them if only you can. And if you have to, put it in template.php, not .tpl files. Probable reason of query not executed is that template got cached and Drupal sees no reason to evaluate files again. You could force it to, probably, but it would be a huge performance killer.
Move your queries to contrib module, and query-based logic to template.php and you'll be good.


How to calculate sum of series $\sum_1^\infty (nx-n+1)x^n $?

Question: I ask for some help with this question:
I need to calculate sum of series $\sum_1^\infty(nx-n+1)x^n $.
I tried this way:
$\sum_1^\infty(nx-n+1)x^n=\sum_1^\infty nx^{n+1}-nx^n+x^n=\sum_1^\infty nx^{n+1}-(n-1)x^n $
Lets $f_n(x)=nx^{n+1}$.
Then we have telescopic series
$\sum_1^\infty nx^{n+1}-(n-1)x^n=\sum_1^\infty f_n(x)-f_{n-1}(x)=\lim_{n \to \infty}nx^{n+1}$
In this stage I somehow do not now how to proceed next .
Thanks.
Answer: Your work is correct, now you should assume that $|x|<1$ to have the convergence and you find
$$\sum_1^\infty nx^{n+1}-(n-1)x^n=\lim_{n \to \infty}nx^{n+1}=0$$
Answer: You are correct. And
If $|x|\lt 1$, then $\lim_{n\to\infty}nx^{n+1}=0.$
If $|x|\ge 1$, then $\lim_{n\to\infty}nx^{n+1}$ diverges.
Do you know why?
Answer: HINT. Develop your term under the summation as n x^(n+1) - n x^n + x^n; you all now can rewrite the previous expression as x^2 [n x^(n-1)] - x [n x^(n-1)] + x^n and write the sums. The last term is a well known geometric progression for which you know the answer. Inside brackets, you already identified the first derivative of the first sum. I am sure you will easily finish from here.
Answer: You want $\sum_1^\infty(nx-n+1)x^n $. Assume that $|x|\lt 1$. We can write our sum as
$$(x-1)\sum_1^\infty nx^{n} +\sum_1^\infty x^n.$$
The last sum is just a geometric series.
For $(x-1)\sum_1^\infty nx^{n}$, rewrite as $x(x-1)\sum_1^\infty nx^{n-1}$. Note that
$\sum_1^\infty nx^{n-1}$ is the term by term derivative of $1+x+x^2+\cdots$, that is, of $\frac{1}{1-x}$. The derivative is $\frac{1}{(1-x)^2}$. When you put things together, there is pleasant simplification.


Linear transformation

Question: I have $2$ questions here, please help me thanks!!

Find $2$ bases $a=(v_1, v_2, v_3)$ and $b=(w_1, w_2, w_3)$ of $\mathbb{R}^3$ such that both of them are non standard and yet the matrix of the identity map $I: \mathbb{R}^3 \to \mathbb{R}^3$ is the identity map.
Let $U$ be a $4$ dimensional vector space over $\mathbb{R}$ and suppose that $U=V+W$, where $\dim V=\dim W=2$. Further, assume that $\{v_1,v_2,w_1,w_2\}$ is a basis of $U$, where $\{v_1,v_2\}$ is a basis of $V$ and $\{w_1,w_2\}$ is a bsis of $W$. Let $T: U \to U$ be a linear operator such that

$T$ sends every vector in $V$ to a vector in $V$ and every vector in $W$ to a vector in $W$
$T$ sends every vector in $V$ to a vector in $W$ and every vector in $W$ to a vector in $V$

What can you say about the matrix of $T$ with respect to the basis $\{v_1,v_2,w_1,w_2\}$ in either of these situations.
I don't really understand the questions. Thanks for the help again.
Comment: Ya,im aware that a=b, but i can just choose any bases? Soory, I;m quite weak in linear algebra.
Comment: Take $a$ any non standard basis. Set $b:=a$. Then the matrix is necessarily $I_4$.
Answer: Hints:
1) Prove that the matrix of $Id$ is $I_3$ the identity matrix if and only if $a=b$.
2) Think $2\times 2$ blocks. For instance, if $A$ is the matrix of $T$ with respect to the basis you took, then the upper-left $2\times 2$ block is the matrix of the restriction of $T$ to $V$, followed by the projection onto $V$.
Very concretely, take your first vector $v_1$. In case i), you know that $T(v_1)$ is in $V$, ie $T(v_1)=\lambda_1v_1+\lambda_2v_2$. What does that tell you about the first column of $A$?
Comment: Ref to 2) Elements in column A will be λ1 and λ2?
Comment: @Chloe Yes, exactly. The first column is $(\lambda_1,\lambda_2,0,0)$. I'm sure you can take it from here.
Comment: Then for the first Q can I prove in this way?I(v1)=1.w1+0.w2+0.w3,I(v2)=0.w1+1.w2+0.w3,I(v3)=0.w1+0.w2+1.w3, therefore v1=w1,v2=w2,v3=w3 and a=b.
Comment: @Chloe Yes. 2.1) The first two columns are of the form $(.,.,0,0)$. Then with the same reasoning, you see that the third and fourth columns are of the form $(0,0,.,.)$. This gives to zero blocks upper-right and lower-left.
Comment: @Chloe Sorry, I did not see your edit. Yes, for the first Q, you've just shown that if the matrix is $I_4$, then the two bases are equal. But note the question actually leads you to do the converse. Take $a=b$ and show the matrix is $I_4$. I just gave the equivalence in my answer because I thought it would lead you to a better understanding.
Comment: So even though the question asks me for the bases, there's no need for me to give a specific value for a and b?
Comment: @Chloe You could give a specific example to make it concrete. But any nonstandard basis $a$ will work if you set $b:=a$. For instance, take $v_1=(1,1,0)$, $v_2=(0,1,0)$, and $v_3=(0,0,1)$.
Answer: Pick any basis $a$ and $b$ such that $a = b$. Its easy to see why: $I(v_1) = v_1$ so you want $v_1 = w_1$ to give $T(v_1) = w_1$. This means that the entries in the first column are $1, 0, 0, 0$ and if you do the same for $v_2$ and $v_3$, then the diagonal entries of the matrix of $I$ will be $1$ and all other entries will be $0$. For the first part to the second question, we must have
$$
T(v_1) = av_1 + bv_2\\
T(v_2) = cv_1 + dv_2\\
T(w_1) = ew_1 + fw_2\\
T(w_2) = gw_1 + hw_2
$$
for some constants $a, b, \dotsc, h$. So the matrix is in the form
$$
\begin{pmatrix}
A & O\\
O & B
\end{pmatrix}
$$
where $A, B, O$ are matrices with $A,B$ contain the constants and $O$ being the zero matrix. Similarly, for the second part the matrix must be in the form
$$
\begin{pmatrix}
O & A\\
B & O
\end{pmatrix}
$$
Comment: Why the second part to the second q is (OBAO)??
Comment: All vectors in $V$ go to $W$. So we have $T(v_1) = aw_1 + bw_2$ and $T(v_2) = cw_1 + dw_2$ for some constant $a, \dotsc, d$ using the basis for $W$. Since it is an ordered basis, the first two columns are $0, 0, a, b$ and $0, 0, c, d$. So you can clearly see that the top left $2 \times 2$ block is zero and the bottom left is some matrix $B$ which we don't know. Finding the right side of the matrix is similar. To answer these questions, all you need to know is how to find the matrix of a linear map (which is very easy if you know it). If you don't know how to do it, please review it.

Linear transformation


Generate price from item selected in drop down

Question: I am using Drupal 7.14, Commerce 7.x 1.3 and Views 7.x 3.3.
I want to have a drop down list on my product display form (or content display form) containing, say:
Full Price, no coach required - £ 200
Full Price, Glasgow coach - £ 230
Full Price, Edinburgh coach - £ 230
Full Price, Liverpool coach - £220
....
and I want, when an item on the list is selected, the displayed price to change to the indicated value and, of course, this to be passed to the cart.
How can I do that.
Answer: You can do this using the Rules module: http://drupal.org/project/rules/.  That should already be up and running if you're using Drupal Commerce.
So just go to admin/config/workflow/rules and add a new rule that looks something like this:

Event: Calculating the sell price of a product
Condition: Entity has field: [commerce-line-item], Field:
Action: Set the unit price to a specific amount; Parameter: [commerce_line_item]; Value:  can either select another field to base this on or do a hard-coded value; Leave Price component type and Price rounding mode to their defaults
Test!

Let me know if this ends up working for you
Comment: Thanks so much, Boriana, for your very quick reply. Will try out your suggestions and get back to you.
Comment: Have go to the setting of the Action, but I don't know how to do this.  Have defined an additional field in the product type (booking_type) which is a drop down list with allowed values (key|value) How can I specify this as the value?
Comment: Under the 'Amount' section of that action, try expanding the 'Data selectors' section, and you'll see all the fields that you can use.  Just copy and paste the one that matches your drop down list... but if your drop down list contains text (vs. an Amount), that won't work very well.  Test it out.


Expected time to hit a single boundary in the Gambler's Ruin problem

Question: I have a traditional Gambler's  Ruin problem on a set of integers $0,1 \ldots , N$ with transition probabilities of $p(k,k+1) = p(k,k-1) = 1/2$.
In the text book we learned how to compute the expected hitting time in any one of the boundaries ( $0$ or $N$).
Now I face with a little bit different problem: Starting from $0$ what is the expected time to hit the boundary $N$.
My intuition is that I can convert the problem into a new one in which my starting point
is exactly in the middle of a sequence of $2N -1 $ elements and then I can use what we leaned in class regarding the hitting time in any one of the boundaries.
For example, consider a Gambler's Ruin problem on a set of integers $0,1 \ldots , 2N $.
starting from $N$. My hope is that the expected time to hit any of the boundaries ($0$ or $2N$) is the same as my original problem.
Is my intuition correct ?
edit: I start from $0$ and need to get to $N$ and it does not matter if I hit $0$ again and the process will continue in that case.
Comment: If the goal is to hit $N$ but the fortune reaches zero first, what happens? Reflection? Please state your question more precisely. The starting point is important as well.
Comment: I added clarification - hitting zero again will not terminate the process.
Answer: Assume that $p(0,1)=1$. Then the expected time to hit $N$ from $0$ is exactly $N^2$. To see this, consider a simple random walk $\{S_k\}_{k\ge 0}$, started at $S_0=0$ and stopped when it reaches $\{-N,N\}$. Then your process is simply $\{|S_K|\}_{k \ge 0}$.
Comment: Hi @YuvalPeres, this is unrelated to your answer, hence I would be deleting this comment soonest. Please could you help out with this question https://math.stackexchange.com/q/4441875/585488


Parametric equation for $n$-dimensional cone

Question: In the wiki-page, the explicit parametric equation for a right circular cone with apex at the origin and aperture $2\theta$ is only given for a $3$-dimensional cone whose axis coincides with the $z$-axis.
What would be the analogous formula for an $n$-dimensional cone with axis parallel to a vector $d$?
References and/or derivations are both very welcome. Thanks.
Answer: $\newcommand{\Reals}{\mathbf{R}}\newcommand{\dd}{\partial}\newcommand{\Cpx}{\mathbf{C}}\newcommand{\Basis}{\mathbf{e}}\newcommand{\Brak}[1]{\left\langle #1\right\rangle}\newcommand{\Vec}[1]{\mathbf{#1}}$If $\Vec{x}$ denotes a point of the unit sphere in the hyperplane orthogonal to $d$, the cone with vertex at the origin, having aperture $2\theta$ and opening along the ray spanned by $d$, can be parametrized by
$$
X(t, \Vec{x}) = t \frac{d}{\|d\|} + t\tan\theta\, \Vec{x}.
\tag{1}
$$
One way to turn this into a useful specification is to fix:

A parametrization $(f_{1}, \dots, f_{n-1})$ of the unit sphere in $\Reals^{n-1}$. (Stereographic coordinates cover the whole sphere with two conformal charts; generalized spherical coordinates might be preferable.)
An orthonormal basis $(\Basis_{j})_{j=1}^{n-1}$ for the hyperplane orthogonal to $d$.

Then write
$$
\Vec{x} = f_{1} \Basis_{1} + \cdots + f_{n-1} \Basis_{n-1}
$$
in equation (1).
Comment: Thank you (once again!). I'm a bit confused as to what $x$ is exactly. How would it look if $d$ consisted of $d_1,d_{1+(n+1)},d_{1+2(n+1)},\dots,d_n=\frac{-1}{\sqrt{n}}$ and $0$ otherwise?
Comment: Depending on $d$, $\Vec{x}$ could be something of a mess; that's why I'd pick an orthonormal basis for the hyperplane $H$ orthogonal to $d$, then use that basis to define a Cartesian coordinate system in $H$. Finding that basis may be a pain, but it's algorithmic using [Gram-Schmidt](https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process). (Not sure I understand the components of the $d$ you mention; my browser's math fonts may be a bit wonky, but it looks like $d_{1} = d_{1 + (n+1)} = d_{1 + 2(n+1)} = \dots = d_{n} = -1/\sqrt{n}$...?)
Comment: Separately, [Parametric Equations for a Hypercone](http://math.stackexchange.com/questions/13555) looks more-or-less equivalent, which makes me realize I neglected to divide $d$ by its magnitude in (1).
Comment: All right. Yeah, the notation is ugly (but you got it right) because I'm actually working with matrices in $\mathbb{R}^{m\times m}$ and there $d$ is a "unit matrix" $-1/\sqrt{n}I_n$, where $I_n$ is the identity matrix - I simply "reshaped" $d$ (as a matrix) to be an $m^2=n$-dimensional vector. And thank you for the reference!
Comment: Just realized that my notation of the entries of $d$ in vector form doesn't make any sense, sorry about that!
Comment: As it happens, it's not too difficult to write down $m^{2} - 1$ matrices forming an orthonormal basis of the traceless matrices (i.e., orthogonal to $-1\sqrt{m} I_{m}$): You only need Gram-Schmidt for the diagonal matrices; the others can be taken to be symmetric or skew-symmetric with precisely two non-zero entries (or simply to have a single $1$ and the remaining entries $0$).
Comment: Btw, in the answer you referenced, shouldn't $\phi_1$ run from $0$ to $2\pi$ and the rest run from $0$ to $\pi$, instead of the other way around? Also, the "central angle" in that question is half the aperture from this question, right?
Comment: Regarding angle ranges, I think you're right: There's an "initial longitude" that runs over a whole circle, and "successive dimensions are added" by a half-turn. (Modulo indexing, which I haven't carefully checked, Wikipedia agrees with you.) Also yes, $\theta = 2\alpha$ in the notation of the linked question.


Can someone help me with tis errors i get?

Question:  using System;
  using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
   using System.Windows.Forms;

  namespace Adaline
  {
  public partial class Form1 : Form
  {
    float d1, d2, d3, d4, eta;
    float y1, y2, y3, y4;
    float w10, w11, w12;
    float w20, w21, w22;
    float w30, w31, w32;
    float w40, w41, w42;
    float x10, x11, x12;
    float x20, x21, x22;
    float x30, x31, x32;
    float x40, x41, x42;

    float net, net1, net2, net3, net4;

    float dw10, dw11, dw12;
    float dw20, dw21, dw22;
    float dw30, dw31, dw32;
    float dw40, dw41, dw42;

        public Form1()
    {
        InitializeComponent();
    }
        public void Adaline(float x0, float x1, float x2,
                            float w0, float w1, float w2,
                            float d, float net, float y,
                            float dw0, float dw1, float dw2, float eta)
        {
            net = x0 * w0 + x1 * w1 + x2 * w2;

            if (net <= 0)
                y = 1;
            else
                y = -1;

            dw0 = eta * x0 * (d - net);
            dw1 = eta * x1 * (d - net);
            dw2 = eta * x2 * (d - net);

            string a = "{0}   {1}   {2}   {3}   {4}    {5}   {6}   {7}   {8}    {9}     {10}    {11}", x0, x1, x2, w0, w1, w2, d, net, y, dw0, dw1, dw2;
            listBox1.Items.Add(a);
        }

    private void button1_Click(object sender, EventArgs e)
    {
        eta = Convert.ToSingle(textBox20);

        d1 = Convert.ToSingle(textBox19);
        d2 = Convert.ToSingle(textBox18);
        d3 = Convert.ToSingle(textBox17);
        d4 = Convert.ToSingle(textBox16);

        w10 = Convert.ToSingle(textBox3);
        w11 = Convert.ToSingle(textBox2);
        w12 = Convert.ToSingle(textBox1);
        int passes = 0;

        x10 = Convert.ToSingle(textBox7);
        x11 = Convert.ToSingle(textBox11);
        x12 = Convert.ToSingle(textBox15);
        x20 = Convert.ToSingle(textBox6);
        x21 = Convert.ToSingle(textBox10);
        x22 = Convert.ToSingle(textBox14);
        x30 = Convert.ToSingle(textBox5);
        x31 = Convert.ToSingle(textBox9);
        x32 = Convert.ToSingle(textBox13);
        x40 = Convert.ToSingle(textBox4);
        x41 = Convert.ToSingle(textBox8);
        x42 = Convert.ToSingle(textBox12);

        while (passes <= 100)
        {
            Adaline(x10, x11, x12, w10, w11, w12, d1, net1, y1, dw10, dw11, dw12, eta);

            w20 = w10 + dw10;
            w21 = w11 + dw11;
            w22 = w12 + dw12;

            Adaline(x20, x21, x22, w20, w21, w22, d2, net2, y2, dw20, dw21, dw22, eta);

            w30 = w20 + dw20;
            w31 = w21 + dw21;
            w32 = w22 + dw22;

            Adaline(x30, x31, x32, w30, w31, w32, d3, net3, y3, dw30, dw31, dw32, eta);

            w40 = w30 + dw30;
            w41 = w31 + dw31;
            w42 = w32 + dw32;

            Adaline(x40, x41, x42, w40, w41, w42, d4, net4, y4, dw40, dw41, dw42, eta);

            w10 = w40 + dw40;
            w11 = w41 + dw41;
            w12 = w42 + dw42;

            passes += 1;
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

}

}
I get thiese errors:
1 Cannot use local variable 'net' before it is declared. The declaration of the local variable hides the field 'Adaline.Form1.net'
2 Cannot use local variable 'x0' before ot os declared.
3 Cannot use local variable 'w0' before ot os declared.
4 Cannot use local variable 'x1' before ot os declared.
.
.
.
Comment: The errors are very clear, just... you know, read them and take a minute to think.  Go look up the documentation.
Comment: Is this a homework? Please use the respective tag for this purpose.
Comment: Perhaps if the error said, "You cannot use variable Net because you haven't declared it at all."
Comment: @JohnKraft they are declared in the `Adaline` method signature.
Answer: You cannot format a string like this:
string a = "{0}   {1}   {2}   {3}   {4}    {5}   {6}   {7}   {8}    {9}     {10}    {11}", x0, x1, x2, w0, w1, w2, d, net, y, dw0, dw1, dw2;

Instead, you must use a formatting method, such as:
string a = String.Format("{0}   {1}   {2}   {3}   {4}    {5}   {6}   {7}   {8}    {9}     {10}    {11}", x0, x1, x2, w0, w1, w2, d, net, y, dw0, dw1, dw2);

The compiler believes that you are redefining x0, x1, x2, w0, etc...
Comment: but why does not print them as float values?
Comment: Try {0:f2} where 2 is digits past decimal
Answer: The errors likely stem from the fact that your Adaline() method has parameters with the same names as your members (e.g. net). Change their names or use the this prefix to reference your members instead of the parameters.
Answer: The second error is the cause of the other errors.
You have declared a method parameter with the same name as a method field. That hides the field inside the method.
That error causes the parameters not to be declared correctly, and you get another error for each time you use one of the parameters in the method.


Square roots of $-1$ in quaternion ring

Question: In this Wikipedia page it is said that the square roots of -1 in the quaternion ring are the elements of the imaginary sphere. I don't understand why this is so. I don't understand the system that's written there. If I do
$$(a+bi+cj+dk)^2=a^2-b^2-c^2-d^2+2(ab+cd)i+2(ac-bd)j+2(ad+bc)k=-1$$
the system we get is
$$\begin{cases} a^2-b^2-c^2-d^2=-1 \\ ab+cd=0 \\ ac-bd=0 \\ ad+bc=0 \end{cases}$$
I suppose this could be solved to get the same solution, but it is quite tiresome and I'd like to understand how to get to the prettier system the Wikipedia gives.
Comment: The norm of a quaternion is multiplicative i.e. $|q_1q_2|=|q_1||q_2|$, so if the square is $-1$, the norm squared is $a^2+b^2+c^2+d^2=1$.  So your first equation tells you that the only way this can be true is if $a^2=0$, i.e. $b^2+c^2+d^2=1$.  Oh, and your last three equations are wrong, it's not $ab+cd=0$, it's $ab=0$.  This is because when you multiply-out your first line $jk=-kj$, so the two terms with $cd$ in them cancel.
Answer: Add your first equation to $a^2+b^2+c^2+d^2=1$ and you get $a=0$, whence $b^2+c^2+d^2=1$.
Then observe
$$(b\mathbf{i}+c\mathbf{j}+d\mathbf{k})^2=-(b^2+c^2+d^2)+(cd-dc)\mathbf{i}+(db-bd)\mathbf{j}+(bc-cb)\mathbf{k} $$
$$=-1+0\mathbf{i}+0\mathbf{j}+0\mathbf{k}=-1.$$
Hence any quaternion $\mathbf{q}=a+b\mathbf{i}+c\mathbf{j}+d\mathbf{k}$ with $a=0,b^2+c^2+d^2=1$ is a square root of $-1$. The error in your calculations is that you didn't take into account anticommutativity, i.e.
$$(c\mathbf{j})(d\mathbf{k})=cd\;\mathbf{i}\quad\text{but}\quad (d\mathbf{k})(c\mathbf{j})=-dc\;\mathbf{i}.$$
Answer: They have it right. You have not been careful enough in $\pm$ signs. The coefficient of $i$ does begin with $2ab$ as you say, but then we get
$$ c j d k + d k c j = c d i - c d i=0.$$ And so forth.
Comment: Ouch, I found my mistake. I must remember that the binomial theorem only works in *commutative* rings. Thank you!

Square roots of $-1$ in quaternion ring


Não consigo salvar todos os registro do foreach - LARAVEL

Question: No id do usuário ele tem 2 registro só que na hora de salvar ele só salva 1 registro e não os 2, como devo fazer para salvar corretamente ?
Segue Código abaixo
Controller Lista os dados do usuário
public function listardados(){
    $matricula = Matricula::where('user_id', Auth::id())->get();

    //dd($matricula);
    return view('dashboard.renovacao.teste', compact( 'matricula'));
}

-- Controller Salva registro do form
public function store(RenovacaoRequest $request){

    $user = Auth()->user();

    $dados = $request->all();

    $renovacao = Renovacao::create($dados);

    return view('dashboard.renovacao.confirmacao', compact ('renovacao'));
}

-- View form
@extends('layouts.app') @section('content')

        <form class="form-horizontal " id="regForm" action="{{route('renovacao.store')}}" method="POST">

Solicitar Renovação

                {{ csrf_field()}}
                <right>
                    **Dados Cadastrados**
                </right>

                    @foreach($matricula as $matric)

has('user_id') ? 'has-error' : ''}} ">
                            Nome do Pai:
                            <input type="text" class="form-control" name="nomerespo[]" value="{{ $matric->nomedopai }}">

has('user_id') ? 'has-error' : ''}} ">
                            Nome do Aluno(a):
                            <input type="text" class="form-control" name="nomealuno[]" value="{{ $matric->nomealuno }}">

                @endforeach

                        Voltar
                            arrow_back_ios

                        <button type="submit" class="btn orange darken-4 btn-info right">Confirmar
                            save
                        </button>

    </form>

@endsection
Answer: Olá, as tags input no seu formulário estão com um nome fixo dentro de um @foreach isso faz que ao enviar um formulário com várias entradas apenas uma (de cada nome) seja realmente enviada.
Tente alterar o seguinte:
<input type="text" class="form-control" name="nomerespo" value="{{ $matric->nomedopai }}">
<input type="text" class="form-control" name="nomealuno" value="{{ $matric->nomealuno }}">

para:
<input type="text" class="form-control" name="nomerespo[]" value="{{ $matric->nomedopai }}">
<input type="text" class="form-control" name="nomealuno[]" value="{{ $matric->nomealuno }}">

Repare que os atributos name das tags foram alterados para um array, assim todos os campos serão enviados para o seu Controller
Caso a relação com Renovacao com usuário tenha sido definida e a propriedade $guarded ou $fillable estejam definidas em Renovacao poderá salvar o conteúdo com algo da forma: $user->renovacoes()->saveMany($dados) e o Laravel tratará da relação de chaves estrangeiras para você.
Edit
O laço for do seu formulário ficaria da seguinte forma:
@foreach($matricula as $matric)

has('user_id') ? 'has-error' : ''}} ">
            Nome do Pai:
            <input type="text" class="form-control" name="nomerespo[]" value="{{ $matric->nomedopai }}">

has('user_id') ? 'has-error' : ''}} ">
            Nome do Aluno(a):
            <input type="text" class="form-control" name="nomealuno[]" value="{{ $matric->nomealuno  }}">

@endforeach

O dd($request->all()) deve retornar o seguinte:

Pelos seus comentários e pelos prints notei que não há relação estabelecida no seu Model User com a renovacao que utilizei como exemplo, então não é possível criar com $user->renovacao()->createMany() ou qualquer outra operação relacionada a $user->renovacao().
Edit 2
Para deixar documentado, o array não estava aparecendo no seu dd, pois falhava na validação. Como o HTML foi alterado para enviar um array é necessário alterar as regras de validação também:
[
   'nomerespo.*' => 'required|string|max:255',
   'nomealuno.*' => 'required|string|max:255',
]

Esse código valida a entrada como um array.
Para utilizar o método create como você quer é necessário alterar o HTML novamente:
<input type="text" class="form-control" name="rematricula[{{ $loop->index}}][nomerespo]" value="{{ $matric->nomedopai }}">
<input type="text" class="form-control" name="rematricula[{{ $loop->index}}][nomealuno]" value="{{ $matric->nomealuno }}">

Repare que o nome do input foi alterado para rematricula e há mais um nível no array.
Agora no seu Contoller pode fazer algo o tipo:
$dados = $request->get('rematricula');

foreach ($dados as $key => $dado) {
    Rematricula::create($dado);
}

Sugiro verificar a entrada de dados que o Controller está recebendo e olhar a documentação do Laravel (https://laravel.com/docs/5.7/eloquent#inserts) para entender melhor o código.
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](https://chat.stackexchange.com/rooms/86262/discussion-on-answer-by-andre-minoro-fusioka-nao-consigo-salvar-todos-os-registr)
Comment: Só não entendi essa key no foreach, de onde vem ela ?
Comment:  eu adicionei para vir matricula_id como eu configuro para não aparece no form junto com os demais ?


Combination Problem with a Variable

Question: I have the following problem:

$_xC_6$ = $_xC_4$

I expand both sides to:
$$\frac{x!}{[(x-6)!]6!} = \frac{x!}{[(x-4)]!4!}$$
Next I multiply both sides by the denominator of the right-hand expression to get:
$$\frac{x![(x-4)!]4!}{[(x-6)!]6!}=x!$$
At this point things start to become a mess, so I'm wondering if these first few steps are correct.
EDIT: Similar, but different, problem:
$$_{12}C_4 = _xC_8$$ translates to: $$\frac{12!}{8!4!}=\frac{x!}{(x-8)!8!}$$
First, I multiply both sides by $8!$ to get:
$$ \frac{12!}{4!}=\frac{x!}{(x-8)!} $$
Then I reduce/simplify the RHS to get:
$$ \frac{12!}{4!}=(x-7)! $$ (I'm not completely confident this step is correct)
Here's where I get stuck. The LHS=19,958,400 but I can't figure out how to manipulate the factorial on the RHS to get to just $x$.
Thanks in advance!
Comment: $\frac{{x!}}{{(x - 8)!}} \ne (x - 7)!$, hence the equation $\frac{{12!}}{{4!}} = (x - 7)!$ is wrong. Rather, from $\frac{{12!}}{{4!}} = \frac{{x!}}{{(x - 8)!}}$, it is readily seen that $x=12$ is a solution: indeed, $12!=12!$ and $4!=(12-8)!$ (compare numerators and denominators).
Comment: It might help you to remember that the binomial coefficients ${}_p C_q$ are coefficients of the binomial expansion, and then see that they satisfy a symmetry, e.g. $(x+1)^4=x^4+4x^3+6x^2+4x+1$, from which you can see, e.g. that ${}_4 C_1={}_4 C_3$... try to do something similar with ${}_{12} C_4$.
Comment: @J. M. Thanks for your reply. The textbook I'm working from hasn't covered binomial coefficients yet. Is there an alternative way to look at it?
Comment: In that case, the best you can do is note that $12=4+8$
Comment: @Shai Covo Thanks. I now see, if not so readily, that is in fact what's happening. I'm trying to work through the algebra as much, if not more, than simply getting to the answer. What is the correct simplification of the RHS?
Comment: You repeatedly apply the relation $n!=n\cdot(n-1)!=n(n-1)\cdot(n-2)!=\cdots$
Comment: For the RHS, it holds $$\frac{{x!}}{{(x - 8)!}} = \frac{{1 \cdot 2 \cdots (x - 8)(x - 7)(x - 6) \cdots x}}{{1 \cdot 2 \cdots (x - 8)}} = (x - 7)(x - 6) \cdots x$$.
Comment: Thus, for example, $$\frac{{12!}}{{(12 - 8)!}} = (12 - 7)(12 - 6) \cdots 12 = 5 \cdot 6 \cdots 12 = {\rm 19958400}.$$
Comment: @Shai Covo Got it - thank you!
Comment: Glad it helped.
Answer: Your steps are correct. However, more simply, from your first equation
$$
\frac{{x!}}{{(x - 6)!6!}} = \frac{{x!}}{{(x - 4)!4!}},
$$
you can see (by dividing both sides by $x!$) that
$$
\frac{1}{{(x - 6)!6!}} = \frac{1}{{(x - 4)!4!}},
$$
hence
$$
\frac{{(x - 4)!}}{{(x - 6)!}} = \frac{{6!}}{{4!}}.
$$
The rest is easy.
Comment: Of course - dividing by x! makes perfect sense. Then the rest would be: 1/(x-6)(x-5)=30? Now I start to get lost again...
Comment: Nick: $\frac{{(x - 4)!}}{{(x - 6)!}} = \frac{{(x - 6)!(x - 5)(x - 4)}}{{(x - 6)!}} = (x - 5)(x - 4)$. So you need to solve $(x - 5)(x - 4) = 30$.
Comment: Nick: Moreover, it is readily seen that $x=10$ is a solution of $\frac{{(x - 4)!}}{{(x - 6)!}} = \frac{{6!}}{{4!}}$ (indeed, $10-4=6$ and $10-6=4$, hence $(10-4)!=6!$ and $(10-6)!=4!$).
Comment: Yes, I could see it given the numbers are small. However I wanted to ensure I could perform the computation to get to the answer. Thanks again for your help!
Comment: If you had $1/((x-6)(x-5)=30$, it would just be a quadratic equation:
$$
(x-6)(x-5) = \frac{1}{30}
$$
$$
x^2 - 11x + 30 - \frac{1}{30} = 0
$$

Combination Problem with a Variable