Contravariance problems with event properties

Question: Suppose I have a simple EventArgs subclass:
class MyArgs : EventArgs { }

Consider I have two classes with events:
class MyData {
    public event EventHandler<MyArgs> Method;
}

class MyObject {
    public event EventHandler Method;
}

And a simple program that uses them:
    static void Main(string[] args){

        MyObject o = new MyObject();
        o.Method += MyMethod;

        MyData data = new MyData();
        data.Method += MyMethod;

    }

    static void MyMethod(object sender, EventArgs e) { }

Thanks to Contravariance, MyMethod counts as both an EventHandler and an EventHandler<MyArgs>. However, if I change MyObject's event handler into a property that forwards the method to a MyData:
class MyObject {

    MyData data = new MyData();

    public event EventHandler Method {
        add { data.Method += value; }
        remove { data.Method += value; }
    }

}

The event property is unable to forward the EventHandler to the EventHandler. This seems strange to me because it seems to fall into the contravariance category - a handler with a weaker signature (base classes) should be able to accept arguments with a stronger signature (subclasses).
Why won't C# let me do this? Is there a way to tunnel a generic EventHandler down through an event property into an EventHandler? Is there some sort of legal cast that can be performed on the delegates?
Answer: There is no implicit conversion from EventHandler to EventHandler<T>.  However since both are of compatible types with each other, you could just pass the EventHandler to the constructor to "convert" it.
public event EventHandler Method
{
    add { data.Method += new EventHandler<MyArgs>(value); }
    remove { data.Method -= new EventHandler<MyArgs>(value); }
}

Comment: Huh - I hadn't thought of that. I didn't realize it was using implicit conversions there - thanks!


AEM Display DeActivate Later time

Question: In AEM (Adobe Experience Manager 6.2) a user can select a page to be "Activated Later" (Publish Later) and choose a date/time.  The Notifications display will show "Waiting for activation" with the date/time.  This is great.  But when a page is scheduled for deactivation using the "DeActivate Later" (UnPublish Later), the Notification does not contain the date/time.  Is there a way to add text to the comments section of a notification to include the date/time?  Or trigger AEM to fill it in?
Notifications:
Comment: This is by design in AEM. You cannot display the information unless you overlay this interface.
Answer: This is because of difference in workflow model of both requests.
workflow model for activation request

workflow model for deactivation request:

As you can see there is a Create version step in activation request. I think this step is setting above message.
If you want to create the unpublished version for your page, you can add the same step to deactivation model or create your own process step for adding the time stamp, then add the same to the deactivation model.
It should work.
Comment: The create version step does not set a time. It creates a version. The timestamp displayed in scheduled activation message is for the job schedule.
Comment: Thank you Pooja Chauhan for pointing me in the right direction.  I don't want to create a new version, but the CreateVersionProcess.execute() method has a line in it:
data.getMetaDataMap().put("comment", "Activate version " + revStr + " on " + cal.getTime().toString());
Which is what I need to do in my new workflow step.  I will try and report back on how it works.
Comment: @AlexHomeBrew , Glad it Helps !!!..  If you find the comment helpful give a upvote plz

AEM Display DeActivate Later time


Choice of 3/2 or 6/4 time signature

Question: Newbie question!  The time signature for this tune is 3/2 but could it just as correctly be marked as 6/4?  What criteria would you use to decide between the two or is there no difference?
http://www.folktunefinder.com/tunes/25251
Thanks
Comment: Perhaps this isn't quite a duplicate: 3/4 isn't the same time signature as 3/2. But it's close. The relationship between 3/2 and 6/4 is precisely analogous to the relationship between the much more common 3/4 and 6/8. If you read over the post yours is said to duplicate, you will find a lot of explanations that apply equally to your question.
Answer: There are good answers here.  But something that is unwritten in those answers thus far, but nevertheless will help you to understand them is that, traditionally, time signatures in multiples of 3 starting from 6 (ie. 6, 9, 12, 15, etc) are called compound meters, and have (n/3) beats beats per bar.  This is in contrast to simple meters, which are meters that subdivide exclusively into halves.  (4/4 is the most common simple meter.)
Since a numerator of 6 implies a compound meter, 6/8 actually has two beats, not six, and is often counted something like "One-and-ah Two-and-ah".
This makes 6/4 fundamentally a different meter from 3/2.
Comment: I agree, and I specifically said that it wasn't.  "starting from 6" is even italicized.
Comment: 3/8 time is not compound.
Answer: On paper it looks very much like 6/4, because of the positions of the minims, but actually it is syncopated. The computer performance is very slow and misleading. If you listen to a real performance, it is definitely 3/2, not 6/4.
That's because there are three beats in each bar, not two.
It is conventional to write 3/2 for three minims in a bar, and 6/4 for two dotted minims. They might be the same in terms of arithmetic, but the 6/4 form draws attention to itself as not 3/2, so it was adopted centuries ago as a way of saying "this is compound time."
Answer: 3/2 is three half-note beats in the bar.  6/4 is two dotted half beats.   Like 3/4 amd 6/8.   Is your piece predominantly three-in-a-bar or two-in-a-bar?
Comment: Apologies for being a bit thick - why is 6/4 considered two dotted half beats and not six quarter notes per bar (mathematically the same but certainly different in my eyes)?
Comment: @nigelr By convention, meters labelled as "6" are always subdivided as 3+3, not 2+2+2. If you want 2+2+2, that's what triple meter is for.
Comment: Music almost invariably groups in twos or threes.  It's obvious why 3/2 was chosen to represent three in the bar.  As there's no bottom number in a time signature 'fraction' to represent a dotted note, we use 6/4 (or 6/8, rarely 6/16) for compound duple (beat divisible into three, two of them).
Answer: I haven't listened to the piece, but given that we're deciding between 3/2 and 6/4 based on sheet music and not a recording, I'd listen to the piece and figure out whether every second quarter note sounds more emphasized (so 3/2) or every third quarter note is (so 6/4).
(If I were to decide on time signatures based solely on recordings, I'd likely use 3/4 or 6/8 instead, but I'd also have to figure out whether the emphasis is less on every second "triplet" (so more likely to be 6/8), for starters...)
Comment: My thought is that the majority is phrased as 2 groups of 3 crotchets except for bars 5 and 7 which are definitely 3 groups of 2 crotchets.  I'm confused!
Comment: This is the piece:  https://www.youtube.com/watch?v=A9uUlgV2IKM
Answer: Those time signatures have very little to do with each other. 6/4 is compound duple time with a beat consisting of a dotted minim where 3/2 time is simple triple time where a beat is equal to a minim.
You can covert simple an compound time signatures to each other while you keep to the amount of beats. You can make, for instance compound duple time into simple duple time, so 6/4 into 2/2. You can also turn simple triple meter into compound triple meter, so turn 3/2 into 9/4 for instance. You cannot convert triple time into dubbel time

Choice of 3/2 or 6/4 time signature


Fire javascript on a form submit

Question: Even the searching I have done that looks like there may be a solution doesn't really seem to answer this.
I have a form with an input value.  When the user enters a value and clicks submit, I want to call a javascript routine and make that value available to it.
It seems simple enough, but I can't really find a good answer.
Answer: You need some jQuery on the page, e.g:
Drupal.behaviors.form_submit_processor = {
  attach: function (context, settings) {
    $("form#my-form").submit(function(e) {
      alert('form submitted');
      alert($('form#my-form #edit-name').val());
    });
  }
}

You could add to your theme script.js, with drupal_add_js or form_alter and $form['#attached'] ( recommended )
Comment: My form keeps redirecting to another URL.  I changed the $form['#action'] value to url("#").  I'm not sure how to prevent Drupal from handling the submit and just let the JS handler deal with it.
Comment: When I event.preventDefault() after my event handler, it seems to work.
Answer: Alternatively you can do this from Form API where you have access to the form directly. This enables complex behaviours and form alterations on AJAX calls.
Take a look at the Ajax framework commands. You'll need to enable AJAX in your form too. Sometimes this is as simple as adding the no-js path argument in hook_menu or adding the use-ajax class on links. Read up on the AJAX framework  in Drupal and ajaxifying forms.
After the hook_form_submit you can then return an array of commands to run including the roll-your-own ajax_command_invoke.
Answer: Here's how I did it:
Drupal.behaviors.form_submit_processor = {
  attach: function (context, settings) {

    // Function to be run before form submission
    var preFormSubmit = function () {
      // do some stuff here...
    }

    // Add a js function to run before form submission
    var formE = $('#my-form-id');
    formE
      .on('submit', function (e) {
        e.preventDefault();
        $.when(preFormSubmit()).done(function () {
          formE
            .off('submit')
            .submit();
        });
      });
    }
  };
})(jQuery);

Using $.when(preFormSubmit()).done allows preFormSubmit() to finish before the form is submitted.

Fire javascript on a form submit


Taylor expansion for random variables

Question: Let $X_n$ and $Y_n$ be random variables such that $X_n-Y_n\overset{p}{\longrightarrow}0$ as $n\rightarrow\infty$. Let $f(.)$ be a differentiable function. Is the following correct?
$$f(X_n) = f(Y_n) + f'(Y_n)(X_n-Y_n) + o_p(X_n-Y_n)$$ as $n\rightarrow\infty.$
Answer: To gain some intuition about the issues, let's consider a sequence of bivariate random variables $(X_n,Y_n)$ that have simple distributions and a function $f$ that is easy to calculate with.  We want to give your supposition a hard time in the sense of contemplating functions $f$ for which the Taylor approximation $f(z+a) \approx f(z) + af^\prime(z)$ is particularly poor.  If it can withstand such examination then we will proceed to developing a proof; otherwise, we will have constructed a counterexample.
There are many ways to perform such an investigation.  For instance, we could examine functions $f$ that, although differentiable, are not continuously differentiable.  But perhaps the simplest is to examine functions whose derivative can become arbitrarily large, and then let the sequence $(X_n,Y_n)$ approach points where the derivative "blows up."
Consider, then, the function
$$f:(0,\infty)\to \mathbb{R};\ f(x) = \frac{1}{x},$$
chosen to be easy to compute with but to have a derivative
$$f^\prime(x) = -\frac{1}{x^2}$$
that diverges as $x\to 0.$
Let $(X_n,Y_n)$ be a sequence of discrete random variables converging towards each other and towards $0;$ specifically, suppose
$$\eqalign{
\Pr\left((X_n,Y_n) = \left(\frac{2}{n}, \frac{1}{n}\right)\right) &=  \frac{1}{2}\\
\Pr\left((X_n,Y_n) = \left(\frac{3}{n}, \frac{2}{n}\right)\right) &=  \frac{1}{2}.
}$$
Equivalently, $nY_n-1$ has a Bernoulli$(1/2)$ distribution and $X_n = Y_n + 1/n.$  Their difference converges to zero in any sense you care to use: In particular, since $X_n-Y_n=1/n\to 0$ everywhere, $X_n-Y_n \overset{p}{\longrightarrow} 0.$
Let's compute  the difference
$f(X_n) - \left[ f(Y_n) + f^\prime(Y_n)(X_n-Y_n) \right].$  This is a quantity you hope will be growing smaller in some sense: you want to be able to assert it is "$o_p(X_n-Y_n).$"
There are two possible values, each with probability $1/2.$  I will show the computations with a table, one row for each possibility:
$$\begin{array}{cc|cccc}
X_n & Y_n & f(X_n) & f(Y_n) & f^\prime(Y_n) & f(X_n) - \left[ f(Y_n) + f^\prime(Y_n)(X_n-Y_n) \right] \\
\hline
\frac{2}{n}  & \frac{1}{n} & \frac{n}{2} & n & -n^2  & \frac{n}{2} - [n - n^2\frac{1}{n}] = \frac{n}{2} \\
\frac{3}{n}  & \frac{2}{n} & \frac{n}{3} & \frac{n}{2} & -\frac{n^2}{4} & \frac{n}{3} - [\frac{n}{2} - \frac{n^2}{4}\frac{1}{n}] = \frac{n}{12}
\end{array}$$
Because the values $n/2$ and $n/12$ diverge everywhere, there is no possible definition of "$o_p$" that could make the statement true.

The insight provided by this simple example, and variations on it (in which $X_n$ and $Y_n$ may be independent or $f$ may be defined everywhere, for instance) is that for the hoped-for result to be true, you cannot allow $X_n$ and $Y_n$ to have any appreciable probability of attaining values where the Taylor approximation becomes arbitrarily poor.

Taylor expansion for random variables


Calendário dinâmico de meses JavaScript

Question: sou iniciante em Javascript.
Preciso fazer um calendário que mostra apenas os meses.
Por exemplo:
Estamos em Setembro.
O calendário vai mostrar de Setembro(2016) a Agosto(2017).
Com o código abaixo, eu consigo imprimir os meses de Janeiro a Dezembro.
Mas preciso que ele mostre do mês atual até 12 meses à frente.
Podem me ajudar?

            window.onload = function calendar() {
                var a = new Date();
                var b = a.getMonth();
                var months = [
                    "Janeiro",
                    "Fevereiro",
                    "Março",
                    "Abril",
                    "Maio",
                    "Junho",
                    "Julho",
                    "Agosto",
                    "Setembro",
                    "Outubro",
                    "Novembro",
                    "Dezembro"
                ];
                var i = months[i];
                for (i = 0; i <= 11; i++) {
                    document.getElementsByClassName("month-time")[i].innerHTML = months[i];
                }
            }
Comment: Só ví agora essas duas variáveis desnecessárias no começo da função.
Answer: Podes fazer assim:

var a = new Date();
var b = a.getMonth();
var months = [
    "Janeiro",
    "Fevereiro",
    "Março",
    "Abril",
    "Maio",
    "Junho",
    "Julho",
    "Agosto",
    "Setembro",
    "Outubro",
    "Novembro",
    "Dezembro"
];
window.onload = function calendar() {
    var meses = [];
    for (i = b; i <= b + 11; i++) {
        var mes = i > 11 ? months[i - 12] : months[i];
        meses.push(mes);
    }
    [].forEach.call(document.getElementsByClassName("month-time"), function(el, i) {
        el.innerHTML = meses[i];
    })
}
.month-time:first-of-type {color: blue;}

Dessa maneira crias a array num loop e depois chamas todos os elementos de uma só vêz e iteras preenchendo-os com o mês correto
Comment: Funcionou direitinho! Muito obrigado!

Calendário dinâmico de meses JavaScript


How to find the series $\sum_{n=0}^{\infty} \frac{(-1)^n x^{4n}}{(4n!)}$

Question: It is known that, $$\sum_{n=0}^{\infty} \frac{(-1)^n x^{2n}}{(2n)!}=\cos(x)$$ and $$\sum_{n=0}^{\infty} \frac{x^{2n}}{(2n)!}=\cosh(x)$$
From this follows that $$\sum_{n=0}^{\infty} \frac{x^{4n}}{(4n)!}=\frac{\cos(x)+\cosh(x)}{2}$$
How to find $$\sum_{n=0}^{\infty} \frac{(-1)^n x^{4n}}{(4n)!}$$
Comment: Replace $x$ by $\exp(\pi i/4)x$.
Comment: @AnginaSeng thank you for fixing my typos!
Comment: Factorial and paranthesis are in wrong places.
Answer: To expand a little on @Angina Seng's point, essentially the thing to notice is that if we can find the fourth root of ${-1}$, and replace $x$ with $x$ multiplied by this fourth root you get
$${\frac{((-1)^{\frac{1}{4}}x)^{4n}}{(4n)!}=\frac{((-1)^{\frac{1}{4}})^{4n}x^{4n}}{(4n)!}=\frac{(-1)^nx^{4n}}{(4n)!}}$$
There are actually four different fourth roots of ${-1}$:
$${e^{\frac{i\pi}{4}},e^{\frac{-i\pi}{4}},e^{\frac{3i\pi}{4}},e^{\frac{-3i\pi}{4}}}$$
So any one of these will suffice. If we take the principal root (${e^{\frac{i\pi}{4}}}$) though, this would make your answer
$${\sum_{n=0}^{\infty}(-1)^n\frac{x^{4n}}{(4n)!}=\frac{\cos\left(e^{\frac{i\pi}{4}}x\right)+\cosh\left(e^{\frac{i\pi}{4}}x\right)}{2}}$$
Just as others have said. But we don't have to pick that root,
$${\sum_{n=0}^{\infty}(-1)^n\frac{x^{4n}}{(4n)!}=\frac{\cos\left(e^{\frac{3i\pi}{4}}x\right)+\cosh\left(e^{\frac{3i\pi}{4}}x\right)}{2}}$$
is also just as valid
Edit: I won't write the full working (I will leave it as an exercise to you) - but we can actually further then simplify the result to
$${\sum_{n=0}^{\infty}(-1)^n\frac{x^{4n}}{(4n)!}=\cos\left(\frac{x}{\sqrt{2}}\right)\cosh\left(\frac{x}{\sqrt{2}}\right)}$$
Comment: It's easy to check that $y=\cos(x/\sqrt2)\cosh(x/\sqrt2)$ satisfies the DE $y^{(4)}=-y$ and that it has the right initial conditions.
Comment: This was useful in my case
$$
\cos(a+ib)=\cos a\cosh b-i\sin a\sinh b
$$
$$
\cosh(a+ib)=\cos b\cosh a+i\sin b\sinh a.
$$
Comment: @AnginaSeng indeed!
Comment: @MikaelHelin and yeah this was how I simplified it :D
Answer: For $0\le j\le 3$ define $S_j(z):=\sum_{n\ge0}\frac{z^{4n+j}}{(4n+j)!}$ so, for $0\le k\le3$,$$\sum_ji^{jk}S_j=\sum_{jn}\frac{(zi^k)^{4n+j}}{(4n+j)!}=e^{i^kz}.$$In other words,$$\begin{align}S_0+S_1+S_2+S_3&=e^z,\\S_0+iS_1-S_2-iS_3&=e^{iz},\\S_0-S_1+S_2-S_3&=e^{-z},\\S_0-iS_1-S_2+iS_3&=e^{-iz}.\end{align}$$Solving simultaneous equations gives each $S_j(z)$; you want $S_0(e^{\pi i/4}x)$. In particular $S_0+S_2=\cosh z,\,S_0-S_2=i\sin z$ so $S_0=\tfrac12(\cosh z+i\sin z)$, making your series $\tfrac12(\cosh\tfrac{1+i}{\sqrt{2}}x+i\sin\tfrac{1+i}{\sqrt{2}}x)$, which you're welcome to rewrite as you wish.
Answer: Use $(-1)^{\frac{1}{4}}$ to be able to use the series, so you get
$$\frac{\cos (\frac{(1+i)x}{\sqrt 2})+\cosh (\frac{(1+i)x}{\sqrt 2})}{2}=\sum_{n=0}^\infty\frac{(-1)^nx^{4n}}{(4n)!}
$$
Then use
$$
\cos(a+ib)=\cos a\cosh b-i\sin a\sinh b
$$
and
$$
\cosh(a+ib)=\cos b\cosh a+i\sin b\sinh a.
$$
In our case $a=b$ so $\cos(a+ia)+\cosh(a+ib)=2\cos a\cosh a$. Set $a=\frac{x}{\sqrt 2}$ and we get the solution
$$
\sum_{n=0}^\infty\frac{(-1)^nx^{4n}}{(4n)!}=\cos \frac{x}{\sqrt 2}\cosh \frac{x}{\sqrt 2}.
$$


Gravity forms jQuery variable to PHP variable populate dynamically

Question: I would like to pass a jQuery variable to php variable, in purpose to make a database selection. Im using gravity forms for the process, the jQuery code get the data from the drop down(2) and add it to another field(5), but i need the selected data from the dropdown to use in database selection:

SELECT Title FROM table WHERE Status=$variable

and the selected value to add to the field 5 in gravity forms.

    add_filter("gform_pre_render_1", "monitor_dropdown");
    function monitor_dropdown($form){

        ?>

        <?php
        return $form;
        }

hold.php
    add_filter( 'gform_field_value_url_data', 'populate_date' );
    function populate_date( $value) {
    $value2 = $_POST['data'];
    return $value2 ;
       }
// OR
       $value3 = $_POST['data'];
       return $value3;

Even after adding the ajax im not still what i need, is the ajax right? Or where im wrong ?
Comment: You need to use `$.ajax`
Comment: I agree with @Hackerman, you'd need to use some ajax in your code snippet and post your input change value to an external PHP file that would do something with the data you send to it. In that file you could include your database query and return its results to do something with if you needed to.
Comment: @Hackerman i added ajax but still no success !!!
Answer: You can handle the Form submission in the $POST macro variable.
Your Form must look like this :
<form action="link_to_your_php" method="post">
    <input id="input_1_5" name="input_1_5" />
    <input type="submit" value="Find" />
</form>

Then you can handle the variable like this.
<?php
    $variable = $POST['input_1_5'];
?>

And then make your query
SELECT Title FROM table WHERE Status=$variable

Comment: I need to pass the variable before the submission not after. And for the fom im using gravity form
Comment: Please don't dump variables in queries like it's okay, because [it's not](http://bobby-tables.com/).


Problem about Inverse Function Theorem

Question: In my lecture notes about Inverse Function Theorem it said

There is no need to have an Inverse Function Theorem for functions $F
: \mathbb R^n → \mathbb R^m$. If we only require $F$ and $F^{-1}$ to be continuous (not necessarily differentiable), then we can still conclude m = n."

Does it mean that for $F: \mathbb R^n → \mathbb R^m$ which has an inverse function $F^{-1}:\mathbb R^m → \mathbb R^n$, says $F$ is differentiable at $a\in \mathbb R^n$ and $F^{-1}$ is differentiable at $b=F(a)\in \mathbb R^m$,then $m$ must be equal to $n$? Why is it true?
Answer: The Inverse Function Theorem requires a continuously differentiable function.
Your assumption is true. The Invariance of Domain Theorem says that $F$ cannot be bijective and continuous if $m\neq n$.

Problem about Inverse Function Theorem


The proof differentiability of multilinear function using "product" of function.

Question: In Kolk's Multidimensional Real Analysis I: Differentiation
He used the following Corollary 2.4.3

to prove that a multilinear(k-linear) map $T \in Lin^k(\mathbf{R}^n,\mathbf{R})$ is differentiable.(In the proof of proposition 2.7.6)
The whole argument is a single sentence:

The differentiability of T follows from the fact that $T(a_1,\cdots, a_k) \in \mathbf{R}$ are polynomials in the coordinates of vectors $a_1,\cdots, a_k \in \mathbf{R}^n$. See corollary 2.4.3.

I know the fact that $T(a_1,\cdots, a_k) \in \mathbf{R}$ are polynomials in the coordinates of vectors $a_1,\cdots, a_k \in \mathbf{R}^n$. It's a basic property of multilinear map. But how does the conclusion relate to corollary 2.4.3?
Note that he defines the product $\langle f_1, f_2 \rangle$ as the composition:
$
\begin{equation}
\langle f_1, f_2 \rangle: x \mapsto (f_1(x),f_2(x)) \mapsto \langle f_1(x), f_2(x) \rangle : \mathbf{R}^n \rightarrow \mathbf{R}^p \times \mathbf{R}^p \rightarrow \mathbf{R}
\end{equation}
$
Answer: If we write
$$a_{i}=\sum_{\ell=1}^{n}b_{i,\ell}e_{\ell},$$
then
$$T(a_{1},\ldots,a_{k})=T \left( \sum_{j_{1}=1}^{n}b_{1,j_{1}}e_{j_{1}},\ldots \sum_{j_{k}=1}^{n} b_{k,j_{k}}e_{j_{k}}\right)=\sum_{j_{1}=1}^{n}\cdots \sum_{j_{k}=1}^{n}T(e_{j_{1}},\ldots,e_{j_{k}})b_{1,j_{1}}\cdots b_{k,j_{k}}.$$
By part (i) of Corillary 2.4.3, its is enough to show that $S(a_{1},\ldots,a_{k})=b_{1,j_{1}}\cdots b_{k,j_{k}}$ is differentiable. You can think $S$ as the product of the maps of the form
\begin{align*}
    S_{1,j_{1}}:\mathbb{R}^{n} \times \cdots \times \mathbb{R}^{n} & \to \mathbb{R} \\
    (a_{1},\ldots,a_{k}) & \mapsto b_{1,j_{1}}.
\end{align*}
Thus, $S$ is differentiable using (ii) $k$-times.
Comment: Because $S_{1,j_{1}} \in \mathrm{Lin}(\mathbb{R}^{nk},\mathbb{R})$ and linear maps are differentiable with $DS_{1,j_{1}}(a)=S_{1,j_{1}}$, where $a \in \mathbb{R}^{nk}=\mathbb{R}^{n} \times \cdots \times \mathbb{R}^{n}$.
Comment: One question: how do you know $S_{1,j_{1}}$ itself is differentiable?


Show that for $f$ analytic in $B(0,2)$, $\max_{|z|=1}|\frac{1}{z}-f(z)|\ge 1$?

Question: Let $f:B(0,2)\to \Bbb C$ be an analytic function. Show that $$\max_{|z|=1}\left|\frac{1}{z}-f(z)\right|\ge 1.$$
I tried to write $f(z)$ as power series since it is analytic, it doesn't seem work. I also tried to use maximum modulus principle, it also did not work.
Could anyone kindly help? I am really struggling with this problem. Thank you!
Comment: Possible duplicate of http://math.stackexchange.com/questions/1862998/a-question-about-maximum-principle-in-complex-analysis
Answer: Hint: Try integrating $1/z-f(z)$ around the unit circle.
Comment: I get $2\pi i-\int_{\gamma}f(z)dz=2\pi i -i\int_0^{2\pi}e^{it}f(e^{it})dt$, I am really confused what to do next. Could you help give some hint about what to do next? Thanks!
Comment: Well, $f(z)$ is analytic on the entire unit disk.  What does that tell you about $\int_\gamma f(z)dz$?


Set Bool in custom property from view controller

Question: Allocating a custom class in a vc. Then I set a bool value (either set or . notation).
The value never gets to the custom class - always reports NO.
Googled and tried many different variations - none work. What else could be wrong with the code below?
CustomView.h
    @interface CustomView : UIScrollView <UIScrollViewDelegate> {
    BOOL myLocalProperty;
}

@property (assign) BOOL myProperty;

CustomView.m
     @implementation CustomView

    @synthesize myProperty =_myProperty;

    - (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];

    myLocalProperty = _myProperty;

    if (myLocalProperty==YES) {
        NSLog(@"YES");
    } else if (myLocalProperty==NO) {
        NSLog(@"NO");
    }

    return self;
}

ViewController.m
(in some method that is def. being called)
CustomView *myView = [[CustomView alloc] initWithFrame:CGRectZero];

    myView.myProperty=YES;

This value of YES never gets to the property. Anything obviously wrong here?
Answer: The value of YES does get there, but that happens after you have printed the default NO.
The current value of _myProperty is printed in the initializer; by the time you assign the property YES, the initializer is done!
You can check that the value does get there by adding a method to show the current value of the property:
- (id)showMyProperty {
    myLocalProperty = _myProperty;
    if (myLocalProperty==YES) {
        NSLog(@"YES");
    } else if (myLocalProperty==NO) {
        NSLog(@"NO");
    }
}

Now change your code that creates CustomView as follows:
CustomView *myView = [[CustomView alloc] initWithFrame:CGRectZero];
myView.myProperty=YES;
[myView showMyProperty]; // This should produce a "YES" in NSLog

Answer: You're logging the value of myProperty in CustomView's initWithFrame: method, but you're not assigning YES to myProperty until initWithFrame: has returned.  You should try logging NSLog("myView.myProperty = %@", myView.myProperty ? @"YES" : @"NO"); after your assignment, myView.myProperty = YES;.


Telegram bot api - getUpdates does not igonre deleted messages

Question: I'm working on Telegram Bot API and I want to implement some features in my application. At this time, I need to get last NON deleted channel message via a bot. For this purpose, I have created a bot and set it as an administrator of that channel, and call getUpdates method of official api. For calling this method, I have provided bot token, and set offset: -1 and limit: 1. This returns me the last message. But my problem is even if I delete last message, api still returns deleted message. How can I solve this problem?
Comment: I am running into the same issue, curious if you were able to figure out a way?
Comment: @user1596115 No, I don't know why, but telegram policy is not ignoring deleted messages! I found telegram official bot support, you can ask this question from him. Telegram username: @ BotSupport
Comment: thanks man, appreciate the reply!
Answer: This might be a little late, but: I think this is how it should be. The telegram getUpdates is only for checking if there are new updates. Message deletion doesn´t count as an update that´s why you get the deleted update. Sadly there is no attribute to check if the message is already deleted...
Maybe you could think of using a webhook as alternative or somethink like that?


Can a 3 note triad be half diminished?

Question:

This is from the book "tonal harmony",
the 14th chord is vii half diminished 7; consisting of the notes D# F# A C#, with A in the bass, therefore it is vii half diminished 4 3, second inversion, which makes sense to me
but the 16th chord is what's confusing me, it has notes F# A D#, without a C#, the textbook answer says it's vii half diminished 6, first inversion, but can a triad be half diminished? I thought only seventh chords could be HALF diminished, the 6 clearly states that it's a TRIAD in first inversion, and the slashed circle states that it is half diminished,
so can a TRIAD be half diminished?
(UPDATE)
It seems there are multiple errors/typos in this book, I have spotted even more typos after further reading
Comment: It might be a reminder that a four-note chord built on the 7th step of a major scale is half diminished. But a triad indeed can't be half diminished. I wonder what the "vii°" in the last bar of example 3 refers to? Are they at least consistent within the book?
Comment: They are consistent for the most part
Answer: Your analysis is correct, and this seems to be an error in the book, in which chord 16 in the answer key should include an open circle rather than the slashed circle.
A half-diminished chord is, by definition, a seventh chord -- thus requiring a (minor) seventh, which chord 16 lacks.
Note that the excerpt itself is a correct reduction of the original. Here is the passage in question from the Bärenreiter Urtext.
Answer: A triad can be diminished - with a m3 and a d5. A fully diminished chord will be that triad plus a dim 7,the same sounding note as M6. In key C - C, E♭, G♭ B♭♭.The last sounding like A.
The 'half-diminished' part of a chord comes when a m7 is added, instead of that d7. That's why it's only 'half-diminished' as opposed to 'diminished', or 'fully-diminished'.
So it would appear that there's a typo - or it's just incorrect.
Sometimes, it's easier to understand when it's called m7♭5, as that portrays all the relevant details.
Comment: In precise terminology it's a fully diminished *seventh* chord, so called because both the seventh and fifth are diminished.  In other words, the distinction between B-D-F and B-D-F-A♭ is the word "seventh," not the presence or absence of any modifiers on the word "diminished."  This is of course complicated by the fact that in imprecise terminology people often use "diminished" as shorthand for "diminished seventh."
Comment: But half diminished chord is not a variant of minor seventh, which the notation m7b5 erroneously suggests.
Comment: @Divide1918 - it's a variant. A dim is A C Eb Gb. A half dim is A C Eb G. Am7 is A C E G. All varying by one note moved a semitone. Unless you use 'variant' as a sustitute for 'inversion'. But - to whom was the comment directed?
Comment: @Tim But they're all different types of chords. It's like saying Cmaj11(#11)  and C9(#11) are variants of each other. How could a major chord be a variant of a dominant 11th? Also by your logic, almost all chords of high enough extension (like 11, 13) are more or less variants of each other.
Answer: The triads (there are only triads of 3 tones)  are built by 2  minor thirds in root position. (m3dim5)
You are right, a triad ti-re-fa (here D#-F#-A) is diminished, in respect to the diminished 5th.
Half diminished is the VII7-5 tetrad: ti-re-fa-la (or iim7b5 in minor - like Tim says)
A diminished tetrad is  built by  3 minor thirds e.g. ti-re-fa-lu or si-ti-re-fa: the vii dim7 chords of the major and minor keys.
Answer: The question is, "Can a three note triad be half diminished." Starting with a major triad, you can flat the fifth and leave the third major...C(b5), etc. But it's not called a half diminished. It's a "major, flat 5". The term "half diminished" is reserved for seventh chords.

Can a 3 note triad be half diminished?


Ionic Angular Firestore not displaying single document data in view

Question: I am trying to retrieve a single document in a collection and display it in a view, but it always results in a blank page.
I have a service and a component.
Here is my service:
getReview(reviewID) {
      console.log('review id sent to service: ' + reviewID);
      this.reviewDoc = this.af.doc(`reviews/${reviewID}`);
      return this.reviewDoc.valueChanges();
  }

Here is my component:
    ngOnInit() {
    const reviewID = this.route.snapshot.params.id;
    this.getReview(reviewID);
    }

    getReview(reviewID) {
    this.reviewDetailsService.getReview(reviewID).subscribe((data) => {
      this.review = data;
      console.log(this.review);
    });
    }

The console log shows this:
{imgURL: "http://someimage.jpg",caption: "This is my caption}
In my HTML view I am doing this:
    <ion-content class="ion-padding">

        {{rev.caption}}

    </ion-content>

This does not display anything on the page.
Am I missing something?
Answer: You cannot use ngFor over an object, ngFor used over a collection, change your view as

 {{review.caption}}

Comment: I get this error now: ERROR TypeError: Cannot read property 'caption' of undefined
Comment: With the help of your answer I was able to find out that I needed to also make my review property and array by declaring review like this `review: any = [];`


Test for subset of coefficients being zero

Question: Given a linear model
$$
y = \beta_0 + \beta_1x_1 + \beta_2x_2+\beta_3x_3 + \beta_4x_4
$$
we can perform an $F$-test for the null hypothesis
$$
H_0: \beta_1 = \beta_2 = \beta_3 = \beta_4 = 0
$$
However, what test is appropriate for a subset of these coefficients being zero in the same model?
$$
H_0': \beta_1 = \beta_4 = 0
$$
Answer: You can use still an F-test. The test statistic is:
$$F_0 = \dfrac{SS_R/2}{MS_E},$$
where $SS_R$ is the increase in the residual sum of squares of the reduced model (setting $\beta_1=\beta_4=0)$ with respect to the full model with all the parameters. $MS_E$ is the residual sum of squares of the full model divided by $n-5$, where $n$ is the number of observations.
Under $H_0$, $F_0$ is distributed as a $F_0$ of Fisher-Snedecor with $d_1=2$ (i.e. number of restrictions) and $d_2=n-5$.
Remark: clearly the result is valid under the usual assumptions of the Linear regression (e.g. Gaussian residuals).
See here the details of what they call partial F Test.
Comment: Perhaps you could expand your post a bit to summarize the main ideas. It's common practice on this site when linking to an external source. This makes the answer self-contained, and preserves it for the benefit of future readers in case the link ever goes dead.
Comment: @user20160, you are right! I edited as suggested.


Error guzzlehttp/guzzle ^6.3 -> no matching package found when update from 8.7.9 to 8.8.1

Question: When i tried to update my project using composer from 8.7.9 to 8.8.1 i get the following error:
Command:
composer update drupal/core --with-dependencies

[Composer\DependencyResolver\SolverProblemsException]
    Problem 1
        - Installation request for drupal/core 8.8.1 -> satisfiable by drupal/core[8.8.1].
        - drupal/core 8.8.1 requires guzzlehttp/guzzle ^6.3 -> no matching package found.
      Problem 2 .
        - drupal/core 8.8.1 requires guzzlehttp/guzzle ^6.3 -> no matching package found.
        - drupal/ultimate_cron 2.x-dev requires drupal/core ^8.5 -> satisfiable by drupal/core[8.8.1].
        - Installation request for drupal/ultimate_cron ^2.0 -> satisfiable by drupal/ultimate_cron[2.x-dev].
Potential causes:
     - A typo in the package name .
     - The package is not available in a stable-enough version according to your minimum-stability setting .
       see https://getcomposer.org/doc/04-schema.md#minimum-stability for more details.
     - It's a private package and you forgot to add a custom repository to find it

Any ideas ?
Comment: Run `composer clear-cache` and try again
Comment: I have tried, the same result!
Comment: Maybe try `composer update drupal/core guzzlehttp/guzzle --with-dependencies`
Comment: I have tried it too, the same error
Answer: I have just to remove the vendor Folder it works now:
For the complete steps see 8.5.6 Update not being recognized .


Javascript -Paste from clipboard to specific cell in Excel

Question: I have a JS function that copies an image from a div onto a clipboard (only in IE) and pastes it into Excel. I would like to know how I can paste the contents of the clipboard into a specific cell in Excel. Here is the JS function code snippet I have. I would like to know how I can paste the clipboard contents into a specific cell
<code>var imgObj = document.getElementById('exportimage');
imgObj.contentEditable = 'true';
var controlRange;
if (document.body.createControlRange)
{
    controlRange = document.body.createControlRange();
    controlRange.addElement(imgObj);
    controlRange.execCommand('Copy');
    var objExcel = new ActiveXObject ("Excel.Application");
    objExcel.visible = true;
    var objWorkbook = objExcel.Workbooks.Add;
    var objWorksheet = objWorkbook.Worksheets(1);
    objWorksheet.Paste;
 }
</code>
Copying to clipboard from div, and pasting it into Excel may not be a recommended approach but I would like to get this working for an internal (use only) application
Comment: Does this code currently paste the image into the first cell in the sheet? If so you probably have to select the cell you want to paste into and then invoke .Paste. I'm just guessing - I don't have IE or excel.
Comment: maybe: `objWorksheet.range('R2')` or `objWorksheet.cells('D2')` ?
Comment: Yes. This code does paste the image into the first cell in the sheet. I am able to assign a value by doing objWorksheet.range('R2').value='abc'; but I don't know how to paste into a specific cell.
Comment: You say the code pastes the image into the first cell but you don't know how to paste into a specific cell. Do you mean it pastes to that location? Are you sure it is IN the cell or located AT the cell?
Comment: You are right datatoo. The code pastes the image AT the cell and not IN the cell
Answer: The best you will achieve is pasting to the location where the cell is. You can't insert into the cell. There are other things you may want to do such as insert the image into a comment, or paste an image link, but actually placing the image in the cell isn't going to work.
The closest you can get is to define the Range("A1").Select  (or whatever location) and paste to that beginning point. You can also fine tune the location however, so depending on what you are trying to do you can offset from a cell range by specific amounts, if that is what you need.


how can i calculate the age using the input (String) of the month,day and year?

Question: <code>        string Month, Year, Day;
        Console.Write("\nInsert birth month: ");
        Month = Console.ReadLine();

        if (Month.Equals("null"))
        {
            Console.Write("Insert birth day ");
            Console.Write("\nInsert birth year \n");

            Console.WriteLine("BIRTH MONTH:");
            Console.WriteLine("BIRTH DAY:");
            Console.WriteLine("BIRTH Year:");
            Console.WriteLine("BIRTHDAY:");

            Console.ReadKey();
        }
        else
        {
            Console.Write("Insert birth day: ");
            Day = Console.ReadLine();
            Console.Write("Insert birth year: ");
            Year = Console.ReadLine();

            Console.WriteLine("BIRTH MONTH: {0}", Month);
            Console.WriteLine("BIRTH DAY: {0}", Day);
            Console.WriteLine("BIRTH YEAR: {0}", Year);
            Console.WriteLine("BIRTHDAY:{0}/{1}/{2}", Month, Day, Year);
           Console.WriteLine("Age: {0}", DateTime.Now.Year - Convert.ToInt32(Year));
           Console.ReadKey();

           the only  variable that i can calculate is the year but when it comes to the month
           and day it does not show correctly.

            The program runs like this:
            Insert birth month: 04
            Insert birth day:14
            Insert birth year:2000

            BIRTH MONTH:04
            BIRTH DAY:14
            BIRTH Year:2000
            BIRTHDAY:04/14/2000
            AGE: 22

The program runs like that because it does not considered the day and month to execute.

    The program should run like this:

            Insert birth month: 04
            Insert birth day:14
            Insert birth year:2000

            BIRTH MONTH:04
            BIRTH DAY:14
            BIRTH Year:2000
            BIRTHDAY:04/14/2000
            AGE: 21
</code>
As you can see the age is 21 because the month and day which is April 14 is being considered. any there who can help me out?
I used integer first but the "null" word is not working that's why i used string instead to work this out.
The program should run like this if i insert null work:
Insert birth month:null
Insert birth day
Insert birth year
BIRTH MONTH:
BIRTH DAY:
BIRTH Year:
BIRTHDAY:
AGE:
here's my concern how can i calculate age considering the Three main variable which is Month,Day and Year.
Thanks in advance
Comment: You can construct a `DateTime birthday` from the month, day and year input. Then calculate the difference `DateTime.Now - birthday`
Answer:
Calculating age accurately needs lot of condition to check, because of leap year considerations Refer more on here : How do I calculate someone's age based on a DateTime type birthday?
<code>using System;

namespace ConsoleApp2
{
internal class Program
{
      static void Main(string[] args)
        {

            string FirstName, LastName = " ";
            char MiddleInitial = ' ';

            Console.Write("Insert  first name: ");
            FirstName = Console.ReadLine();

            if (FirstName.Equals("null"))
            {
                Console.Write("Insert middle initial ");
                Console.Write("\nInsert last name \n");

            }
            else
            {
                Console.Write("Insert middle initial: ");
                MiddleInitial = Console.ReadLine()[0];
                Console.Write("Insert  last name: ");
                LastName = Console.ReadLine();
            }
            string Month = "", Year = "", Day = "";
            Console.Write("\nInsert birth month: ");
            Month = Console.ReadLine();

            if (Month.Equals("null"))
            {
                Console.Write("Insert birth day ");
                Console.Write("\nInsert birth year \n");

                Console.WriteLine("\nYour record");
                Console.WriteLine("FIRST NAME:{0}", FirstName == "null" ? "" : FirstName);
                Console.WriteLine("MIDDLE INITIAL: {0}", MiddleInitial);
                Console.WriteLine("LASTNAME: {0}", LastName);
                Console.WriteLine("BIRTH MONTH:");
                Console.WriteLine("BIRTH DAY:");
                Console.WriteLine("BIRTH Year:");
                Console.WriteLine("BIRTHDAY:");

                Console.ReadKey();
            }
            else
            {
                Console.Write("Insert birth day: ");
                Day = Console.ReadLine();
                Console.Write("Insert birth year: ");
                Year = Console.ReadLine();

                var DOB = string.Format($"{Day}/{Month }  / {Year}");

                var currentdate = DateTime.Now;
                var age = Age(DateTime.Parse(DOB), currentdate);

                Console.WriteLine("\nYour record");
                Console.WriteLine("FIRST NAME:{0}", FirstName == "null" ? "" : FirstName);
                Console.WriteLine("MIDDLE INITIAL: {0}", MiddleInitial);
                Console.WriteLine("LASTNAME: {0}", LastName);
                Console.WriteLine("BIRTH MONTH: {0}", Month);
                Console.WriteLine("BIRTH DAY: {0}", Day);
                Console.WriteLine("BIRTH YEAR: {0}", DateTime.Now.Year - Convert.ToInt32(Year));
                Console.WriteLine("BIRTHDAY:{0}/{1}/{2}", Month, Day, Year);
                Console.WriteLine("Age: {0} ", age);
            }
        }

        public static int Age(DateTime birthDate, DateTime laterDate)
        {
            int age;
            age = laterDate.Year - birthDate.Year;

            if (age > 0)
            {
                age -= Convert.ToInt32(laterDate.Date < birthDate.Date.AddYears(age));
            }
            else
            {
                age = 0;
            }

            return age;
        }

    }

}
</code>
Comment: There is an error in this line
Comment: var age = Age(DateTime.Parse(DOB), currentdate);
Comment: The World "Age" says does not exist
Comment: I dont get any error. Please check the brackets also pasted the whole code.
Comment: have you tried your code?
Comment: is there any issues ur facing
Comment: It says Exeception Unhandle, String.FormatException: 'string was not recognized as a valid'
Comment: that's the only problem with your code when i try to run it
Comment: what is the input u have provided for day, year, month
Comment: the error appears when i inserted  value in : "Insert birth year:  "maybe because the value should be in integer data type that's why it recognized as string which is not a valid to continue.


Regular link to URL in Foundation tabs

Question: I am using Foundation 5.2.1 and I want to use vertical tabs for navigation.

uk

ru

en

What is unusual here is that I use not links to sections like href="#section1" but links to external URL. When I click on any tab it becomes highlighted as active but no redirection to the specified URL happens.
Is there a way to make the links to external pages work with tabs in Foundation, or should I use something different?
Answer: I've found the solution. Strange that this was not documented anywhere.
All one needs is to remove data-tab attribute from the
 element.
Then links will work as usually.
Comment: This won't work with Foundation 6. The externally linked tab will work but the others do not.
Answer: I've been looking to do something similar. If you need to link offsite or to another page of your app, You can use a onclick event on your dd element:

Google

Answer: @BartoNaz's solution is no longer working in Foundation 6 — it looks like
Zurb failed to separate presentation (I want something that looks like tabs) from function (I want to show and hide parts of a single page).
I don't like the verbosity of Bootstrap, but since it's more flexible, and doesn't get in the way of RESTful web design, I guess I'll have to go back to it.
Answer: The answer is the same for Foundation 6, remove the data-tabs property from the ul

Regular link to URL in Foundation tabs


Related Links for Content

Question: In the design for my article pages I have related links in a right hand side column.
In Drupal administration when you edit content I want to have a 'Related Links' section, which prints a list of the content currently on the site with checkboxes so a user can choose which pages should be displayed as related.
I'm new to Drupal development, however have experience in working with PHP/mySQL and writing modules for other content management systems.
What steps should I go about to achieve this? And how would I then print the selection on the front-end of the site?
Thanks so much for your time
Answer: With References or Entity References (recommended) module, you can add node reference fields to your node type.
It's pretty straight forwad. I'd suggest looking at drupal.org docs about making node types asyou are new to Drupal. You will not need to code anything in most cases. for content display, you can use theme templates and/or Views.

Related Links for Content


Forma certa de obter uma determinada div

Question: Estou tentando descobrir um meio de se acessar uma div via jquery para manipulá-la. Segue o código:

...

Como está mostrado no comentário acima, a div que eu quero acessar é a de raiz mais alta das mostradas aqui. Sei que essas divs ao redor são desnecessárias, mas as vezes alguns frameworks e cms as colocam, e aí me encontro numa situação dessas, tendo que acessar a div que desejo mexer, como está no comentário.
O que eu faço no jquery para acessar é o seguinte:
$("#conteudo").parent().parent().parent().css('padding','15px');

Como eu posso acessar essa div sem esse código todo? Muitas vezes não consigo tirar essas divs desnecessárias, então queria acessar as divs que desejo de uma maneira mais eficaz (imagina se fossem 10 divs ali, quantos parents eu teria que escrever...)
Comment: você consegue obter o pai da div que quer manipular?
Comment: sim, como mostrei através do parent eu faço isso, mas queria fazer isso de uma maneira melhor, pois se a div estiver envolvida por muitas outras divs, vou ter que usar vários parents
Comment: Vc não entendeu a pergunta, VC consegue saber qual eh o pai, ou que tipo de div existe acima da que você quer manipular?
Comment: ah sim. Olha em alguns casos sim, mas na maioria das vezes não consigo. Esse é um caso que não consigo.
Comment: o problema então é só evitar chamar `.parent()` várias vezes?
Comment: Sim, queria ver se tinha algo melhor a fazer no jquery.
Answer: Combine a função .parents() com o seletor :eq():
$("#conteudo").parents(':eq(2)')

Note que a indexação é em 0, então para acessar o 3º nível deve ser usado 2.
Comment: Exatamente isso! Não sabia que essa combinação poderia ser feita!
Answer: Coloca um identificador nela um ID ou uma classe e chama ela diretamente

...

Depois faça o $('#esse').css('padding','15px'); se não for possível mexer nesse div então o Sanção já demonstrou a outra forma.


DNA sequence classification

Question: I have a database of 3190 instances of DNA consisting of 60 sequential DNA nucleotide positions classified according to 3 types: EI, IE, Other.
I want to formulate a supervised classifier.
At the moment I apply the 60 nucleotides as features and in addition 64 features from a 2nd order Markov Transition Matrix.
The nucleotides A,C,G,T are encoded simply as 1,2,3,4
I'm running a Neural Net and achieving about 90% accuracy.
Next thing to try is a SVM.
My Question is:
1. Is there a better way to encode the feature data?
2. Is there a better way to approach the problem given that the sequential nature of the data is relevant.
Answer: I would also suggest looking at recurrent neural networks for their natural application to sequence data. Check out this tensorflow tutorial on machine translation for ideas about network specification: https://www.tensorflow.org/tutorials/seq2seq. Also this nice explanation on Long Shirt Term Memory (LSTM) RNNs: http://colah.github.io/posts/2015-08-Understanding-LSTMs/. I'm not sure there is a "better" way to encode the data, but there are definitely more compressed ways, such as packing multiple binary variables into a byte. There is also chas game representation, and the related universal sequence mapping (USM) which encodes lengths of sequences into pairs of 32 or 64 bit floats or ints (essential just bit packing on the quaternary code), both of which have been used recently for NNs on DNA sequences.
Answer: Interesting questin. Since extracting relevant features from DNA sequences could be non-trivial it could be a good idea to look  at convolutional neural networks where the network learns which features to extract.
Cool example:
http://www.nature.com/nbt/journal/v33/n8/full/nbt.3300.html
Answer: I assume all the instances have equal length. This is why you can try neural network or SVM.
As you mentioned, neural network and SVM is not explicitly considering the dependencies on the evens of the sequence.
For sequential model, Markov Chain or Hidden Markov model are widely used and can be used to model variable length sequences.

DNA sequence classification


Finding Bigrams in a list of worrds

Question: How would I go about finding a bigram in a list? For example, if I wanted to find the
bigram = list(nltk.bigrams("New York"))

In a list of words,
words = nltk.corpus.brown.words(fileids=["ca44"])

I have tried doing,
for t in bigram:
        if t in words:
             *do something*

As well as,
if bigram in words:
   *do something*

Answer: .bigrams() will return a generator of tuples. You should convert the tuples to strings first. For example:
bigram_strings = [''.join(t) for t in bigram]

then you can do
for t in bigram_strings:
    if t in words:
         *do something*

Comment: Sorry maybe my question isn't clear enough :S, What I am after is to be able to find occurrences of where there is ('new', 'york') together . What you have suggested although good prints 'newyork'
Comment: Then you are better with @L3viathan's answer, but I think you should use `for bigram in nltk.bigrams(["New", "York"]):` then.
Answer: You can write a generator that yields bigrams for your word list:
def pairwise(iterable):
    """Iterate over pairs of an iterable."""
    i = iter(iterable)
    j = iter(iterable)
    next(j)
    yield from zip(i, j)

(For example, list(pairwise(["this", "is", "a", "test"])) will return [('this', 'is'), ('is', 'a'), ('a', 'test')].)
And then zip over that and the result of .bigrams():
for pair in pairwise(words):
    for bigram in nltk.bigrams("New York"):
        if bigram == pair:
            pass  # found

Finding Bigrams in a list of worrds


How to call a method within a method from another method?

Question: In a javascript file I have this:
Work.expenses= function (params)
{
    function deleteExpenses()
    {
      //here I want to call the loadExpensesList method
    }
}

Work.expensesList= function (params)
{
    function loadExpensesList()
    {
     //this is the method I want to call
    }
}

How do I call the loadExpensesList method in the deleteExpenses method?
Thank you!
Comment: `loadExpensesList` isn't really a method; it's just an inner function that you have to make public if you want to call it from outside.
Comment: You can't unless you expose it to a higher scope.
Answer: Work.expenses= function (params)
{
    function deleteExpenses()
    {
      Work.expensesList('something')();
    }
}

Work.expensesList= function (params)
{
    function loadExpensesList()
    {

    }
    return loadExpensesList;
}

You can try like this. But can be better by understanding the requirement.


jquery code snippet small help needed

Question: i made this code with the help of friends. Now i was trying to add functionality as mentioned as under. But i was not able to get success.
here is the fiddle.
Fiddle:
http://jsfiddle.net/FLgsq/
jquery code:
$(document).ready(function () {
    $('#word_count').wordCount();
});

jQuery.fn.wordCount = function (params) {
    var p = {
        counterElement: "display_count"
    };
    var total_words;

    if (params) {
        jQuery.extend(p, params);
    }

    //for each keypress function on text areas
    this.keypress(function () {
        total_words = this.value.split(/[\s\.\?]+/).length;
        jQuery('#' + p.counterElement).html(total_words);
    });
};

$(document).ready(function () {
    $('input[name=rdOptin]').click(function () {
        var selected = $(this).val();
        var var0 = 0.3;
        var var1 = 20;
        var var2 = var1 * 3.9 / 100;
        var var3 = 20;
        var var4 = (var1 + var3) * 3.9 / 100;
        if (selected == 'norm')
            var total = var0 + var1 + var2;
        else
            var total = var0 + var1 + var3 + var4;
        $("#calc_value").html("Numbers " + total.toFixed(2) + "");
    });
});

what i was trying to achieve is, how can i do that if the number of words in the textfield (which is already counted by the function "jQuery.fn.wordCount") increase more than 13 the output of variable "total" change accordingly with the already existing functionailty (i.e. it is also monitoring radio "rdOptin" and doing calculation based on that). Rather it just adds +5 or it the numbers is between 13-18 it shall add 5 to the output of portion "Calculated Value:", then if 18-23 adds 10, then 24-28 adds 15 and so on or 6 iterations can be taken.
how can it be done guys?
Comment: See here http://stackoverflow.com/questions/7422192/jquery-count-words-in-real-time
Answer: $(document).ready(function () {
    $('input[name=rdOptin]').click(function () {
        var selected = $(this).val();
        var var0 = 0.3;
        var var1 = 20;
        var var2 = var1 * 3.9 / 100;
        var var3 = 20;
        var var4 = (var1 + var3) * 3.9 / 100;
        if (selected == 'norm')
            var total = var0 + var1 + var2;
        else
            var total = var0 + var1 + var3 + var4;
        var wordcount = parseInt($("#display_count").html(), 10);
        if (wordcount >= 13) {
            var inc = Math.ceil((wordcount-12)/5);
            total += inc;
        }
        $("#calc_value").html("Numbers " + total.toFixed(2) + "");
    });
});

FIDDLE

jquery code snippet small help needed


Understanding the Heine–Cantor theorem

Question: The "Heine–Cantor theorem" states: If $f : M → N$ is a continuous function between two metric spaces, and $M$ is compact, then $f$ is uniformly continuous.
I do not doubt its validity, of course, just trying to understand why it is valid.
If we, say, take the function: $y = x^4$.
It rises very quickly with the rising value of the argument. How is it that according to Heine–Cantor theorem just because we enclose the argument of the function, say, between $[0, 10]$ it automatically becomes "uniformly continuous" (considering of course that it is "continuous")?
There are areas of function values inside the argument segment where function will rise quicker than in some other areas.
Does the reason have to do with the fact that we could in worst case choose $\delta=10$ (length of the segment in example) and thus cover all possible cases for $\varepsilon$?
Comment: The rough idea is that, in the $\varepsilon-\delta$ language, for fixed $\varepsilon$ we have that $\delta$ is a continuous function of $x \in M$. So if $M$ is compact it admits a minimum by Weierstrass theorem, and this implies that continuity is in fact uniform continuity.
Comment: @Eval it is not independent of $\epsilon$. It's independent of $x$.
Comment: It means that this δ would be sufficient for **any**  $\epsilon$ you might choose for the definition of the uniform continuity to hold.
Answer: Compactness is a finiteness property. It says that given any infinite collection of data associated to open sets in a topological space, you can in fact deal with only finitely many.
The great thing about a finite number of objects, is that you can compare them. Unlike with infinite sets, which only have well-defined suprema and infima, finite sets have maxima and minima (infinite sets can have these, but often don't, such as with sets like $(0,1)$, which has no maxima or minima).
Uniform continuity is a statement that one particular $\delta$ works for every $x$. Compactness says finitely many $\delta$ suffice to talk about the $\delta$'s needed for the whole space. So the finiteness lets us pick the one we need for the whole space.
Comment: @Eval Applying the (metric) definition of continuity at each point for any fixed $\epsilon$ gives you an open cover of $[a,b]$, so that if you have two points in the same interval their images are within $\epsilon$ of each other. Compactness gives a finite subcover. The intervals in this finite subcover necessarily have some minimal positive length, which is your $\delta(\epsilon)$ (not depending on $x$ but still depending on $\epsilon$).
Comment: Is thus "_the one we need for the whole space_" in fact the one that represents the length of the segment where a continuous function is defined?
Comment: @Eval I'm not sure I understand this question. The $\delta$ that we pick is the minimum of the finitely many $\delta$'s that appear after applying compactness. Maybe said another way, you can think of $\delta$ as a function which depends on $x$. It tells you how close to $x$ you have to be to ensure continuity changes the function by at most $\epsilon$. Uniform continuity is the statement that we can choose $\delta$ to be small enough that it is independent of $x$.
Answer: you can also consider the following idea(take for simplicty $N = \mathbb{R})$: since $f$ is continouus and $M$ is compact, the function $f$ obtains its maximal value, which is some real number, inside $M$ (see also here).
In other words, you can control the values in $N$ taken by $f$ and in particular, $f:M \to \mathbb{R}$ is a bounded function (because $f$ is always less or equal than its maximum). That example makes it easier to understand why you can control $f$ on the entire compact set $M$, as you questioned.
Comment: I don't think this helps, as it says nothing of why for instance $f(x)=\sin(1/x)$ on $(0,1]$ is not uniformly continuous.

Understanding the Heine–Cantor theorem


Como obter resultados randômicos em SQL com diferentes SGDBs?

Question: Me baseando nesta pergunta existente no SOen e querendo trazer um conteúdo interessante e útil ao SOpt faço esta pergunta:
Como obter resultados randômicos em SQL com diferentes SGDBs?

Estou deixando uma resposta pronta, mas vou deixar aberto acaso sujam soluções melhores ou mais performáticas
Comment: Debate sobre a pergunta: https://pt.meta.stackoverflow.com/q/7007/3635
Comment: Gostaria muito de saber o motivo dos downvotes, [afinal até aonde entendo](http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/) responder as proprias perguntas é incentivado pelos idealizados do Stack Overflow. Grato a quem explicar as motivações.
Answer: Parte dos exemplos foram obtidos nesta resposta do SOen do @YaakovEllis

Já deixo avisado que isto não foi feito testes de performance, o que provavelmente pode ser um pouco complicado se necessitar consultar muitas coisas. Pretendo realizar testes próprios e sugerir talvez maneiras diferentes.
Outro detalhe, o uso de LIMIT, TOP 1, rownum, etc é somente para indicar que houve limitação de resultados, afinal a intenção é pegar resultados randômicos e não apenas ordenar de forma randômica

MySQL
Select randômico em MySQL:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1

PostgreSQL
Select randômico em PostgreSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

SQL Server
Select randômico em Microsoft SQL Server:
SELECT TOP 1 column FROM table
ORDER BY NEWID()

IBM DB2
Select randômico em IBM DB2
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

Oracle
Select randômico em Oracle:
SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1

SQLite
Select randômico em Sqlite:
SELECT column FROM table
ORDER BY RANDOM() LIMIT 1

Answer: No SQL Server, se não for precisar selecionar todas as linhas e sim apenas uma amostra das linhas e performance for importante, use o seguinte:
SELECT * FROM table
  WHERE (ABS(CAST(
  (BINARY_CHECKSUM(*) *
  RAND()) as int)) % 100) < 10

A ideia aqui é gerar um numero aleatório entre 0 e 99 e depois selecionar todos que são menores do que 10. Dessa forma selecionando ~10% da base.
Você pode trocar o 100 da query por outro valor se precisar pegar porções menores de 1% da base.
Usar ORDER BY newid() pode ser problemático por que ORDER BY faz com que todas as linhas da tabela sejam copiadas para o tempdb e isso é lento por que pode ser muito IO e se a base for muito grande, pode estourar o tempdb.


Fazendo o insert no SQL Server em um campo float?

Question: Estou com o seguinte problema no meu código, tenho um textbox que recebe o valor 0.900, só que quando estou gravando este valor no banco, esta gravando apenas 900, e preciso que grave o 0.900 e não estou conseguindo gravar desta forma, o campo na tabela do sql esta como float. Estou tentando fazer desta forma float.Parse(txt_qtda.Text) e não esta dando certo, só grava 900 e não 0.900.
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO CB0020 (CB0_FILIAL, CB0_CODETI, CB0_DTNASC, CB0_TIPO, CB0_CODPRO, CB0_QTDE, CB0_LOCAL, CB0_LOTE, CB0_DTVLD, CB0_FORNEC, CB0_LOJAFO, CB0_XLOTEF, CB0_XQTDKG, CB0_XORIGE, CB0_XDTFAB, CB0020.R_E_C_N_O_) VALUES ('01','" + txt_codbarras.Text + "', '" + txt_dtnasc.Text + "', '01', '" + txt_codprod.Text + "', '" + float.Parse(txt_qtda.Text) + "', '01', '" + txt_lotefrac.Text + "', '" + Convert.ToDateTime(txt_dtvalidfrac.Text).ToString("yyyy/MM/dd").Replace("/", "") + "', '" + txt_codfbaric.Text + "', '01', '" + txt_lotefabric.Text + "', '" + float.Parse(txt_qtda.Text) + "', '" + txt_codorig.Text + "', '" + Convert.ToDateTime(txt_dtfabricfrac.Text).ToString("yyyy/MM/dd").Replace("/", "") + "', '" + txt_recno.Text + "')";
cmd.Connection = conex;
conex.Open();
cmd.ExecuteNonQuery();

Comment: tem como vc colocar o trecho do codigo que insere no banco de dados?
Comment: coloquei acima o trecho do código.
Answer: Tem vários erros aí.
Isso parece dinheiro ou algo semelhante (quantidade) e float nunca deveria ser usado para isto. Isto é um problema seríssimo que causa prejuízos.
Se houver um digitação errada a aplicação vai quebrar. O problema na verdade deve estar na conversão ou na entrada do dado.
Se a conversão for correta é para tudo funcionar. Mas se ainda tiver algum motivo para mudar a escala basta dividir por 1000. Não que estou dizendo que é o caso, não vi o todo, mas já vi situação que a solução seria esta. Não use isto como gambiarra, só se for a solução correta. É uma solução útil quando realmente se digita o valor em escala diferente da desejada. Se for para consertar o erro anterior, não faça.
Você tem sérios problemas de segurança inserindo dados desta forma. Parametrize a query.
Estas conversões de data parecem estranhas também.
A nomenclatura das colunas e da tabela costuma ser ruim, mas isso tem um pouco de gosto, ainda que quase todo mundo concordaria que esses nomes são ilegíveis.
Coloquei no GitHub para referência futura.
Comment: Obrigado pela atenção, esta tabela e uma tabela de banco de dados da Totvs, todos os campos são criados como varchar, não sei porque isso, mas esta converão não e em valor que estou passando e sim e peso, para impressão de etiquetas somente, então no caso acima seria 0.900kg para impressão de etiquetas, e não valor. me desculpe o código acima não esta mo formato adequado, estou iniciando em c# então acho que ainda tenho muito que aprender...
Comment: Desconfiei, eu trabalhava lá, sempre fui crítico disto. Mas parece que agora está pior que na minha época. Se isto não for usado para mais nada talvez seja só o caso de pedir os dados de outra forma para evitar o erro de digitação. Eu corrigiria o problema de segurança, é muito sério.
Comment: Vou verificar esta parte da segurança sim, muito obrigado pela atenção.


Labeling a dominant triad over subdominant bass

Question: I wanted to highlight a particular chord of my previous question because it was bugging me a bit. What would you call a dominant triad over a subdominant bass, in pop/jazz roman numeral analysis? It could be seen as a V7 in third inversion, but if you have a strong subdominant bass it doesn't really sound like it. But just calling it a IV seems... meh. Especially because we call the inverse, a subdominant triad over a dominant bass, a sus chord.
Update: Thanks all for your responses. As most of you have said, roman numeral analysis isn't really suited for these kinds of chords. I might decide to just slash chords for bass and then come up with a different way to notate secondary chords and modulations in a functional manner. I don't want to do this literally because that doesn't make sense in a tonic-agnostic notation.
Comment: How about V7/IV or just V/IV? That's a G/F chord.
Comment: The problem with that is: it's a slash chord, which conflicts with the roman numeral analysis meaning of V7 *of* IV.
Comment: I see. What's this analysis good for anyway? ;) If something as basic as G/F is difficult, it must completely explode at F/G. (just joking) TBH I thought I had seen V/IV somewhere as meaning this case, in addition to the secondary dominant meaning. But couldn't find where that was. Maybe you could tweak the notational practices by adding an explanation text, "in this example, V/IV means ..."
Comment: To allow me to more easily transpose in every key when playing a piece. I could go for a more literal spelling, but understanding the piece better, also allows me to play it better. I guess my notation is somewhere in between literal and full-on analysis. I don't notate inversions for example.
Comment: This probably doesn't help at all, but I think of scale degrees, chords and inversions etc. in terms of objects and spatial locations, not in terms of textual symbols at all. What shape is my basic chord and where do I put it, where do I put my bass note. They are like my hands, I can think about my left hand without thinking about any word or letter. Just like I can think about my left back pocket without assigning it any text or symbol or number, I think about scale degrees and chord roles. Chords and notes are _objects_ with a _shape_, in _locations_ in _space_ where I move and operate.
Comment: Isn't it just an inverted dominant 7th chord? Its Roman numeral symbol would be V4/2 (a V with a superscript 4 and subscript 2).
Answer: Not fully understanding the dots - it's key C,from the key sig., and the chords go from F to G7 back to F.
That G7 is in 3rd inversion, because the F is in the bass.If it was going to be called V/IV, in key C, that would make it C7, which it obviously isn't, and anyway C7 would be designated I7.
RN isn't particularly helpful in cases such as this. It could be called G/F, which again isn't helpful fot transcription to other keys.
A better way would be to label using NNS - the Nashville Number System.
Comment: I agree, NNS is worth learning. But could you explain how it makes this example easier?
Comment: @user45266 - it's more 'bare bones' and not steeped in history!
Answer: I see two ways to analyze this. First, it's just a IV-V7-IV with a subdominant pedal. Another possibility is a IV-V42-IV progression. Both give the same note. I think the first describes the music a bit better. It might be worth looking at some of Handel's stuff as he liked the third inversion seventh enough that it's been commented on in the music history books.
"Passing" or "non-functional" chords are not always easy to describe; they often arise from just voice-leading considerations rather than being part of a harmonic direction. (They don't conflict with harmonic functions, they only "decorate" them.)
Comment: But does the second chord sound like a V7 to you? To me, it really doesn't.
Comment: Passing chords don't always sound the same as when used functionally. Also, a pedal point seems to disguise most chords with perhaps the exception of a pedal on the dominant. Here not only is it a passing chord, but also a 64 chord; these (to me anyway) always sound like decorations rather than functional. Analysis of chords over an independent bass line isn't well described by most analyses.
Answer: In your last question, you engaged with the common-tone diminished seventh chord (CT°7). But diminished sevenths aren't the only possible common-tone chords; another common possibility is the common-tone dominant seventh (CTV7), which I would argue is what we have here.
This is especially common with IV moving to V above a scale-degree 4 pedal, as it does here. And it's exactly the same as the opening of "Part of Your World" from The Little Mermaid: "Look at this stuff" is above a IV chord, and "isn't it neat?" is above a CTV7, that V42 where V is above a pedal of scale-degree 4. It resolves back to IV on "Wouldn't you think..."
I think this label is better than understanding that middle chord as a true V42, because in most cases that V42 is going to resolve to tonic (and typically in first inversion, but that changes based on style and genre). Here it's clearly prolonging IV, and since common-tone chords are inherently prolongational, I think the CTV7 is the best interpretation.
Comment: I like this answer, I think you might be onto something about the common-tone prolongation being more important than strict harmonic function.
Comment: I don't think you're wrong, but honestly, it's hard to beat the plain V/IV in roman numerals - in the same way that I find IV/V a more functional expression than V9sus4. I'm starting to think whether I should just use the slash for bass and then 'V of V' etc. for secondary chords. (I'm sure many folks here will now roll their eyes haha.)
Answer: It's triads over a pedal.  F, G/F, F.   If tempted to call the second chord G7/F, take the idea a little further...

Wouldn't it be ridiculous to call that new chord A♭6/F?   No, these are plain triads over a pedal and deserve  to be named as such.
But I don't think Roman numbers deal with this very well.  It likes everything to be functional.
(This, of course, would be a different matter.  Here it IS a last-inversion G7.)
Comment: I agree with you that V/IV is the common sense way to do it. But then how to distinguish it from a secondary chord? (V of IV)
Comment: Yes,  V/IV means V of IV.    Like I said, Roman number analysis doesn't deal with this sort of non-functional harmony very well.
Answer: Normally the melody do-ti-la above IV (the subdominant) will be considered (the middle not e) as passing tone. Now together with  parallels of 3rd and 6th we get a resoti (V) chord. I think it is most useful to consider this passage as a slash chord and it will help you to transpose it easily in other keys.
I think the idea of passing tones or suspensions 6-5;9-8;11-10 is more logical than the 3rd inversion of V7.
Comment: The OP is asking, what is the official notation for writing slash chords in Roman numerals. Slash notation "V/IV" is already reserved for a different use meaning "five of four", i.e. in key C major it would mean secondary dominant, "dominant of F", i.e. C7. Maybe slash notation is used in other meanings as well even with Roman numerals, but I couldn't find credible evidence of that.
Comment: Then we must use the through bass notation 43;65;98. We over here use the secondary dominant in brackets: (V)V=V/V ...
Comment: @AlbrechtHügli So you use brackets for secondary chords and slash for the bass?
Comment: yes, if you look up the German wiki site of secondary dominante (Zwischendominante = the dominante *between* ). But for the slash chord V over IV you can invent your own signs, if you want.  Btw. I can use what I want, if I understand my language. Theory is never ending. ;)
Answer: I agree that these are modal 'color' chords over a pedal point. The V chord is not functioning as a dominant at all; rather, it brings out the Lydian nature of the IV chord. The Lydian mode gives that faraway, otherworldly sound, and is especially exploited in cinematic music.
You might have better luck with pop/jazz music notation, even though you lose the tonic-agnostic benefit of roman numerals. Check out this excerpt from a jazz lead sheet:

Here we see chords progressing over pedal tones. The emphasis is on readability. Functional analysis is left open to debate - this kind of music can have multiple, overlapping harmonic interpretations.


Is there a way in Lilypond to omit entire staffs from the pdf layout but listen to them in MIDI?

Question: I'm using Lilypond to compile music for my church choir.
I've recently discovered the use of midiMaximumVolume and midiMininumVolume so I can highlight a given staff to isolate a part.
I produce multiple Books at a time with identical 'bookOutputSuffix', often they are "All Parts", "Piano", "SATB", "Soprano", "Alto", "Tenor", and "Bass". Each book isolates the part, removing the other staves. Up to this point the MIDI files I've used also only isolated their part, but now I have all the music there, just quieter in comparison to the part I'm isolating so they have a reference point to the music.
But I want, in one \book, (possibly one \score ) the way to have just the "Tenor" part print isolated in the PDF layout without the "SAB" or "Piano" staves, but have all the music from all staves appear in the MIDI file while I use midiMaximumVolume and midiMininumVolume to make the "Tenor" part stand out.
I've done separate \books for MIDI and PDF Layout, but with having multiple books with the same \bookOutputSuffix I end up with "-Tenor.pdf" and "-Tenor-1.midi" which messes with my organizational system.
Answer: You can always create separate \score blocks for \layout and \midi.  Using \tag (and \keepWithTag and \removeWithTag) to organize your source helps in avoiding duplication of most material.
Comment: Answer could be improved with an example showing success.
Comment: I have chosen to select this answer, and I have posted my own answer to show the code for how I implemented it.
Answer: I've decided to accept user48549's answer, and in response to Carl Witthoft's comment, I'm going to show how I implemented the suggestion in my own workflow below:
First I set up the musical notations:
%% MUSIC %%

global = {
  \tempo 4 = 88
  \time 4/4
  \numericTimeSignature
  \compressFullBarRests
  \key c \major
  s1*4 \bar "|."
}
pianoUpper = {
  \new Staff <<
    \global
    \clef treble
    \relative c' {
      c4 c c c | c c c c | c c c c | c c c c | c c c c |
    }
  >>
}
pianoLower = {
  \new Staff <<
    \global
    \clef bass
    \relative c {
      c4 c c c | c c c c | c c c c | c c c c | c c c c |
    }
  >>
}
sopranoMusic = {
  <<
    \global
    \clef treble
    \relative c'' {
      c4 c c c | c c c c | c c c c | c c c c | c c c c |
    }
  >>
}
altoMusic = {
  <<
    \global
    \clef treble
    \relative c' {
      c4 c c c | c c c c | c c c c | c c c c | c c c c |
    }
  >>
}
tenorMusic = {
  <<
    \global
    \clef "treble_8"
    \relative c' {
      c4 c c c | c c c c | c c c c | c c c c | c c c c |
    }
  >>
}
bassMusic = {
  <<
    \global
    \clef bass
    \relative c {
      c4 c c c | c c c c | c c c c | c c c c | c c c c |
    }
  >>
}

And the lyrics:
%% LYRICS %%

commonLyrics = \lyricmode {
  la la la la
  la la la la
  la la la la
  la la la la
  la la la
}
sopranoLyrics = \lyricmode {
  \commonLyrics ooh
}
altoLyrics = \lyricmode {
  \commonLyrics aah
}
tenorLyrics = \lyricmode {
  \commonLyrics eh
}
bassLyrics = \lyricmode {
  \commonLyrics hmm
}

Then I set up the parts:
%% PARTS %%

% Normal Volume Parts

piano = {
  \new PianoStaff \with {
    instrumentName = #"Piano"
    shortInstrumentName = #"Pno."
  } <<
    \pianoUpper
    \pianoLower
  >>
}

soprano = {
  \new Staff \with {
    instrumentName = #"Soprano"
    shortInstrumentname = #"S"
  } {
    \sopranoMusic
  }
  \addlyrics \sopranoLyrics
}

alto = {
  \new Staff \with {
    instrumentName = #"Alto"
    shortInstrumentname = #"A"
  } {
    \altoMusic
  }
  \addlyrics \altoLyrics
}

tenor = {
  \new Staff \with {
    instrumentName = #"Tenor"
    shortInstrumentname = #"T"
  } {
    \tenorMusic
  }
  \addlyrics \tenorLyrics
}

bass = {
  \new Staff \with {
    instrumentName = #"Bass"
    shortInstrumentname = #"B"
  } {
    \bassMusic
  }
  \addlyrics \bassLyrics
}

Then I add additional parts for Loud and Soft versions. I can omit the lyrics and the instrument name since these parts are only rendered in MIDI.
% Soft Volume Parts

pianoSoft = {
  \new PianoStaff \with {
    midiMinimumVolume = #0.2
    midiMaximumVolume = #0.4
  } <<
    \pianoUpper
    \pianoLower
  >>
}

sopranoSoft = {
  \new Staff \with {
    midiMinimumVolume = #0.2
    midiMaximumVolume = #0.4
  } {
    \sopranoMusic
  }
}

altoSoft = {
  \new Staff \with {
    midiMinimumVolume = #0.2
    midiMaximumVolume = #0.4
  } {
    \altoMusic
  }
}

tenorSoft = {
  \new Staff \with {
    midiMinimumVolume = #0.2
    midiMaximumVolume = #0.4
  } {
    \tenorMusic
  }
}

bassSoft = {
  \new Staff \with {
    midiMinimumVolume = #0.2
    midiMaximumVolume = #0.4
  } {
    \bassMusic
  }
}

% Loud Volume Parts

sopranoLoud = {
  \new Staff \with {
    midiMinimumVolume = #0.6
    midiMaximumVolume = #0.9
  } {
    \sopranoMusic
  }
}

altoLoud = {
  \new Staff \with {
    midiMinimumVolume = #0.6
    midiMaximumVolume = #0.9
  } {
    \altoMusic
  }
}

tenorLoud = {
  \new Staff \with {
    midiMinimumVolume = #0.6
    midiMaximumVolume = #0.9
  } {
    \tenorMusic
  }
}

bassLoud = {
  \new Staff \with {
    midiMinimumVolume = #0.6
    midiMaximumVolume = #0.9
  } {
    \bassMusic
  }
}

Then with every book that I want to isolate a part for I can add two scores, one with the \layout {} block and the other with the \midi {} block:
%% BOOKS %%

% All Parts (No Isolation)
\book {
  \header {
    title = #"My Song"
    instrument = #"All Parts"
  }

  \bookOutputSuffix "All-Parts"

  \score {
    <<
      \new ChoirStaff <<
        \soprano
        \alto
        \tenor
        \bass
      >>
      \piano
    >>

    \layout{}
    \midi{}
  }
}

% Soprano (Soprano Part Isolated)
\book {
  \header {
    title = #"My Song"
    instrument = #"Soprano"
  }

  \bookOutputSuffix "Soprano"

  \score {
    <<
      \new ChoirStaff <<
        \soprano
      >>
    >>
    \layout{}
  }

  \score {
    <<
      \new ChoirStaff <<
        \sopranoLoud
        \altoSoft
        \tenorSoft
        \bassSoft
      >>
      \pianoSoft
    >>
    \midi{}
  }

  % Other parts omitted but similar to Soprano above.

The final output of those two books, if the file name is "My-Song.ly" should generate:

My-Song-All-Parts.midi (playing each part normally)
My-Song-All-Parts.pdf (containing all staves)
My-Song-Soprano.midi (Soprano part plays loudly, and all other parts softly)
My-Song-Soprano.pdf (containing only the Soprano staff)
Answer: \RemoveEmptyStaves or \RemoveAllEmptyStaves should work.  See Hiding Staves in the documentation.
Comment: In my case the staves wouldn't be empty. There would still be music in them. I've updated my question to reflect this.
Comment: Answer could be improved with an example showing success.


Am planning to upgrade angular v1.2.17 to latest legacy version 1.2.29

Question: Will there be any changes required in the code for this minor version upgrade ?
Comment: I guess there will be changes, you've to check the ChangeLog of the AngularJS
Comment: Thanks @Tushar it helps a lot. But i guess, there should not be any ground breaking change in minor version release. They often involve performance and bug fixes only.. Right ?
Comment: Angular Team has also added Breaking change list in the [Changelog](https://github.com/angular/angular.js/blob/master/CHANGELOG.md#breaking-changes)
Answer: You can check that directly in the Changelog


Why C++ doesn't default construct return value when return statement is not specified?

Question: According to the C++ standard function not returning the value produce an undefined behaviour. It was resonable for C where we don't have constructors but this why this haven't fixed in C++11/14/17?
I think it is natural to default-construct return value if no return statement occur during execution. It will make code cleaner and safer without breaking compatibility with old C++ and C code.
Compare:
optional<int> foo() try {
   return some_complex_computation();
} catch (err1& e) {
   LOG << e;
   return none;
} catch (err2& e) {
   LOG << e;
   return none;
} catch (err3& e) {
   LOG << e;
   // oops, undefined behaviour
}

and just
optional<int> foo() try {
   return some_complex_computation();
} catch (err1& e) {
   LOG << e;
} catch (err2& e) {
   LOG << e;
} catch (err3& e) {
   LOG << e;
}

Comment: How hard is it to type `return {};` that you need a language feature?
Comment: Any decent compiler will warn about this, turn up the warning level and/or actually start reading the warnings.
Comment: The language standard for C++ is developed openly. If you feel that this might enhance the langauge feel free to file a propsoal. Here are the guidelines: https://isocpp.org/std/submit-a-proposal
Comment: In your example, it returns a good value, or throws an exception.  That's a good model.  Just re-raise the exception. If you do neither, you WANT the compiler to reject the code.
Comment: Man, I really hate looking at someone else's code with long functions peppered with return statements :(
Answer: Returning a default-constructed value might be better than undefined behavior, but it's worse than the current state of affairs, which is that most compilers warn when the closing brace of a non-void function is (or may be) reachable.
Catching errors at compile-time is always best, and the current rule gives compiler developers the flexibility to do that.  By adding default-return, you blur the line between good code and bad code.
I suggest you read Raymond Chen's blog posts where he discusses that correct code is not enough, you need to be able to tell on inspection that is IS correct.  And he's not the only one, other well-known experts say the same thing.

Raymond Chen: Cleaner, more elegant, and harder to recognize
Raymond Chen: Cleaner, more elegant, and wrong
Joel Spolsky: Making Wrong Code Look Wrong
Comment: I could see some marginal value in having a `default return ;` statement that would be useful in code that has many places that are error (or "no value") returns and only a small number of places that return data. But you definitely would want to require a specific statement to invoke it. Otherwise, an accidentally omitted `return` would often not be detected at compile time.


How can I extend drush aliases with specific variables?

Question: I like to know if it is possible to extend drush aliases with more specific path variables. Is there anybody who can tell me how to extend the drush example code, that follows below with array for the file system paths for

temporary files directory
files directory
private files directory

So that I don't have to change them manually after every db sync when the dev server has other path settings then the productive server
This may be a silly question but I just looked at the documentation on github and haven't found any details.
Comment: Is there any reason you need to Drush in particular? Usually one would use an environment-specific settings.php file to override config vars for just that site, e.g. `$conf['file_temporary_path'] = '/path/to/tmp';`. Config Variables declared in settings.php will always override those in the database
Comment: The name of a variable is the same as the html 'name' attribute of the element used to input its value. Inspecting the HTML for the relevant admin pages will give you everything you need
Comment: so it seems i have missunderstood the concept and will rewrite my question
Comment: maybe good to know: by default settings.php is not sync with "drush rsync". So you can define your custom variable there as suggested by Clive. see "drush help rsync"
Answer: The Drush rsync and drupal-directory (dd) commands already supports the functionality you desire, without the need for you to extend your alias files.  For example, to copy your files directory:
drush rsync @live:%files @dev:%files
To copy a specific folder from your temporary directory:
drush rsync @dev:%temp/foo @live:%temp
To change your working directory to the location where the devel modulr is installed:
cd $(drush dd @dev:%devel)


Como contar toques (letras, espaços e símbolos) em PHP?

Question: Eu fiz um programa que extrai minhas anotações do meu código e cria um arquivo txt para ser um manualzinho. Fiz uma formatação para ficar mais legal:
+-----------+
|           |
| ESPECIAIS |
|           |
+-----------+

Ele pega a linha ESPECIAIS e formata. Simples! Ocorre que alguns não ficam bem formatados porque tem letras com acento, e neste caso não consigo contar os toques corretamente. A linha "FUNÇÕES" fica assim:
+-----------+
|           |
| FUNÇÕES |
|           |
+-----------+

Isso porque a string é formada pelos códigos 70|85|78|195|135|195|149|69|83 somando 9 caracteres pelo strlen do PHP, já que os acentos estão usando o prefixo 195, extrapolando a contagem em 2.
Este problema em específico não é difícil de resolver, mas quero aproveitar para compreender melhor a questão. Não sei como funciona a codificação dos acentos nesse caso (arquivo de texto UTF-8).
Em JavaScript eu conto os toques usando DOMElement.textContent.lenght que já compreende a string como texto.
Existe alguma função similar em PHP?
Answer: A solução mais simples é usar a função mb_strlen() que está preparada para lidar com caracteres multibyte como é o caso do UTF-8.
mb_strlen("FUNÇÕES") // produz 7

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Não estava funcionando. Como respondeste com tanta segurança, resolvi tentar de novo. Desta vez eu forcei o UTF-8 no segundo parâmetro do mb_strlen, que é opcional - funcionou! Às vezes eu defino o conjunto de caracteres no início do arquivo php, desta vez eu não fiz, talvez seja isso. De qualquer forma, é bom o cara estar atento a este detalhe. Valeu!


Line detection in 2D point cloud

Question: I am developing a larger system for navigation and positioning of automated guided vehicles and have stumbled upon a problem. When developing a map, the important part is finding the walls. The navigation is done using a LiDAR unit.
An example "image" of that the sensor sees is as follows:

And the wanted output is something like this:

I have looked alot at the Hough transform and the RANSAC algorithm but the Hough transform as from what I know is used on images which is not optimal for my case and the RANSAC is not great for finding multiple walls in sparse data.
The data that was used in this specific example can be found in this link: https://drive.google.com/file/d/1EnSOr2FYjIdqG1RdFgTkgsoEhVcG7Tl_/view?usp=sharing
Where the two arrays in the file represent x and y coordinates where elemets correspond by index.
Im developing in python but I have no issue to write the algorithm myself if anyone knows a suitable one that is not available in a package or so.
Thanks in advance, Jakob
Comment: @SuhasC Thank you for the answer, my cpp knowlage is close to non-existing but I will have a look at it.
Comment: From a clueless guy, perhaps you should cluster your points and then perform RANSAC? But why does HoughTransform not work? Theoretically it should work by finding the edges among your sparse points....and image is simply a collection of  points on a plane with light intensity values.
Comment: @JasonChia Yeah you might be right but then how do I properly cluster the measurements? When it comes to the Hough Transform I think I mainly came to a conclusion that it would require me to reduce the precision to much, I need to be able to estimate the walls to millimeter precision in a 50 meter long warehouse. Do you think the Hough could be used for that? Thank you for the answer.
Comment: Have you tried this code from PCL? Plane segmentation http://pointclouds.org/documentation/tutorials/planar_segmentation.php
Comment: @JakobVinkas have you found a solution in python? I'm facing the same problem too!
Answer: You could try mathematical morphology such as erosion/ dilatation https://docs.opencv.org/trunk/d9/d61/tutorial_py_morphological_ops.html
I tried on your image and it starts looking to a room :

Here is an example of implementation in  python using opencv:
<code>import numpy as np
import scipy.stats
import cv2

inputImage = cv2.imread('input.jpg')

skernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
cv2.imshow("test1",inputImage)

openImg =cv2.morphologyEx(inputImage, cv2.MORPH_OPEN, skernel, iterations =15)
cv2.imshow("test2",openImg)
img_gray = cv2.cvtColor(openImg, cv2.COLOR_BGR2GRAY)
ret,th3 = cv2.threshold(img_gray,200,255,cv2.THRESH_BINARY)

cv2.imshow("test3",th3)
</code>
Also I think that there is a missing keyword in your question since what you are looking for is a point cloud reconstruction algorithm. you may have a look here also https://hal.inria.fr/hal-01348404v2/document
Comment: Hi, thank you for the answer and for all the effort you went through. Sadly I suspect that this would yiled a less than optimal precision.. And I belive that the large amount of noise in the data is going to screw up the results to much using the "image analysis" method.
Comment: this approach does not provide a way to find the lines in the image. It only makes it 'look better' for a human, which is completely irrelevant in this case.
Comment: cv2 has canny edge detection, and there are loads of look for lines in the road functions for autonomous cars that can extend or ignore lines as needed.  Probably @jacobvinkas and others including myself would benefit from comparing the hough transform with the above and see which prove useful.
Answer: Probably a bit late for the original question, but I'm sure more people will want to solve the same problem.
Hough transform can very well be done on a point cloud, however I'm not aware of a ready to use library implementation.
Here is an excellent example with full explanation and source code: Processing LIDAR data using a Hough Transform
If you understand how Hough transform works and take a look at the code, you'll see how it iterates through the points and creates a 2-d histogram in the feature space. It's farly straightforward to implement something like this.

Line detection in 2D point cloud