QT UTC linux Clock skew detected. Your build may be incomplete

Question: I have a code which I am writing it in QT (C++) where I want to display a date on a dateTime display on the GUI.. I get the time from another component and then I parse it into argument list and then I use Qprocess to run date - u command .. anyhow it seems like my make doesn't like what I am doing because it prints out this error:
QT UTC linux Clock skew detected. Your build may be incomplete.

the whole purpose of what I am doing is to update the UTC time of my linux computer according to the value I am getting and then gets that date using QT code to get the computer UTC time
here is part of the code :
    if(month<10)
{
    argument  = "0"+ argument + QString::number(month);
}
else
{
    argument =  argument + QString::number(month);
}
if(day<10)
{
    argument = "0"+ argument + QString::number(day);
}
else
{
    argument =  argument + QString::number(day);
}
if(hourUTC<10)
{
    argument =  "0" + argument + QString::number(hourUTC);
}
else
{
    argument =  argument + QString::number(hourUTC);
}
if(minUTC<10)
{
    argument =  "0"+ argument + QString::number(minUTC);
}
else
{
    argument =  argument + QString::number(minUTC);
}
argument =  argument + QString::number(year);

argument =  argument +  ".";

if(secUTC<10)
{
    argument =  "0"+ argument + QString::number(secUTC);
}
else
{
    argument =  argument + QString::number(secUTC);
}
//argument =  argument + QString::number((qint32)qRound(msUTC/ 1000.0));

argumentlist << argument;

qDebug() << argumentlist;

QProcess* proc = new QProcess();

// Change system date and time "date -u MMDDhhmmYYYY.ss" in tha application the date is created dynamically
proc->start(program, argumentlist);
proc->waitForFinished();
m_pOi->setTime();

any idea how can I force the change in time to my compute ? and yea I do run the code as a super user !
Answer: I think this error happens when your file times are newer than your system clock. make warns you that it may not be building everything correctly because of this. touching all your files should sort out the problem.
One of the causes is an SCM system that preserves file times and is ahead of your system clock.
Comment: Right answer. Your build system check last modification time of your source files to point out what to compile and what is up-to-date. So it's a good idea to rebuild your project every time instead of incremental build to be sure that everything is built correctly when you're making such experiments with the system clock
Comment: I tried the touch command on the files and I got this error when I recompiled e: Warning: File `OBY_GUI.pro' has modification time 422 s in the future
Comment: make: warning:  Clock skew detected.  Your build may be incomplete.


Converting explicit solution to implicit solution of linear system

Question: I am trying to convert the explicit solution of a linear system back to its implicit form.
I am given the following system of equations:
$$
\begin{cases}
    x + y + z = 0 \\
    x - y + 2z = 1
  \end{cases}
$$
We can solve the system using gaussian elemination to obtain the explicit solution:
$$
(x,y,z) = \left(\frac{1}{2}-\frac{3}{2}t,\ -\frac{1}{2}+\frac{1}{2}t,\ t\right) \text{ where } t \in \mathbb{R}
$$
Now we can describe the solution set of this system in 2 ways:
Implicit solution:
$$
\{ \ \left(x,y,z\right) \ | \ x + y + z = 0 \text{ and } x - y + 2z = 1 \ \}
$$
Explicit solution:
$$
(x,y,z) = \left(\frac{1}{2}-\frac{3}{2}t,\ -\frac{1}{2}+\frac{1}{2}t,\ t\right) \text{ where } t \in \mathbb{R}
$$
From the above, we know how to convert from the implicit to the explicit solution. But I do not know how to convert from the explicit to implicit solution. Could somebody please advise me?
Answer: From the parametric equations
$$\begin{align}
x &= \frac{1}{2} - \frac{3}{2} t \\
y &= -\frac{1}{2} + \frac{1}{2} t \\
z & = t
\end{align}$$
derive $t=z$ and use it to eliminate $t$ from the first two equations.  You get:
$$\begin{align}
x + \frac{3}{2} z &= \frac{1}{2} \\
\frac{1}{2} z &= y + \frac{1}{2} \enspace.
\end{align}$$
This solves the "implicitization" problem.  If you want to go back to the original equations, maybe as a verification step, write the first as
$$ x + \frac{1}{2}z + z = \frac{1}{2} \enspace, $$
and substitute the second to get $x + y + z = 0$.  Also, from the second equation, get $-2y + z = 1$.  Add $x + y + z = 0$ to it to get $x - y + 2z = 1$.


Ada rendezvouz mutual synchronization

Question: So i've got code like this:
task body Task1Type is
begin
    Put_Line("Task1 Part1");
    Task2.Part1Ready;
    accept Part1Ready;
    Put_Line("Task1 Part2");
end;

task body Task2Type is
begin
    Put_Line("Task2 Part1");
    Task1.Part1Ready;
    accept Part1Ready;
    Put_Line("Task2 Part2");
end;

My logic tells me that part2 in every task must run after both tasks completed task1. But it doesn't. Where I'm wrong?
Answer: When Task1 calls Task2.Part1Ready, it blocks until Task2 issues accept Part1Ready. Likewise, when Task2 calls Task1.Part1Ready, it blocks until Task1 issues accept Part1Ready.
This is known as a 'deadly embrace', and means that neither task can proceed. One way round this is to use a protected object, perhaps like this:
protected Readiness is
   procedure Task_1_Ready;
   entry Wait_Until_Task_1_Ready;

   procedure Task_2_Ready;
   entry Wait_Until_Task_2_Ready;
private
   Task_1_Is_Ready : Boolean := False;
   Task_2_Is_Ready : Boolean := False;
end Readiness;

protected body Readiness is
   procedure Task_1_Ready is
   begin
      Task_1_Is_Ready := True;
   end Task_1_Ready;

   entry Wait_Until_Task_1_Ready when Task_1_Is_Ready is
   begin
      null;
   end Wait_Until_Task_1_Ready;

   procedure Task_2_Ready is
   begin
      Task_2_Is_Ready := True;
   end Task_2_Ready;

   entry Wait_Until_Task_2_Ready when Task_2_Is_Ready is
   begin
      null;
   end Wait_Until_Task_2_Ready;
end Readiness;

Then get rid of the Part1Ready task entries, replacing
task body Task1Type is begin
   Put_Line("Task1 Part1");
   Task2.Part1Ready;
   accept Part1Ready;
   Put_Line("Task1 Part2");
end;

with
task body Task1Type is begin
   Put_Line("Task1 Part1");
   Readiness.Task_1_Ready;
   Readiness.Wait_Until_Task_2_Ready;
   Put_Line("Task1 Part2");
end;

and vice-versa in Task2Type.

Ada rendezvouz mutual synchronization


Why do people place speaker cabinets or combo amps on top of things?

Question: In a lot of gigs I've played, I have noticed that they have placed the amplifier speaker cab (usually just the bass amp) on top of a chair or a stool or something, so as not to be on the ground.
What is the benefit of something like that?
Answer: It is so the speaker is pointed more towards your head than your feet and so you can hear yourself better. If a small combo-amp is on the ground, the sound has to bounce quite a bit to actually get to your ears and if you are at a band practice or a gig it may mean bandmates can hear you better than you can hear yourself. If your speaker is pointed at your head you can usually cut down on a lot of volume and still hear yourself just as good then if it was louder and pointed away from your head.
Another trick some people use is they tilt the combo-amp back so they can leave it on the ground and still have the sound from the amp directly pointed at their head. If everyone in the band with an combo-amp does one of these tricks it can seriously reduce stage volume.
In all my experience as a sound technician the number one issue is and will always be stage volume being to loud. It leads to many, many problems including:

Feedback (High and Low)
Signal Distortion
"Bleeding" sounds (when instruments are mic-ed sometimes sounds other than the instrument are picked up)
Musician not being able to hear themselves and others
Musician's hearing being damaged
Damage/Excessive Vibrating due to a material's Fundamental Frequency

Any one of these is a serious issue and have to be dealt with for live sound. The bass being on the low end of the frequency range has to be kept even more in check because of feedback and issues with Fundamental Frequencies. The less intense (loud) the sound is the less problems it causes. Also bassist will turn up if they can't hear themselves and every speaker I've ever seen is louder if you point it at your ears because that is how they are designed to work.
Answer: I see that you noticed this happens usually with the bass amp, and I don't see an answer addressing bass in particular.
I can think of some reasons:
Mechanical Coupling
Bass amps are isolated from the floor to avoid mechanical coupling.
Depending on the venue (stage design, materials, acoustics, etc) floor vibration can cause an array of problems, like triggering the snare  and inducing movement noise on mics. This can be specially bad and nasty if a particularly strong resonance occurs, not only for the noise it will cause, but for the added potential of feedback.
Sound Design
Another possibility for that specific amp placement is sound-design. If microphones are being used, the timbre of the instrument and amp  combo will be different depending on the placement of both the mic and the amp.
Comment: The bass from the amp would not be as relevant as the bass from the house subs which are much more powerful and contain all the low frequencies on stage. If the stage is vibrating from just a bass amp then the house subs will definitely cause a worse problems because in most venues they are sitting right on the stage.
Comment: @Dom Of course all subs have the same problem, it's not exclusive to bass amps! That's not relevant to my answer, though. Also, not all sound waves are directional, you got that backwards! In fact, sound waves of all frequencies are naturally omnidirectional (the total opposite)! It's the sound source characteristics and the wave length what carves the directionality. As we go lower in frequency, and the wavelength becomes larger than the sound source, the sound waves become less directional and more omnidirectional (inverse relationship). Low frequencies are the opposite of directional.
Comment: @Dom That depends on the speaker system used and the system placement/design. House subs can be directional and/or have their own isolation dynamic or placement. Even if this is not the case, there is no need to add additional mechanical coupling if it can be avoided; FOH sound doesn't kill the amps and monitor sound, on the contrary, it interacts with it.
Answer: "I see another answer explains that the positioning is to "hear yourself better", but this will be hardly the case for bass amps, since those wavelengths are not very directional. Bass amp isolation from the floor will make little to no difference; low frequencies, the ones produced by the bass, are omnidirectional (unless a special system is used, which is not the case of bass amps)."

That's not strictly true (sorry!). It's in degrees : The lower end of the bass range is less directional, and will "fill the room", but middle-top end of bass definitely is directional and that's where the detail is. Our bassist always stands his amp on the drummer's floor tom case (as it's not being used)-  it's about the right height and quite sturdy. The reason is so that he can hear himself without having to turn up, as Dom suggests.

Bottom line is you don't have ears in your knees, so you need to point the amp at your head a little bit so you can catch some of the sound being played.
Worst case of NOT doing this I've experiences was a keyboard player who put his amp under the keyboard (in front of knees), pointing forward. He could hardly hear himself, but to the audience he was blisteringly loud. Turned it up more to hear himself .. it didn't end well.
Comment: Brain fart: wasn't thinking about the highest harmonics. Removed that part from my answer.
Comment: I sometimes use my combo amp as a seat when playing keyboard.  I have to be aware of how this affects what I hear of course.  But I'm a LOT nearer to the speaker than the audience is. Having it pointing at MY ears, that close up, would be painful.
Comment: @LaurencePayne Interesting - I bet you can 'feel' the sound a bit too,  hahaa. I've seen a band where the guitarist had is fair-sized combo amp at the side of the stage pointing across it. They sounded fine, quite a good mix but I bet his guitar was loud on stage. Seemed to work though.


ResNet 34 training with custom dataset

Question: I am a beginner in Neural Networks and wanted to implement ResNet34 for a pet project at my workplace. Due to confidentiality issues, I do not want to use ImageNet trained weights.
I have a dataset of around 10000 images which I can use to train my dataset. Can you suggest if that is possible without overfitting. I can use data augmentation for additional data.
Any help is appreciated. Thanks.
Comment: Not sure how confidentiality makes transfer learning an issue. That does not make sense to me and i would strongly consider it.
Answer: Ideally, you'd want a bit more images in order to train your model effectively. I've managed to train a couple of ResNet-50 models on around 10000 MR Images from scratch, without much problem.
However, what I was trying to solve was a relatively easy task. If you want to train your model on a more generic task, you might encounter a few issues. On the other hand, because of the strict format of MRIs, I couldn't augment my images to a large degree.
Comment: I am trying to classify documents into around 10 categories. Do you think it would work ?
Comment: And each document is represented as an image?

ResNet 34 training with custom dataset


Can't upgrade from SQL 2008 R2 Evaluation to Workgroup

Question: I have a Windows Server 2008 server with SQL Server 2008 R2 Evaluation edition. I am trying to upgrade to SQL Server 2008 R2 Workgroup edition and having a problem.
When installing I get the error:

Rule "SQL Server 2008 edition upgrade" failed.
The Selected SQL Server instance does not meet upgrade matrix requirements.'

According to the Microsoft Upgrade Matrix I needed to uninstall Analysis Services (which I did), but I still get the same problem.
Any help would be appreciated!
Answer: So the real answer was that I was given the SQL Server 2008 Workgroup disk, not the SQL Server 2008R2 Workgroup disk.
SQL server cant' downgrade from 2008R2 to just straight 2008, so really there was no system error, just user error.
Answer: had this error:
<code>---------------------------
Rule Check Result
---------------------------
Rule "SQL Server 2008 edition upgrade" failed.

The selected SQL Server instance does not meet upgrade matrix requirements.
---------------------------
OK
---------------------------
</code>
on a upgrade 2008 R2 Standard to Enterprise.
My issue what that I started the wrong SQL Server Installation Center
The right one is the R2 at "C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\SQLServer2008R2\x64\LandingPage.exe"


A maximum principle

Question: Suppose that $\Omega\subset\mathbb{R}^n$ is bounded with smooth boundary $\partial\Omega$. Consider the elliptic boundary value problem for $\phi=\phi(x)$, $x\in\mathbb{R}^n$:
\begin{equation}%%\label{eqn: cn cp phi system with steric effect stationary solns}
\begin{cases}
-\Delta \phi\geq \eta(\phi^{\ast})(\phi-\phi_0)\quad \text{in}\quad\hspace{2.5mm} \Omega,\\
\hspace{7mm}\phi=0 \hspace{28mm} \text{on}\quad \partial\Omega,
\end{cases}
\end{equation}
where $\eta(\phi^{\ast})<0$, for some $\phi^{\ast}\in\mathbb{R}^1$  and $\phi_0\in\mathbb{R}^1$ is arbitrary. Does this problem enjoy the maximum principle? In other words, could we conclude that $\phi>0$ in $\Omega$?
Comment: Indeed, let $w=\phi-\phi_0$, then $w$ satisfies
$$
\begin{cases}
-\Delta w\geq \eta(\phi^{\ast})\,w\quad \text{in}\quad\hspace{2.5mm} \Omega,\\
\hspace{7mm}w=-\phi_0 \hspace{7mm} \text{on}\quad \partial\Omega.
\end{cases}
$$The maximum principle leads to $w>-\phi_0$ in $\Omega$, i.e. $\phi>0$ in $\Omega$. Is this argument correct?
Comment: Argument is correct only if $\phi_0$ is negative. Such an assumption is not in the question statement.
Comment: Thanks for the reply. According To Corollary 3.2 in Gilbarg-Trudinger, $\phi_0$ should be positive so that $inf_{\partial\Omega} w^{-}=-\phi_0$
Comment: Someone provided me a counter example. As $\phi_0<0$, the conclusion cannot be true, as shown by the following example: Let $\Omega=(-1,1)$ and $\phi=x^2-1$. Then it is easy to see that $\phi=0$ on $\partial\Omega$ and $\Delta \phi=-2\geq (-1)(\phi-(-100000))$ in $\Omega$, where $\eta(\phi^{\ast})=-1$ and $\phi_0=-100000$. However, $\phi=x^2-1<0$ in $\Omega$.
Answer: It depends on the sign of $\phi_0$. You have
$$
-\Delta \phi -\eta(\phi^*)\phi \ge -\eta(\phi^*)\phi_0.
$$
If in addition  $\phi_0$ is positive, then $\phi$ must be positive as well.

A maximum principle


Review on BoundView and UnboundView

Question: I would like to share the following snippet of a Bound/Unbound views to get feedback. Any suggestions will be welcome.
Yn.UnboundView = Em.View.extend({

  item: null,

  didInsertElement: function() {
    this._super();
    this.$().text( this.get('item') );

  }

});

Yn.BoundView = Em.View.extend({

  item: null,

  render: function(buffer) {
    buffer.push( this.get('item') );
  },

  _itemDidChange: Ember.observer(function() {
    this.rerender();
  }, 'item')

});

Comment: What are you trying to accomplish?
Comment: I need sometimes to have an UnboundView or BoundView as a child of a more complex composite view.
Answer: This is more idiomatic:
App.MyBoundView = Ember.View.extend({
    template: Ember.Handlebars.compile('Value: {{value}}'),
    valueBinding: 'App.myController.value'
});

Or unbound version:
App.MyUnboundView = Ember.View.extend({
    template: Ember.Handlebars.compile('Value: {{unbound value}}'),
    valueBinding: 'App.myController.value'
});

Or even:
App.MyOtherUnboundView = Ember.View.extend({
    template: Ember.Handlebars.compile('Value: {{unbound value}}'),
    value: 42
});

Sample @ http://jsfiddle.net/MikeAski/GcUMu/
Comment: That was my first approach, but then it came to my mind that perhaps we don't need a template for these cases.

Review on BoundView and UnboundView


Stochastic Processes/Trajectory and a Standard Example for a Modification

Question: I try to understand the nature of the sample space $\Omega$ for a stochastic process $(X_t)_{t \in I}$. Similar to the question here, I wonder what a fixed $\omega \in \Omega$ means, when we talk about a trajectory or path given by the function on $I$ , $t \rightarrow X_t(\omega)$. I can follow the explanation here that $\omega$ encodes a whole sequence and in the book from Oksendal "Stochastic Differential Equations" it is written that $\Omega$ should be regognized as a subset of the space $\tilde{\Omega}=(\mathbb{R}^n)^I$ of all function from $I$ into $\mathbb{R}^n$, if the stochastic process maps to $\mathbb{R}^n$. However, checking the consistency of these statements (and my poor imagination) with examples of stochastic processes, I stumbled over the following example for a modification of a stochastic process see also here (which is quite standard as far as I get it):
$\textbf{Example:}$ Let $\Omega = [0,\infty), \mathcal{A} = \mathcal{B}([0,\infty))$ and $P$ be a probability measure on $\mathcal{A}$ which has a density. Define two stochastic processes $(X(t): t \ge 0)$ and $(Y(t): t \ge 0)$ by
\begin{align}
X(t)(\omega) =
\begin{cases}
1, \text{ if $t = \omega$},\\
0, \text{ otherwise}
\end{cases}
\quad Y(t)(\omega) = 0 \quad \text{for all $t \ge 0$ and all $\omega \in \Omega$.}
\end{align}
Then $X$ and $Y$ are modifications of each other.
I wonder how the idea that $\omega$ should encode the whole sequence relates to the specific sample space $\Omega = [0,\infty)$ given by the example. In this case $\omega \in \Omega$ is just a real number, isn't it? If this statement is true, then dimensionality of $\omega$ does not match my expectations.
On the one hand, $I$ seems to be the non-negative real number line $\mathbb{R}_{\geq 0}$. On the other hand, we obtain a single non-negative real number $\omega \in \Omega  \, \forall t \in I$? Where is the randomness (in time) in this case?
Answer: Well, this is a nice question, but I would recommend you not to care too much about the structure of $\Omega$, as this is quite a delicate matter.
Say, it is possible to define the process "canonically", i.e. on $\Omega = \mathbb R^{[0,\infty)}$: define $\xi:[0,\infty) \to \mathbb R^{[0,\infty)}$ by $\xi: x\mapsto  \mathbf{1}_{\{x\}}(\cdot)$ and let
$$
\mathrm P(A) = P(\xi^{-1}(A)), A\in \mathcal B(\mathbb R^{[0,\infty)}),
$$
where $P$ is some probability measure on $\mathcal{B}([0,\infty))$. Then,
$X_t(\omega) = \omega(t)$ is as in your example. However, the $\sigma$-algebra $B(\mathbb R^{[0,\infty)})$ is quite poor, for instance, the event $\sup_{t\in[0,1]} X_t>0$ will not be measurable unless $P|_{[0,1]}$ is discrete (supported by at most countable set). The problem appears since the whole space $\mathbb R^{[0,\infty)}$ is "too large". To resolve the issue, one can work in a smaller space. In this situation, the space of functions having left-hand and right-hand limits at each points may be suitable, but one has also to consider appropriate topology. So perhaps the best choice is to work, as proposed in the original post, on $\Omega=[0,\infty)$, which we are best acquainted with.
Long story short, there is no problem with a "small" $\Omega$. Vice versa, too large sample space may cause a problem. Actually, any sample space is fine as long as it allows you to pose questions and answer them.
Comment: This is a nice and comprehensive answer, I think the math is a little about my current skills. So sorry for the following up question: I suppose for the subspace $\Omega$ of $\tilde{\Omega}$ we choose all indicator functions $\mathbb{1}_{\{s\}}$ with a random parameter s for a specfic outcome $\omega$ , so that $X_t(\omega)=\mathbb{1}_{\{s\}}(\{t\})$ and $Y_t(\omega) = 0$?
Comment: @StF, yes, you can do that.


Como fazer retorno com Ajax BeginForm

Question: Eu tenho meu Form com a seguinte declaração:
@using (Ajax.BeginForm("Novo","Cliente", new AjaxOptions
{
    OnSuccess = "OnSuccess",
    OnFailure = "OnFailure"
}))
{ }

Minhas funções no js:
function OnSuccess(response) {
    alert(response);
}

function OnFailure(response) {
    alert(response);
}

E meu Controller:
public ActionResult Novo(MyModel model)
{
    if (ModelState.IsValid)
    {
        return Json(new { data = 1 }, JsonRequestBehavior.AllowGet);
    }
    return View(model);
}

Mas ele não chama minhas funções, retorna um Json na página toda.
O que está errado?
Comment: Tiago, na verdade, minha validação é toda no cliente, o ModelState seria usado para retornar a view com validação caso o js estiver desabilitado, outra coisa que omiti, é que tenho 2 submit, um que salva e é direcionado para minha Index, e outro que habilita outras informações da tela de cadastro, então para isso eu retorno um Json com o Id que recém foi salvo
Comment: Retorna a página branca,com o valor 1 apenas, sim, se ele não estiver válido retorna a view, caso contrário ele deve retornar esse Id para que eu possa tratar ele no cliente
Comment: Está na página toda e possui sim botão de submit
Comment: Oi Tiago, pesquisei aqui e vi que para usar o helper Ajax, precisa da lib jquery unobtrusive ajax
Comment: Nem tinha me tocado, se quiser fazer uma resposta e referenciado isso, pode fazer...
Answer: De fato além do jQuery você precisa do plugin Microsof jQuery Unobtrusive Ajax que pode ser obtido via NuGet.
Então a estrutura mínima para efetuar o processo é:

E o helper é no mínimo assim:
@using (Ajax.BeginForm("Novo", "Cliente", new AjaxOptions
{
    OnSuccess = "OnSuccess"
}))
{
    <button type="submit">Submit</button>
}

E a função JavaScript OnSuccess:

Dessa forma você consegue utilizar o Ajax.BeginForm. Se quiser evitar mais um plugin só para envio de requisições Ajax, você pode fazer manualmente sem a necessidade do Unobtrusive Ajax:
@using(Html.BeginForm("Novo", "Cliente", FormMethod.Post, new { id = "formCliente" }))
{
    <button type="submit">Submit</button>
}

Com um script:
$(function () {
    $("#formCliente input[type=submit]").click(function (event) {
        event.preventDefault();
        var form = document.getElementById("formCliente");
        var data = $(form).serialize();
        $.post(form.action, data, function (response) {
            if (response && response.data)
                alert(response.data);
        });
    });
});

E se você usa o Unobtrusive Validate:
$(function () {
    $("#formCliente input[type=submit]").click(function (event) {
        event.preventDefault();
        var $form = $("#formCliente");
        $form.validate();
        if ($form.valid) {
            var data = $form.serialize();
            $.post($form.attr("action"), data, function (response) {
                if (response && response.data)
                    alert(response.data);
            });
        }
    });
});

Como fazer retorno com Ajax BeginForm


Change text displayed when cart is empty

Question: I'm using Drupal 7 with Commerce and I'd like to change the text shown when the user visits /cart and they have not added any items, from the default "Your shopping cart is empty." to a custom message, preferably that contains HTML.
I have tried adding custom text under no results behavior commerce_cart_form view with no luck.
What is the best way to do this?
Answer: I think a theme function called commerce_cart_empty_page is used. So you should be able to add a function:
MYTHEME_commerce_cart_empty_page()
to your themes template.php file and return whatever html you want.
You can also do the same for the cart block with a theme function MYTHEME_commerce_cart_empty_block()
Comment: Perfect, thank you. This is what I was looking for :)
Comment: This works like magic.. Likes :)


Revolving Beacon confusing calculus problem

Question: This is not homework. I have the solutions, I just can't understand why mine are wrong.
The problem states: A revolving beacon $3600$ feet off a straight shore makes $2$ revolutions per minute. How fast does its beam sweep along the shore, (a) at the point on the shore nearest the beacon? (b) at the point on the shore $4800$ feet away from the beacon?
My solutions (second one is wrong): I didn't feel I needed calculus to solve (a). Basically the beacon is travelling 2 times the circumference of a circle of radius 3600 feet at (assumedly) constant speed in 1 minute, so $$C = 2 \pi r = 7200 \pi$$ and therefore $v = 14400 \frac{feet}{minute}$, which is going to be the instantaneous speed at any point on the circumference of that circle, and this agrees with the solution in the book.
For (b), I figured that since the point is $4800$ feet away from the beacon, I could just again take the constant speed of the beacon along the circumference of a circle of radius 4800 this time and have that be the instantaneous speed at any point along the circumference of that circle, and therefore at the point on the shore $4800$ feet away from the beacon.
Which gives me $$C = 2 \pi r = 9600 \pi$$ and $v = 19200 \frac{feet}{minute}$.
However, the book disagrees with that result, and states:
Measuring the distance, $x$, along the shore from the foot of the perpendicular from the beacon to the shore and taking $A$ as the angle between this perpendicular and the beam, we have $x = 3600 \tan{A} $. Hence, $\frac{dx}{dt}=\frac{14400 \pi}{\cos^2{A}}$, making the answer to (b) $25600 \pi \frac{feet}{minute}$.
I don't understand why my answer to (b) is wrong. If constant speed made sense as instantaneous speed at a point given a radius of $3600$, why doesn't it work for a radius of $4800$. I fail to see how the two questions are fundamentally different.
Answer: The difference is the angle the shore makes with the light beam at each spot.
Note that the question asks "How fast does its beam sweep along the shore," which implies that the direction is parallel to the shore. Your method calculates the speed along (tangent to) the circle swept out by the light beam.
In your part (a) the shoreline is tangent to the swept-out circle, so your direction is along the shore and your answer agrees with the book's. In part (b) the circle intersects the shoreline at an angle, which your answer did not take into account.

(As pointed out by @Michael in the comments, the following analysis is incorrect. I'll leave it here so the comments make sense.)
It is possible to get from your answer to the book's answer. Your answer is the component of the desired velocity vector that is perpendicular to the ray from the beacon to the intersection point of circle and shore. You can use trigonometry to find the angle of the desired velocity vector to your component and then the magnitude of the desired velocity vector. We do that kind of problem in my 12th-grade Physics class, but I won't bother doing it here. Ask if you want those details, but I think my first three paragraphs answer your stated question.
Comment: How can Jeremy use his answer to get the book's answer? If you imagine the velocity vector of the radius-4800 circle, its speed into the beach is $19200\pi$ as Jeremy calculated (of course moving at an angle into the beach), but taking its component in the direction along the shore gives $19200\pi \cos(A) = 14400\pi$, which is less than the book answer.  The problem is counter-intuitive since there is a quadratic effect due to the circle radius itself changing.
Comment: I guess the moral of the story is to first come up with $x(t)$ as a function of $t$ (the book gives $x(t) = 3600\tan(A(t))$) and then use derivatives. I likely would have gotten this problem wrong myself by being lazy and not deriving $x(t)$ or noticing the quadratic effect.
Comment: Rory, thank you for your answer. I see now that I should've imagined the light travelling along the coast, whereas what I was imagining at the time was the light hitting the coast at an angle. However, it's not intuitive to me why there is a difference between those two speeds at that point. Do you have an intuitive way to think about it physically speaking? Or any way, really...
Comment: Physically, I can see that the speed of the light along the coast slows down as it gets closer to the perpendicular to the coast, whereas the speed of the light along the circumference of the circle of radius d is constant. However, shouldn't they approach the same limit of the ratio distance:time at any point on the coast?
Comment: @michael your first comment is almost correct, you merely applied the cosine correction in the wrong direction.  Where the beam sweeps at an angle to the shore, it sweeps faster. Divide by the cosine rather than multiply (you have the component, you need to calculate the projection) and you get the book's answer...
Comment: Try editing and fixing it before 5 mins. elapse. Otherwise flag the comment for a moderator and explain the issue.
Comment: You need to think rays instead of particles.  A given angular displacement will produce a larger linear displacement when projected onto a non-tangential surface than it will when projected onto a tangential one.  The angular velocity converted to a tangential velocity is a *component* of the overall velocity, but you need to calculate the *projection* of that component where the shoreline is at an angle to the tangent, so you *divide* by the cosine rather than multiply.  Nothing remotely accidental about this giving the correct answer.  Think about what is is faster, and not slower.
Comment: @ChrisStratton : I have no idea what you are talking about.  If you imagine a particle moving in a circle of radius 4800 about the beacon (at 2 revolutions per minute), its speed in the direction it is going is indeed $19200\pi$, and breaking into components gives a number less than this. This gives the correct answer to the x-coordinate of the particle, but is not the same as the x-coordinate of the light beam (due to changing radius).  Dividing by $cos$ seems unmotivated, it does not seem to be relevant to the envisioned particle.
Comment: Again, stop thinking particles.  Maybe get a flashlight or laser pointer and go stand some distance from a long wall, and look at the linear displacement of the spot along the wall compared to the angular displacement at you, for various points along the wall.  Or for that matter, draw some triangles - first a right one, then adjoining it a skew one with the same angle.
Comment: @ChrisStratton : Sorry I cannot seem to fix the editing issue:  The "delete" sign is overlapping side links on the page and trying to click "delete" just takes me to that link.  I think we are talking past each other.  I suspect you would agree with my comments about my particle. You are likely talking about some other particle, or about just solvign the problem via $x(t)$.
Comment: No "particle" is involved in this **ray** problem, and you are unlikely to understand the situation until you drop that flawed analogy!
Comment: @ChrisStratton : To me, Jeremy's answer was clearly imagining such a particle moving in a circle of radius 4800.  Do you not agree?  And of course he then calculated the overall speed in the direction of motion. Breaking that into components of course gives smaller numbers.
Comment: No, I do not agree.  Your particle model is both inapplicable, and leads you to the obviously at-odds-with-reality idea that the velocity would be smaller.   30 seconds with a laser pointer or equivalent thought model will reveal the truth: you need to calculate the projection of your component, not the component of a projection, and hence the result will be larger (as indeed the book answer confirms), not smaller.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/31933/discussion-between-michael-and-chris-stratton).
Answer: The position on shore is related to the angle by
$x(t) = d \tan \theta(t)$.

Differentiating gives
$\dot{x}(t) = d { 1\over \cos^2 \theta(t) } \dot{\theta}(t)$.
In all cases $\dot{\theta}(t) = 4 \pi$ $\text{min}^{-1}$, $d=3,600$ $\text{ft}$.
For Part (a), if $\theta(t) = 0$, then we have
$\dot{x}(t) = d \dot{\theta}(t) = 14,400 \pi $ $\text{ft } \text{min}^{-1}$.
For Part (b), we have $\cos \theta(t) = {3600 \over 4800 }= {3 \over 4}$ so
$\dot{x}(t) = d ({ 4 \over 3})^2 \dot{\theta}(t)  = 25,600 \pi$ $\text{ft } \text{min}^{-1}$.
Comment: Thanks for your answer. I chose Rory's answer because it really helped my understand why my answer was wrong, but your walkthrough is much more detailed and helpful than the book's solution. Took me a while to walk through it and make sense of everything, but I did and it was very helpful.
Comment: No explanation needed at all!
Comment: @copper.hat : Thanks for your suggestion on how to fix my formatting problem.  It seems I could neither edit nor delete.  I tried taking your suggestion of flagging for moderator help, but it seems I cannot flag my own comment!  So, can you flag my comment for removal? Either the one that is causing the problem, or my other one that tries to get a moderator to fix the issue? Thanks again!
Comment: @Michael: I flagged your comment when I wrote the above, it seems that a moderator has repaired the MathJax.


In Matlab, what is ~m file?

Question: What does the ' ~ ' sign mean at the end of the file name?

BONUS QUESTION: How can I add files to the git repository without adding those '~' files?
Comment: How do I get the bonus points to answer the bonus question?
Comment: First you answer, then you get my prayers (and upvote) ;)
Answer: That is a backup file, and if I am not mistaken it is actually from unix system and not matlab. On windows the backup files are *.asv. If you close your file the backup should disappear.
If you asking about version control, I would suggest you ignore all backup files by adding a like to .gitignore as follows: *.m~.
Comment: +1. If I can also make a suggestion, go to http://www.gitignore.io for premade templates for `.gitignore` files for different kinds of languages. You can also chain multiple languages together to make one composite `.gitignore` if you are developing in multiple languages.  For MATLAB, these not only include backup files, but any MEX generated backup files, Simulink backup files and so on.  This is what the MATLAB template for a `.gitignore` would generate: https://www.gitignore.io/api/matlab
Comment: @rayryeng I had only added `*~`, and that way you ignore all backups .mex's .cpp and any backup. But you are right for matlab specific one would be with only with `.m~`. Btw this is very useful list of useful [.gitignore](https://github.com/github/gitignore).
Comment: Ah I see. I apologize. Please revert my changes.

In Matlab, what is ~m file?


How can I retrieve the current node ID on a custom route?

Question: I have a new route and the yml file looks like this:
rsvplist.form:
  path: '/rsvplist'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'

From the module root directory, I have src/Form/RSVPForm.php, and inside is where I have the build form function that looks like the following:
public function buildForm(array $form, FormStateInterface $form_state) {
    $node = \Drupal::routeMatch()->getParameter('node');
    $nid = $node->nid->value;

    $form['email'] = [
        '#title' => t('Email Address'),
        '#type' => 'textfield',
        '#size' => 25,
        '#description' => t('We will send updates to the email you provide.'),
        '#required' => TRUE,
    ];

    $form['submit'] = [
        '#type' => 'submit',
        '#value' => t('RSVP'),
    ];

    return $form;
}

When I clear the site cache and refresh the page: mylocal.com/rsvplist, I see the following error:
Notice: Trying to get property 'nid' of non-object

I initially used the following code to get the node
$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->nid->value;

If I change the last piece of code to this:
$nid = $node->id();

I see the following error:
Error: Call to a member function id() on null

How can I get the node id when am on the new route?
Reference here
Answer: Your route doesn't have a parameter called node, so therefore $node is null.
In order to make node available as a parameter you have to be on a route that has node as a parameter.
So to add the node parameter to your route, you can do like this:
rsvplist.form:
  path: '/rsvplist/{node}'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'
    _entity_access: 'node.view'
    node: \d+

And then you can add the $node parameter to your buildForm method, like this:
public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
  // Your form.
}

Since I added node: \d+ to your form, $node is now the loaded entity in the buildForm method.
Comment: No, that's why I say you need to add it if you want to access it. You can't get a route parameter that is not on your route.
Comment: I edited my question and added the reference for my code. The route does not have a node parameter
Comment: Jdrupal is right, without a parameter in the route there is no notion of what node you want. The route represents a uri, which is totally independent of any other uri (for example a node view page). It sounds like you want Drupal to just know what page is currently displayed in the user's browser, but that page doesn't even have to be a Drupal page.
Answer: You can try code
rsvplist.form:
  path: '/rsvplist/{nid}'
  ....

use Drupal\node\NodeInterface;
....
$nid= \Drupal::routeMatch()->getParameter('nid');
$node = Node::load($nid);

Comment: No, you should be using Jdrupal's example and allow the routing system to automatically load the node. The upcasting from nid to Node isn't always trivial (e.g. if you have language translations or node revisions etc.) and by doing it through the routing system like Jdrupal shows you have the most flexibility and power to customize the process.


Azure AD: cannot handle missing claims

Question: I have a legacy Vb.Net WebForms application. It uses Azure AD (for employees) and Azure AD B2C (for customers) for authentication. B2C returns some custom claims, which AD does not return. Here is some code that should retrieve the claims:
  If Request.IsAuthenticated Then

        Dim claims = ClaimsPrincipal.Current.Claims

        Dim name As String = claims?.FirstOrDefault(Function(x) x.Type.Equals("name", StringComparison.OrdinalIgnoreCase))?.Value

        Dim userName As String = claims?.FirstOrDefault(Function(x) x.Type.Equals("emails", StringComparison.OrdinalIgnoreCase))?.Value

        Dim userTypes As String = claims?.FirstOrDefault(Function(x) x.Type.Equals("extension_UserTypes", StringComparison.OrdinalIgnoreCase))?.Value

Here, extension_UserTypes is the custom claim. When a customer logs in, all three claims are retrieved successfully. But when an employee logs in, only the first two claims are retrieved, and the 3rd custom claim throws an exception:

Value cannot be null.
Parameter name: username
at System.Web.Util.SecUtility.CheckParameter(String& param, Boolean checkForNull, Boolean checkIfEmpty, Boolean checkForCommas, Int32 maxSize, String paramName)
at System.Web.Security.SqlRoleProvider.GetRolesForUser(String username)
at System.Web.Security.RolePrincipal.GetRoles()
at System.Web.Security.RoleClaimProvider.<get_Claims>d__4.MoveNext()
at System.Security.Claims.ClaimsIdentity.<get_Claims>d__51.MoveNext()
at System.Security.Claims.ClaimsPrincipal.<get_Claims>d__37.MoveNext()
at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()

The same exception happens if I use ForEach on claims.
How can I deal with this issue? I need to be able at least to check if extension_UserTypes custom claim is there. I tried
Dim exists = claims.Any(Function(c) c.Type = "extension_UserTypes")

but got the same exception.
Answer: Claims retrieval code is fine, the stack trace states the problem already exists during a call to SqlRoleProvider.GetRolesForUser(userName). Locate the dbo.aspnet_Users row the affected record/user and replace the null userName value.
Comment: But it is this line Dim userTypes As String = claims?.FirstOrDefault(Function(x) x.Type.Equals("extension_UserTypes", StringComparison.OrdinalIgnoreCase))?.Value that causes the trouble. Without it no exception happens. And I have no idea what this has to do with some SqlRoleProvider, or what userName it is talking about.
Comment: Yes because it relies on the one signaled in my answer. If you're not using the SqlRoleProvider then remove it from your web.config: https://learn.microsoft.com/en-us/dotnet/api/system.web.security.sqlroleprovider?view=netframework-4.8#examples

Azure AD: cannot handle missing claims


Prove the Fundamental Theorem of Algebra

Question: I was reading the proof for the Fundamental Theorem of Algebra in Ian Stewart's book Galois Theory. The author defines $p(w+h)=p_0+p_1h+p_2h^2+\dots+p_nh^n$ for $h\in\Bbb{C}$, then he lets $h=\varepsilon e^{i\theta}$ for small $\varepsilon>0$. Let $m$ be the smallest integer $\ge1$ from which $p_m\neq0$. Then he claims that "$p(w+\varepsilon e^{i\theta})=p_0+p_m\varepsilon^me^{mi\theta}+O(\varepsilon^{m+1})$, where $O(\varepsilon^{n})$ indicates terms of order $n$ or more in $\varepsilon$, and therefore
$|p(w+\varepsilon e^{i\theta})|^2=|p_0+p_m\varepsilon^me^{mi\theta}|^2+O(\varepsilon^{m+1})$."
My question: why do we have $|p(w+\varepsilon e^{i\theta})|^2=|p_0+p_m\varepsilon^me^{mi\theta}|^2+O(\varepsilon^{m+1})$?
I know little to nothing about complex numbers and complex analysis; but using a theorem without understanding the proof is against my religion. Please help if you can - many thanks in advance!
Answer:
Then he claims that "$p(w+\varepsilon e^{i\theta})=p_0+\color{red}{p_m\varepsilon^{mi\theta}}+O(\varepsilon^{m+1})$

I assume that was meant to be $\,p_m\color{red}{\varepsilon^m}\varepsilon^{mi\theta}\,$ instead. Then:
$$
\begin{align}
\left|p(w+\varepsilon e^{i\theta})\right|^2 &= p(w+\varepsilon e^{i\theta})\,\overline{p(w+\varepsilon e^{i\theta})} \tag{1}
\\ &= \left(p_0+p_m\varepsilon^m\varepsilon^{mi\theta}+O(\varepsilon^{m+1})\right)\,\left(\overline{p_0+p_m\varepsilon^m\varepsilon^{mi\theta}}+O(\varepsilon^{m+1})\right) \tag{2}
\\ &= \left|p_0+p_m\varepsilon^me^{mi\theta}\right|^2+O(\varepsilon^{m+1})\cdot\left(O\left(\varepsilon^0\right)+O\left(\varepsilon^0\right)+O\left(\varepsilon^{m+1}\right)\right) \tag{3}
\\ &= \left|p_0+p_m\varepsilon^me^{mi\theta}\right|^2+O(\varepsilon^{m+1}) \tag{4}
\end{align}
$$
[ EDIT ] $\;$ Step by step:
$\;\;{(1)}\;$ using that $\,|z|^2 = z \,\overline{z}\,$ for all complex $\,z\,$;
$\;\;{(2)}\;$ using that $\,\overline{z_1+z_2}=\overline{z_1}+\overline{z_2}\,$ and $\,\overline {\,O(\varepsilon^k)\,} = O(\varepsilon^k)\,$ for real $\,\varepsilon\,$;
$\;\;{(3)}\;$ using that $\,a + b \cdot \varepsilon^k+\dots = a \color{red}{\cdot \varepsilon^0} + b \cdot \varepsilon^k+\dots=O\left(\varepsilon^0\right)\,$;
$\;\;{(4)}\;$ using that $\,O(n_1)\,\pm\,O(n_2) = O\left(\min (n_1,n_2)\right)\,$ and $\,O(n_1)\,O(n_2) = O(n_1+n_2)\,$.
Comment: @Josh12913 I added a few notes about each step at the end of the answer. The notation $\,O(\varepsilon^k)\,$ describes a function in terms of the powers of $\,\varepsilon\,$. For that purpose $\,p_n\varepsilon^ne^{ni\theta}\,$ is just an $\,n^{th}\,$ power $\,\alpha \,\varepsilon^n\,$ with a coefficient $\,\alpha \in \mathbb C\,$. Since $\,\varepsilon\,$ is real, it follows that $\,\overline {\,\alpha \,\varepsilon^n\,}= \overline\alpha\, \varepsilon^n = O(\varepsilon^n)\,$.
Comment: @Josh12913 Glad it helped. And you are right, there is only so much that can be covered here, and Q&As cannot replace a good textbook for establishing the foundations.
Comment: Thank you so much for the help! And you are correct-I have fixed the typo. Still, it seems that I lack quite a bit of foundational knowledge required to understand the machinery at work here. I am not quite sure why $O(\varepsilon^{m+1})$ remains unchanged when taking the conjugate: doesn't $O(\varepsilon^{m+1})$ also contain terms such as $p_n\varepsilon^n e^{ni\theta}$ for some $n>m$?
Comment: I couldn't thank you enough; but it seems like I must build a deeper foundation in the complex numbers before I could fully comprehend this proof.


How to provide a default error page if Flask app is not available in Google App Engine

Question: How to provide a default error page if Flask app is not available in Google App Engine. I see the following error if the app is not available and when its being deployed, how do I provide a more user friendly message.
Error: Not Found
The requested URL / was not found on this server.
Answer: You can't: if the application is not available neither is its config, where custom error pages would be configured.
To avoid such errors it's better to always deploy a new app version and gradually switch traffic to it after it's verified to be working.
Related:

Continuous integration/deployment/delivery on Google App Engine, too risky?
What's the recommended way to stop the current version of app engine using gcloud?


Can I use "return" in here or any ideas?

Question: I'm really new to Java and most of my knowledge are self- taught. can you help me to figure out this.
Our teacher wants us to make a menu about Java. Where the output something like this..
Menu
1 - Java History
2- Java Keywords
3 - Java Arrays and so on. .
Do you want to read one (Yes/No):
//if yes
Please enter a menu number:
// then it will display an information..
//my problem is that how can I connect the new entered value to the first method so that I don't have write it all over again...
this is whats on my mind..
but im stuck..
import java.util.Scanner;

public class Program {

public static void main (String [] args) {

System.out.println("Please enter a number:");
int x = nextInt();

if (x == 1) {

     for (int x = 5; x == 5;x++) // array of 1(first menu)

System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")

// return to if with it's new entered value....

     }
    else if (x == 2)  {
    for loop of array 2

    System.out.println ("Do you want to read another? (Yes/No):");
    System.out.println ("Please enter a menu number:")

    // return to if with it's new entered value....

}

else if (x == 3) {
    for loop of array 3

    System.out.println ("Do you want to read another? (Yes/No):");
    System.out.println ("Please enter a menu number:")

    // return to if with it's new entered value....

else if (x ==4) {
    for loop of array 4

else if (x == 5) {
    for loop of array 5

else if (x == 6) {
    for loop of array 6

else if (x == 7) {
    for loop of array 7

else if (x == 8) {
    for loop of array 8

else if (x == 9) {
    for loop of array 9

else if (x == 10) {
    for loop of array 10

 else {
   //exit the program

Comment: you need a while loop?
Answer: If I understand correctly, you would want to implement the While or do while statement in your program.
Example of While and Do While Loops
Im not really sure what you are trying to accomplish with your program but here is a little example I made quickly of how to utilize the for loop in your case. `import java.util.Scanner;
public class main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        boolean keepGoing = true; //As long as this is true the while statement will continue;
        while (keepGoing) {
            System.out.println("Enter a number");
            int x = scan.nextInt();

            //logic
            if (x == 1) {
                System.out.println("X is equal to 1");
            } else if (x == 2)
                System.out.println("X is equal to 2");

            //prompts the user if they want to keep going.
            System.out.println("Would you like to keep going? Y/N");

            String decision = scan.next();
            if (decision.equalsIgnoreCase("y")) {
                keepGoing = true;
            } else {
                System.out.println("Quitting...");
                keepGoing = false;

            }
        }
    }
}
`

Comment: Yes but I don't exactly know how to do it in a way if it ask the user to enter a new value then that new value will be process again.
Comment: This code does that. It will keep prompting a user to enter a new number to be processed until he/she decides to quit. This is the work of the While loop in action.
Comment: Yeah it worked!!! Thank you very much!! It's a great help.. I finished my codes.. Show it to you next time. I'll put you in my acknowledgements if it's ok with you..


How to change the cell value for entire datagridview column?

Question: I'd like for the datagridview column to check all, or check none. The code below works, but is there an easier/faster way of doing this? For setting the value for all the cells in a column?
if(searchResultsGrid.Columns["checkboxColumn"].HeaderText == "CheckAll")
{
    searchResultsGrid.Columns["checkboxColumn"].HeaderText = "UncheckAll";
    foreach (DataGridViewRow row in searchResultsGrid.Rows)
    {
        row.Cells["checkboxColumn"].Value = true;
        searchResultsGrid.UpdateCellValue(0, row.Index);
    }
}
else
{
    searchResultsGrid.Columns["checkboxColumn"].HeaderText = "CheckAll";
    foreach (DataGridViewRow row in searchResultsGrid.Rows)
    {
        row.Cells["checkboxColumn"].Value = false;
        searchResultsGrid.UpdateCellValue(0, row.Index);
    }
}

Comment: Not really, you do have to loop.
Answer: You could achieve this another way through some trickery. The column must be ReadOnly and the cell values Null. Clicking any cell in the column will toggle the default NullValue of the column; essentially toggling every cell.
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn(false);
chk.HeaderText = "CheckAll";
chk.Name = "checkboxColumn";
chk.ReadOnly = true;
this.dataGridView1.Columns.Add(chk);

this.dataGridView1.CellClick += DataGridView1_ToggleAll;

private void DataGridView1_ToggleAll(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCheckBoxColumn col = this.dataGridView1.Columns[e.ColumnIndex] as DataGridViewCheckBoxColumn;

    if (col?.Name == "checkboxColumn")
    {
        bool checkAll = (bool)col.DefaultCellStyle.NullValue;
        col.HeaderText = checkAll ? "CheckAll" : "UncheckAll";
        col.DefaultCellStyle.NullValue = !checkAll;
    }
}

But note: to get the checked state you'd use cell.EditedFormattedValue and not cell.Value. (Because Value of necessity would always be null for this trick to work.)

This has a creative touch to it, but you must also think about future developers. When you decide to optimize code, you must ask how it will affect maintenance. Loops are easily understood and still execute quickly. You have to weigh the worth.
Below are snippets from my findings in 100 runs each with 10,000 rows of data. These were the run times of toggling the rows:
Standard Looping
Elapsed = 00:00:00.0315538
Elapsed = 00:00:00.0107964
Elapsed = 00:00:00.0676696
Elapsed = 00:00:00.0232370
Elapsed = 00:00:00.0243285

NullValue Toggling
Elapsed = 00:00:00.0006645
Elapsed = 00:00:00.0006712
Elapsed = 00:00:00.0006804
Elapsed = 00:00:00.0007579
Elapsed = 00:00:00.0003037

Note: NullValue toggling speed was consistent despite number of rows. For small data (1000 rows), looping was 2/3rd's faster than the NullValue method.
Comment: To be fair on the speed, my test rows only had 3 columns of simple data. Only doing this on the header cell would be easy, but it's true, this won't work for your purposes if the cell values are allowed to change from `Null`. We *might* be able to work out a solution from this point, but it would be too obscure for maintenance purposes.
Comment: Thanks for the suggestion, but this was only an added feature; meaning that the user may opt to click each cell, or just click the header to select all. Impressive time data you have. For ~800 rows, the current process takes about 45 seconds.


What is the best way to determine if a window is actually visible in WPF

Question: I'm trying to toggle the display of a small window based on the click of a notify icon in a system tray app. This is simple enough to implement, however when the small window is displayed and another application takes focus and therefore moves in front of it (z-order) I want the toggle to assume that the small window is now hidden, even though it's visibility is still set to visible. Otherwise, clicking the icon would set the windows visiblity to hidden even though it is already hidden behind another. I've tried catching / overriding the activate and deactive methods to keep track but clicking the notify icon will always cause the deactive event to fire first. A similar approach using focus / lost focus didn't work either as the window seemed to think it still had focus even when hidden behind another applications window in active use. In the end I had to resort to native code and the WindowFromPoint method as follows:
<code>using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Drawing;

[DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(Point lpPoint);

public static bool IsWindowVisible(System.Windows.Window window) {
    WindowInteropHelper win = new WindowInteropHelper(window);
    int x = (int)(window.Left + (window.Width / 2));
    int y = (int)(window.Top + (window.Height / 2));
    Point p = new Point(x, y);
    return (win.Handle == WindowFromPoint(p));
}
</code>
This checks if the window returned at the coordinates of the centre of the window in question matches said window. i.e. the centre of the window in question is visible.
This seems a little hacky, is there a nicer way to achieve the same result?
Comment: 1. I'm with Joon. Nice solution.
2. One may want to query more than just the center (e.g. window corners).
3. Careful not to use `System.Windows.Point` or you get some ugly exception
Comment: +1 for a very interesting question. I could not find a better way so I used your approach :-)
Answer: You may not want to rely on whether a window is obstructed as there are many factors that can change the window size, positing, etc. and all of them tie into accessibility features which add even more complexities.
Instead, you may want to check whether or not the window has focus.  This is how MSN Messenger knows whether or not to flash orange in the taskbar; it fires a notification and if it doesn't have focus, the taskbar flashes.
Comment: I found that when I checked the focus property of the window, it would return that it had focus even though it was behing another window. I then tried the activate and deactive events, which worked, but deactivate would fire when I clicked the toggle sys tray icon, even though the window was visible


jquery code is not working when added data-input mask attribute in the inputbox

Question: <code>$('#dynamic_field2').append('<input type="text" class="form-control pull-right datepicker"   data-inputmask="'alias': 'date'" name="reg_bdate" data-mask placeholder="Birth Date">');
</code>
when the button was clicked this should append in the dynamic_field2 div but it give's me this error

and I can't figure out how to fix this thank you.
Comment: I've formatted the code in the question properly, which nicely highlights your quoting error.
Comment: Check your quotes (hence the red border)
Comment: You have mis-matched quotes in the string you're appending. Voting to close as a typo.
Answer:
<code>$('#dynamic_field2').append('<input type="text" class="form-control pull-right datepicker"   data-inputmask="'alias':'date'" name="reg_bdate" data-mask placeholder="Birth Date">');
</code>

Your quotation marks are either not escaped or you are trying to insert variables

Correct quotation marks:
<code>$('#dynamic_field2').append('<input type="text" class="form-control pull-right datepicker"   data-inputmask="\'alias\':\'date\'" name="reg_bdate" data-mask placeholder="Birth Date">');
</code>

Variables:
<code>$('#dynamic_field2').append('<input type="text" class="form-control pull-right datepicker"   data-inputmask="'+ alias +':'+ date +'" name="reg_bdate" data-mask placeholder="Birth Date">');
</code>


Salvar excel automaticamente gerado na aplicação ASP MVC

Question: Estou a gerar ficheiros Excel na minha aplicação usando o EPPlus. Surgiu agora a necessidade de guardar automaticamente estes ficheiros numa pasta, independentemente de o utilizador fazer download ou não do mesmo, para poder assim fazer um histórico destes ficheiros gerados.
No meu código tenho:
public ActionResult ExportToExcel(string serie, int numDoc, int servicoID, int agrupamento)
        {
            ARTSOFT.dal.ViewModels.GetDadosComerciais dbArt = new ARTSOFT.dal.ViewModels.GetDadosComerciais();

            var contratoPai = db.DadosComerciais.Where(d => d.Serie == serie && d.NumDoc == numDoc).FirstOrDefault();
            var servicoPai = db.Servicos.Find(servicoID);

            using (var package = new ExcelPackage())
            {
                package.Workbook.Worksheets.Add("Test");
                ExcelWorksheet ws = package.Workbook.Worksheets[1];
                ws.Name = "Folha1"; //Setting Sheet's name
                ws.Cells.Style.Font.Size = 10; //Default font size for whole sheet
                ws.Cells.Style.Font.Name = "Calibri"; //Default Font name for whole sheet

                //Merging cells and create a center heading for out table
                ws.Cells[1, 1].Value = "Relatório - Cópia de Contratos"; // Heading Name
                ws.Cells[1, 1, 1, 10].Merge = true; //Merge columns start and end range
                ws.Cells[1, 1, 1, 10].Style.Font.Bold = true; //Font should be bold
                ws.Cells[1, 1, 1, 10].Style.Font.Size = 13;
                Color colFromHex = System.Drawing.ColorTranslator.FromHtml("#D1F5C6");
                ws.Cells["A1:J1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                ws.Cells["A1:J1"].Style.Fill.BackgroundColor.SetColor(colFromHex);
                ws.Cells[1, 1, 1, 10].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; // Aligmnet is center

                #region Dados contrato Pai

                #region lista de contratos copiados

                var memoryStream = package.GetAsByteArray();
                var fileName = string.Format("CopiaContrato_" + serie + "_" + numDoc + "-{0:yyyy-MM-dd-HHmmss}.xlsx", DateTime.UtcNow);
                // mimetype from http://stackoverflow.com/questions/4212861/what-is-a-correct-mime-type-for-docx-pptx-etc

                return base.File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
        }

O resultado final da função é permitir ao utilizador fazer download do ficheiro gerado. O que estou a tentar fazer agora? Salvar o ficheiro automaticamente numa directoria antes de dar return da função. Para tal estou a fazer:
HttpPostedFileBase filepath = (HttpPostedFileBase)Request.Files[0];
var fileName2 = Path.GetFileName(fileName);
var path = Path.Combine((ConfigurationManager.AppSettings["pathFiles"]), fileName);//ir buscar ao xml
filepath.SaveAs(path);

Este código acima é o que uso para guardar ficheiros (imagens, documentos, etc) carregados pelo utilizador (por exemplo numa input type="file"), tentei fazer o mesmo para gravar o Excel mas não está a resultar.
Answer: Já tenho a solução. Para guardar automaticamente o Excel gerado na aplicação basta fazer:
System.IO.File.WriteAllBytes(@"D:\Report.xlsx", memoryStream);//Guardar ficheiro automaticamente


How to quickly collect data (survey) from students in class?

Question: What would be an easy and simple way to get online responses from students in class for use in class demonstrations.  E.g. Height and Weight. A quick survey method in a computer class could make lab work more interesting. Any ideas? Thank you for reading.
Answer: If all students have access to the Internet, they could easily fill out a spreadsheet in a public drive. Google Drive would work well. Simply create a spreadsheet in Google Drive (similar to Excel), make it public, and share the link to your students. They could then easily fill in their information all at once (i.e., multiple people can use the form at same time and in real time). You could then easily do statistics in that spreadsheet program, or export it for more advanced statistics (e.g., in Excel or SPSS).


Chords with different bass and non-diatonic chords inside a progression

Question: I'm studying music by myself and I'm dealing with several doubts: one of these is, are there some criteria for using a chord with a different bass in a chord progression? And how should I use it? Also, are there some specific ways to use non-diatonic chords inside a progression? I was analyzing yesterday this song by Bruno Mars, which I really like (D Major key), where you can find for example both Gmaj7 and Gm chords, and the second one of course is not constructed in the key of D major. I just want to understand a bit better the whole thing!
You cand find the sheet music here:
Bruno Mars - Versace on the floor
https://musescore.com/user/16069731/scores/3461536
Thank you in advance!
Comment: Hello, You ask two different questions here. It's better to edit out your second question about non-diatonic chords and ask it seperately.
Answer: You're not going to understand music by working outward from 'the rules' I'm afraid!   But you're doing the right thing, you're observing some real-world music that goes beyond simple diatonicism.  (And, believe me, even popular music - let alone the heavy stuff at Symphony Hall -  goes WAY beyond it all the time!)
The key, the home scale of a tune and the chords that can be made from those notes, are a framework.  Not a restriction.  You've discovered that both IV  (G chord in the key of D) and iv (G minor chord in the key of D) sound good.  So do a whole lot of other chords.  In fact, it would be trivial to demonstrate how just about ANY chord could fit well into a sequence in D major!
I'll just offer one 'rule'.  Don't think of chords as entities. 'In key x, we can use chords x,y,z...' Look at the NOTES in a chord.   We're in D major.  We know G major is a basic diatonic possibility.   Perhaps the next chord is A major.  Now, rather than taking the B in G major directly to the A in A major, what more natural than to let it slip down half-way first, to Bb!  That's why the mini-progression D, G, Gm, A sounds so natural.
Comment: ahah thank you for you answer! The fact is that I'm just feeling a bit 'lost' because of all these possibilities, and so I was asking for a clean way to run across.. :)
Answer: Trying to answer the first part of your question. I imagine you mean 'slash chords'. Chords which have two letter names. The first is the chord name itself, the second the lowest note played. This can be one of the chord notes itself, or another note altogether.
Let's take the former. Sometimes it's not the root position that's needed. With C major - C E G - if a 1st inversion is needed, it's shown by C/E.
The latter is a bit more complex, as the note after the slash doesn't necessarily belong to the chord. Like in this sequence: C, C/B, C/Bb, F/A. It could be said that the 2nd chord is Cmaj7, 3rd C7. But what's important is the bass line, which is chromatic. Those chords could be played just as 4/3 note chords, but the chromatic bass line would possibly be lost doing that.
The other way is something like C/D, a sort of 'CaddD', except here, the D is under not above the chord.
Moving on to the other part: Laurence has it pretty well covered, I'm just adding that it's been found (therefore belongs to theory) that another whole set of non-diatonic chords work well. It's from the parallel key. In your case, D is the key, so Dm is the parallel. That explains to a degree where the Gm pops up from.


Importing time sliced samples into Electribe Sampler

Question: The editing of time slices of samples on the Korg Electribe is a real pain.
Is there a way to export my own time sliced samples from my DAW to the Electribe?
Answer: The executive summary of this is:

Time slice your sample in your DAW (in Reaper it's Dynamic Split) so that there are 8 or 16 slices for your sample.
Save each slice. Choose a name and a cardinal number to keep track of where each slice is in the overall sample. For example: Sample-01.wav, Sample-02.wav,...
Import each sample into the Electribe.
Create a new pattern in the Electribe
Assign the slices to pads in the pattern.
Write the pattern


Understanding proportion of variance in PCA

Question: One of my exam question was as follows:

Assume the covariance matrix of your dataset $X $ is $\Sigma$ and while doing Principal Component Analysis, you found  $\Sigma =  CDC^T $. Here $D $ is the following diagonal matrix:
$$\begin{bmatrix}3 & 0 & 0 & 0 \\0 & 2.1 & 0 & 0 \\0 & 0 & 1.4 & 0 \\0 & 0 & 0 & .9 \\\end{bmatrix}$$
Then the proportion of variance (POV) is explained by the first 2 principal components would be (accurate until 2 decimal places):

A) .85
B) .68
C) .31
D) 1
E) None of the above answer are correct

I know for a fact that E) is the correct answer. However, in my calculations i seem to get B) as the correct answer, calculating it as $(3 + 2.1) / (3 + 2.1 + 1.4 + 0.9) = 0.689... $
What am I missing?
Answer: Proportion of explained variance by the first $k$ components in PCA is equal to $$R^2=\frac{\sum_{i=1}^k\lambda_i}{\sum\lambda_i},$$ which in your case gives $0.689...$ as you correctly computed. However, when rounded up to two decimal places (as explicitly specified in the question), it becomes $0.69$ and not $0.68$. This is perhaps why (E), and not (B), is supposed to be the correct answer.
I must add that if so, this is a truly moronic exam question.


Continuity of a restriction operator

Question: Let $\Omega$ be a domain of $R^n, \; n\ge 1.$
I am wondering about the existence of an open subset $\omega$  of $\Omega$ such that
$$
\|y\|_{L^\infty(\omega)} \le C \|y\|_{H^2(\Omega)},\; \forall  y\in H^2(\Omega)
$$
for some constant $C>0?$
In the case $n=1,$ the response is yes with $\omega=\Omega.$ For $n\ge 2$, the inequality is not true for $\omega=\Omega.$
Thanks!
Answer: This would imply that there is an open subset $\omega \subset \Omega$ such that all $u \in H^2(\Omega)$ are bounded on $\omega$. That's not correct for $n \ge 2$. You can find $u_0 \in H^2(D)$ where $D$ is the unit ball such that $\inf_{|x| < \epsilon} u_0(x) \to \infty$ as $\epsilon \downarrow 0$, that is, $u_0(0) = \infty$. You can then move this singular behavior to any point in $\Omega$ by shifting and rescaling $u_0$.

Continuity of a restriction operator


More than one pager in the same page

Question: I have a Page that contains two views one that list the latest news and the other list the latest event
The problem now is that each view has a pager but when I change the page of one of them both view will change.
i.e If I want to see page number 3 in news view,the event view will also change to page number 3
Is there is a way to make that even programmatically
also I don't want to make it ajax because I need to share the url
Thanks
Answer: In Pager options There is a field named Pager ID. Setting a different value for each view should solve the problem.
Comment: Do you know how to set Pager ID to a different value it make a lot of error when change the default value
Comment: What errors?...
Comment: I change the 0 value to be 1 "Notice: Undefined index: 1 in theme_pager() (line 331 of /includes\pager.inc)."
Comment: I have replaced value '0' with '1'(any value). This resolved my issue
Answer: Make View Results Ajaxified.. Enable the AJAX Feature in the view settings. You can do this by editing the view and make the Use AJAX setting under Other settings in the view to YES.
With out using AJAX you can solve this using the Pager ID setting in the pager settings. For first view leave the Pager ID to default 0. For the second view in the same page, edit the view and set the pager ID to 1. Make sure all the views in a single page have different pager ID's.
Comment: is there is any other solutions for that I don't know to make it ajax :) because I need to change url to share the link
Comment: @Ahmed You should simply enable Ajax under the view setting, and it is Ajax. You don't have to know any other thing.
Answer: You have a very tutorial on nodeone.se about what you want to achieve.
But it's almost the same answer than H.NiK...Only difference,he only changed the id pager of one view (the block not the page)
Maybe this video will be helpful.

More than one pager in the same page


Identifying the quotient $\mathbb{R}[x]/(x^3+x)$ with a standard ring.

Question: The question is in the title. By the first isomorphism theorem, I know that if I can find a surjective ring homomorphism $\varphi : \mathbb{R}[x] \rightarrow S$, where $S$ is some standard ring, and ker$(\varphi) = (x^3 +x)$, then I am set.
So I chose $\varphi : \mathbb{R}[x]\rightarrow\mathbb{R}$, where $\varphi (p(x)) = p(0)$ for some $p(x)\in\mathbb{R}[x]$. However, I don't think this map satisfies my kernel requirement.
My question is how can I adjust my mapping to account for ker$(\varphi) = (x^3 +x)$?
Thank you! ~Dom
Answer: Hint: you should use the Chinese remainder theorem for $\def\Kx{K[x]}\Kx$ here ($K$ a field): just like for $\Bbb Z$ one has $\def\Z{\Bbb Z}\Z/n\Z\simeq (\Z/a\Z)\times(\Z/b\Z)$ when $n=ab$ is a decomposition of $n$ into a product of relatively prime numbers $a,b$, one has $\Kx/(P)\simeq(\Kx/(A))\times(\Kx/(B))$ when $P=AB$ is a decomposition of $P$ into a product of relatively prime polynomials $A,B$.
Answer: $\rm h : \Bbb R[x]\to \Bbb R \times \Bbb C\:$ via $\rm\: f(x)\mapsto (f(0),f({\it i}\,))\,$ is onto: $\rm\:a\!+\!(a\!-\!b)x^2\mapsto (a,b).\:$ So $\rm\,Im\ h = \Bbb R \times \Bbb C.\,$ Next, $\rm\:f\in ker\ h\!\iff\!x,\,x^2\!+1\mid f\!\iff\!lcm(x,x^2\!+1) = x^3\!+x\mid f,\:$ thus $\rm\:ker\ h = (x^3+x).\:$ Applying the First Isomorphism Theorem $\rm\:R[x]/(ker\ h) \cong\, Im\ h,\:$ i.e. $\rm\:R[x]/(x^3\!+x)\cong \Bbb R \times \Bbb C$.
Remark $\ $ Weierstrass (1884) and Dedekind (1885) showed that every finite dimensional commutative extension ring of $\mathbb R$  without nilpotents $\rm (x^n = 0 \ \Rightarrow\ x = 0)$ is isomorphic as a ring to a direct sum of copies of $\rm\:\mathbb R\:$ and $\rm\:\mathbb C\:.\:$
Wedderburn and Artin proved a generalization that every finite-dimensional associative algebra without nilpotent elements over a field $\rm\:F\:$ is a finite direct sum of fields.
See this answer for much more on this and related matters.
Answer: Since $\gcd(x,x^2+1)=1$, then by the Chinese remainder theorem
we have
$$\mathbb{R}[x]/(x^3+x)\simeq\mathbb{R}[x]/x\times \mathbb{R}[x]/(x^2+1).$$
Moreover, we have
$$\mathbb{R}[x]/x\simeq \mathbb{R},$$
and
$$\mathbb{R}[x]/(x^2+1)\simeq\mathbb{C}\simeq\mathbb{R}^2,$$
so, we finally find
$$\mathbb{R}[x]/(x^3+x)\simeq\mathbb{R}\times \mathbb{C}\simeq\mathbb{R}^3.$$
Comment: Are you sure that $\mathbb C\simeq\mathbb R^2$?
Comment: Nice try! Nobody can think of $\mathbb R^2$ with this multiplication, and even less (if possible to say so) to $\mathbb R^3$ as being $\mathbb R\times\mathbb R^2$ where $\mathbb R$ is taken with the usual multiplication and $\mathbb R^2$ with that one which gives an isomorphism with $\mathbb C$.
Comment: @YACP If we define the multiplication in $\mathbb{R}^2$ by
$$(a,b)\times(a',b')=(aa'-bb',ab'+a'b),$$
then we can find a ring isomorphism. Is not it?


Show that $n^4+4$ is a composite number

Question:
Show that if $n>1$, then the number $z=n^4+4$ is a composite number.

I only tried to analyze the parity of the number $n$: if $n$ is even then $z$ is even; if $n$ is odd then $z$ is odd.
But the second part didn't help me much, how can I proceed?
More generally, for which values of $k$ is the number $n^k+k$ composite?
Comment: $x^4 + 4 = (x^2-2x+2)(x^2+2x+2)$, a special case of  [Sophie Germain's identity](https://www.cut-the-knot.org/blue/SophieGermainIdentity.shtml)
Comment: Do you mean "composite", i.e. not prime?
Answer: Observe that
\begin{align}
x^4+4=(x^2-2x+2)(x^2+2x+2).
\end{align}
Answer: For the $k=4$ case, one can simply note that
$$n^4 + 4 = (n^2 - 2n + 2)(n^2 + 2n + 2)$$
The motivation is realizing that you have something that looks like it could factor as two factors of $n^2 + ?n + 2$, since $(n^2)^2 = n^4$ and $2^2 = 4$, and trying to determine what that unknown quantity is. One observes that, letting that quantity be variables $b,c$ in two factors, that
$$(n^2 + bn + 2)(n^2 + cn + 2) = n^4 + n^3 (b+c) + n^2 (bc + 4) + n(2b+2c) + 4$$
So one requires that
$$\begin{cases}
b+c = 0 \\
bc + 4 = 0 \\
2b + 2c = 0
\end{cases}$$
though the latter equation is redundant. So you end up having two numbers whose sum is zero, and whose product is $-4$. Some trial and error readily let's one see that $b = -2$ and $c=2$. (Or I suppose you could try substitution or another method.)

That said, I'm not really sure about generalizations on the $n^k + k$ case.

Obviously $k=1$ is a dud. Take $n=6$. ($7$ is prime.)
In the case $k=2$, take $n=3$. ($11$ is prime.)
In the case $k=3$, take $n=2$. ($11$ is prime.)
In the case $k=5$, take $n=2$. ($37$ is prime.)
In the case $k=6$, not sure. (Nothing sticks out as one to me with small cases.)
In the case $k=7$, take $n=4$. ($16,391$ is prime.)
In the case $k=8$, take $n=3$. ($6,569$ is prime.)
In the case $k=9$, take $n=2$. ($521$ is prime.)
In the case $k=10$, not sure. (Nothing sticks out as one to me with small cases.)

So I know it's true for $k=4$, and maybe $6$ and $10$, but I'm not sure.
Not really up for trying more cases, but I'm not sure of a pattern offhand.
Comment: c.f. https://oeis.org/A303121
Comment: and https://oeis.org/A097792
Comment: Well, yes, but you seem to want $n > 1$ based on what you said in the OP.
Comment: Thanks!! For $k=6$ you have $n=1$ right?
Comment: True, I forgot that detail
Comment: That's great! Thanks!
Answer: Hint
$$z=n^4+4=n^4+4n^2+4-4n^2$$
is the difference of two squares.
Answer: Consider $k=27$ or $k=64$. Then $n^k+k$ is composite for all $n\ge 1$. Indeed,
$n^{27}+27= (n^9)^3+3^3= (n^9+3)\cdot(n^{18}-3n^9+9)$
$n^{64}+64= n^{64}+16n^{32}+64-16n^{32}=(n^{32}+8)^2-(4n^{16})^2=(n^{32}-4n^{16}+8)\cdot(n^{32}+4n^{16}+8)$
In general, if $k= m^m$ with $m\ge 3$, odd then $n^k+k$ is composite for all $n\ge 1$.

Show that $n^4+4$ is a composite number


"site map" module and I would like to add the following jQuery line so that the /sitemap page is formatted

Question: I am using "site map" module and I would like to add the following jQuery line so that the /sitemap page is formatted:
$('#mydiv').columnize({ width: 200 , columns: 3 });

The /sitemap page is not trapped within either hook_form_alter or hook_page_alter so how could I add this JQuery line?
Answer: The site_map module has a theme template implementation in the root folder of the module:

site-map.tpl.php

Easiest and most sustainable way to add this would be to copy this file to your theme templates folder, add your javascript in there and flush caches.
Other quick ways:

Create a block and add your javascript in there then place this in a region on the path '/sitemap'
Create your own preprocess_page module that adds this javascript if the path is /sitemap
Comment: so after copying the site-map.tpl.php file to my theme templates folder then an example of adding would be like the following correct?
Comment: no - you would be better of adding it inline, using just html & script tags. you shouldn't modify the headers in a template file, if you want to do that add a preprocess_page function.


Change Stack size in Contiki

Question: Is there a way to programmatically change the stack size in Contiki?
I know on Linux systems I'm able to call:
ulimit -s SIZE

But I'm currently using Contiki as a flashed binary, and don't really have access to a traditional terminal. I've tried executing the command from C using system() and popen() calls to no avail.
Perhaps there's a CFLAG or LDFLAG I can leverage? Or modifying something in the makefile?
FYI I'm flashing the binary to a Texas Instruments cc2650, which has a 32 bit processor.
Answer: CC2650 does not have a MPU (Memory Protection Unit), which implies that no one checks for the boundaries of the stack region during runtime, which in turn implies that there is no way to "reserve" stack in the same sense that stack memory is reserved on Linux.
Essentially, if you keep allocating new things on stack, the stack will keep to grow even after it reaches other memory regions - usually the .data region, which contains dynamically allocated memory, if any, and static/global variables. The growth of stack will corrupt the memory in those other regions in a way that you might even fail to notice, leading to hard-to-find bugs.
There are a couple of things to do. One is to reserve bigger stack memory during compile time. This will not limit the stack region, but will limit the extent of the data region. To do that, change the CC2650 linker script in cpu/cc26xx-cc13xx/cc26xx.ld:
_Min_Stack_Size = 0x100;  /* 256 bytes by default for the stack */

The other thing is to use Contiki-NG recent revisions, which have built-in stackoverflow checks. There is still no way to change the stack region size during runtime, but you will get an error if stack overflow happens.
Comment: Thanks for your answer!

Unfortunately, I don't have to luxury of switching to Contiki-NG at this time. Is there a way to catch a stack overflow on Contiki 3.x, at least to throw a hard error?

Change Stack size in Contiki


Get the select list current value not key

Question: For example, There is a field with 3 options in allowed values, like option1, option2, option3.Is there any function which receive the field name and returns selected values not a keys ?
With this just return key of selected opinion
  print ($node->field_opinion['und'][0]['value'])

Update :
I have create select list field and with this field user can answer and select own value like this
1|Stars
2|Nights
3|Awesome
4|Days

With above code just return the keys field and i want to return values like "Stars"
Comment: Can you please provide us more information?
Comment: @Jeetendra Kumar UPDATE my friend !
Answer: Try this code:

$key = $node->field_opinion['und'][0]['value'];
$label = list_allowed_values(field_info_field('field_opinion'))[$key];

Comment: Can i use that for checkbox forms ?
Answer: You need the field_info_field() and list_allowed_values() functions to get an array representation of the values you entered in the field's configuration.
The following:
$field_opinion_info = field_info_field('field_opinion');
$opinion_values= list_allowed_values($field_opinion_info);

should give you access to an array that looks like this stored in $opinion_values:
Array
(
    [1] => Stars
    [2] => Nights
    [3] => Awesome
    [4] => Days
)

And from that, you can get the needed value like this:
$selected_option = $node->field_opinion[LANGUAGE_NONE][0]['value'];
$selected_value = isset($opinion_values[$selected_option]) ?
  field_filter_xss($opinion_values[$selected_option]) :
 t('Not a valid option');

Note the use of field_filter_xss(); according to the documentation of list_allowed_values():

The strings are not safe for output. Keys and values of the array should be sanitized through field_filter_xss() before being displayed.

Hope this helps!
Comment: Thanks @Stefanos Petrakis but result Must have selected value, your code return all value !
Comment: @BijanZand That is also described in the answer, look for the `$selected_value` variable in my code example. And pay attention to the use of `field_filter_xss` function.


"Identical" power series

Question: This is a question that came to my mind as I was reading about power series. Is it possible for two power series to, in some sense, represent the same function, and thus be "identical"? So the definition would go like:

The power series $f(z)=a_0+a_1z+a_2z^2+\ldots$ and $g(z)=b_0+b_1z+b_2z^2+\ldots$ are identical if $f(z)=g(z)$ for all values of $z$ such that $f(z)$ and $g(z)$ converge.

With this definition, if $f(z)$ or $g(z)$ has radius of convergence $0$ and $a_0=b_0$, then they are identical. What if the radius of convergence $R_f$ and $R_g$ are both positive? Does that guarantee that $a_i=b_i$ for all $i\geq 0$?
Answer: Good question! Yes, it does guarantee that $a_i = b_i$. The way to see this is to note that if two functions are the same, then they have the same derivative, the same 2nd derivative, etc. And the derivative of a power series
$$f(x) = a_0 + a_1x + \dotsb$$
is always $f'(0) = a_1$, and the second derivative is always $2a_2$, etc.
Here we've taken the power series to be centered at zero, but the same applies if it is centered somewhere else.
Note that the condition $R_f, R_g>0$ is used in claiming that $f'(0) = a_1$, because if $R_f \not > 0$, there is no derivative for such a function, since it is not defined in an open set. Once we have convergence in $(-r,r)$ for $r>0$, we know that $f$ converges uniformly on compact subsets of $(-r,r)$, and so we can take the derivative term-by-term on $(-r,r)$.
Note as a simple counter-example that $$f(x) = 1 + 2x + 2^2x^2 + 3^3x^3 + \dotsb$$ and $$g(x) = 1 + 3x + 2^2x^2 + 3^3x^3 + \dotsb$$ agree everywhere where they converge, though they are not identical.
Comment: Hmm... where is the condition that $R_f,R_g>0$ being used here? Because if $\min\{R_f,R_g\}=0$, then it is not necessary that $a_i=b_i$ for $i>0$ (as I mentioned in the post).
Comment: I added a bit more.
Comment: Thank you for your answer, Eric! I missed the point that the derivative wouldn't exist if $R_f=0$ (or $R_g=0$).
Comment: You're very welcome.

"Identical" power series


Moved mySQL to an EBS volume, now innoDB performs very slowly

Question: Hello has anyone had a similar problem to this.. I've set up a new instance on Amazon EC2 for a client.  I've also attached a 250GB EBS volume to hold the files and configured mySQL to use the EBS volume.
Following http://aws.amazon.com/articles/1663?_encoding=UTF8&jiveRedirect=1 - everything was set up fine -

sudo mkdir /vol/etc /vol/lib /vol/log
sudo mv /etc/mysql     /vol/etc/
sudo mv /var/lib/mysql /vol/lib/
sudo mv /var/log/mysql /vol/log/

sudo mkdir /etc/mysql
sudo mkdir /var/lib/mysql
sudo mkdir /var/log/mysql

echo "/vol/etc/mysql /etc/mysql     none bind" | sudo tee -a /etc/fstab
sudo mount /etc/mysql

echo "/vol/lib/mysql /var/lib/mysql none bind" | sudo tee -a /etc/fstab
sudo mount /var/lib/mysql

echo "/vol/log/mysql /var/log/mysql none bind" | sudo tee -a /etc/fstab
sudo mount /var/log/mysql

However the problem I'm facing is that for some reason after moving mysql to the EBS, innoDB
 writes and updates have slowed down almost tenfold, whereas myISAM is fine.
Has anyone seen something similar to this? Cheers
Comment: What file system are you using?
Comment: Run this command (replace device path with EBS volume device) and then report if the writes continue to be as slow: sudo dd if=/dev/xvdm of=/dev/null bs=10M
Answer: In general, the EBS volumes have been criticized for general inconsistency in performance.  That being said, there are other ways to speed up performance.  For example, apparently pre-allocating the space (i.e., writing out 1s for all the memory) speeds up future writes.  See this existing serverfault question for more info.  There are several good links there, but to sum it up:

JFS seems to provide the highest performance.
Allocating space when writing for the first time is very slow.
You can put two EBS volumes in RAID10 for better performance.

Be sure to learn from others' mistakes, however... Reddit, specifically, suffered massive downtime when the EBS volumes went down.
Comment: EBS volumes have a first *use* performance penalty for each block.  It doesn't matter if that first use is read or write.  I recommend reading all the blocks on a disk instead of writing as the writing causes the snapshots to be larger and more expensive.
Comment: Useful info with instructions on how to read all blocks on your EBS volume: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-initialize.html


Python string with byte array to byte array

Question: ciphertext = base64.b64decode(xxxxxx) //output is b'148,240,50,66,81,26,240,2,101,31'
bytearray(ciphertext) // output is bytearray(b'148,240,50,66,81,26,240,2,101,31')

What am looking for is output of bytearray([148,240,50,66,81,26,240,2,101,31])
Full code:
ciphertext = base64.b64decode("MTQ4LDI0MCw1MCw2Niw4MSwyNiwyNDAsMiwxMDEsMzEsMjM3LDEwMSw4OCwxODQsMTQsMTM1LDEzMCw0Miw0NywxODksMTkyLDE1MSw0OCwyMjQsMTU1LDQxLDM5LDE0MywyMDksMTA0LDE5NywyMywxMDUsMjMsMTYzLDUzLDQsMTQ0LDE2MSwxNDgsMjMwLDI1NCwxMzQsMjEzLDE3NCwyNDcsMTkxLDUyLDY0LDE2LDYzLDk0LDE1NCwxMzMsMzksMTMzLDIyNCwxODcsMTE0LDE1OCwyMzksMzUsMTUxLDM4LDE3NSwxNTIsOTksMTAyLDIxNCwyNTEsMTk0LDIxMywxNzMsMTc0LDcyLDIyNSwyMDIsMTcyLDE1NCw4OCwxMzksMTE1LDIzNywyMzYsMTIxLDAsMjE0LDIxNiwxOTYsNDAsMzgsMjA0LDgzLDEzNiwxNjAsMTczLDY5LDcsMzgsMjI1LDExOCw0OSw0OCw3MCwxNjYsMTIxLDI0NSwxOTEsMTgzLDEyMiwxOTksMTg3LDgsNDMsNDUsOTMsMTI0LDIxNSwxNjEsNzAsMjU0LDI2LDE4OCwxMywyMjYsMTMxLDMsNCw0MywxOTgsMjEyLDEwMywxMTcsMjE1LDEyNywyNDMsMzksNzIsNzYsMTE0LDUwLDE5Niw1NSwxMjEsODYsMjUxLDUzLDI0MiwzMCwxMDksNDcsMjEwLDI1MywxNjMsOTAsOTgsMTQsNjAsMTE1LDc1LDE0OSwyMTAsMTc1LDI2LDEyNCwyMjgsMjQ3LDIwLDIwMyw5NiwyMTAsMjYsODEsNjUsMTg4LDEyMSwxMjgsOTEsMTA3LDE2OCwxMywyMDcsMTc1LDE3MCwyNTUsMjM2LDE0OSwxMDksNTksMjQsMTcyLDExLDU4LDEzLDAsMTUyLDExNiwxMTAsMTExLDIyLDIzMSwzLDIzNyw0Miw4MSw3Nyw2MywyMjMsMTAzLDEwOSw1NiwxNTgsNDMsMjA2LDIwMiwzOCwxNDgsMTM3LDE4OSwyMTQsMjE2LDkwLDE4LDIyNCwyNTQsMzcsMTA5LDE4LDg0LDIyMiwyMDksMjUsNTMsMjE5LDE2OSwyMTEsNTAsMTgyLDQwLDExMiwyMDksMzEsNTIsMjEsNTMsOTgsMTIyLDI1NCwxMDgsMzksMzgsMTM0LDE1MCwxMzksMTk0LDMw=")

Comment: Can you please post a repeatable code? i need to know the input var type inside "base64.b64decode()"
Comment: agreed with @ShadowRanger
Answer: Replace:
bytearray(ciphertext)

with:
bytearray(map(int, ciphertext.split(b',')))
# Or if you prefer genexprs:
bytearray(int(x) for x in ciphertext.split(b','))

The former is just converting the raw bytes to an equivalent bytearray, the latter splits it up by commas and parses the components as ints.


Dynamic Content Type? (field appears based on previous taxonomy choice)

Question: I want to show/hide a field based on a taxonomy choice (in the content admin side of things).
Though having this field attached to every item of this content type does add overhead; I suspect it contributes to the easiest solution for a dynamic field.
I like the idea of dynamic fields, where only certain instances of an entity would have/need them, however, this seems like it could be quite an undertaking. (or my Drupal imagination is lacking today)
Answer: Try out the Conditional Fields module.

Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.
Conditional Fields allows you to manage sets of dependencies between fields. When a field is "dependent", it will only be available for editing and displayed if the state of the "dependee" field matches the right condition.
Comment: This looks like exactly what I was imagining! Might have to warm up to contrib by working on this module...