How do I set up the relation using Fluent API between an Employee entity and an ICollection?

Question: I am using entity framework and I have an Employee entity among other entities. One navigation property that I want Employee to have is a list of Employees that this Employee manages. This is the Employee class (it actually uses an EF prefix, but I'm referring to it without the prefix to make it less confusing):
///
/// The Class model for the Employee Entity
///
[Table("employee_entity")]
public class EFEmployee : EFBusinessEntity
{
    ///
    /// The hire date of the employee
    ///
    [Column("hire_date")]
    public DateTime HireDate { get; set; }

    ///
    /// The list of jobtitles for the employee
    ///
    [Column("job_title")]
    [Required]
    public byte[] JobTitle { get; set; }

    ///
    /// The Employee's salary (note: not attached to jobtitle necessarily)
    ///
    [Column("salary")]
    public int Salary { get; set; }

    ///
    /// List of Certifications for the employee
    ///
    [Column("certifications")]
    public byte[] Certifications { get; set; }

    ///
    /// Employee's stored up vacation time
    ///
    [Column("vacation_time")]
    public int VacationTime { get; set; }

    ///
    /// Employee's stored up sick time
    ///
    [Column("sick_time")]
    public int SickTime { get; set; }

    ///
    /// Maps the employee entity to the office entity
    ///
    [ForeignKey("office_entity")]
    public virtual EFOffice Office { get; set; }

    ///
    /// Maps the employee entity to the person entity
    ///
    public virtual EFPerson Identity { get; set; }

    ///
    /// Maps the employee entity to another employee entity
    ///
    public virtual EFEmployee ReportingTo { get; set; }

    ///
    /// Maps the employee entity to a collection of employee entites
    ///
    public virtual ICollection<EFEmployee> Managing { get; set; }

    ///
    /// Constructor for an Entity. Only requires the properties that cannot be null.
    ///
    /// <param name="Id"></param>
    /// <param name="TenantId"></param>
    /// <param name="hire"></param>
    /// <param name="titles"></param>
    /// <param name="salary"></param>
    /// <param name="certifications"></param>
    /// <param name="vacationTime"></param>
    /// <param name="sickTime"></param>
    public EFEmployee(Guid Id, Guid TenantId, DateTime hire, byte[] titles, int salary, byte[] certifications, int vacationTime, int sickTime)
    {
        this.HireDate = hire;
        this.JobTitle = titles;
        this.Salary = salary;
        this.Certifications = certifications;
        this.SickTime = sickTime;
        this.VacationTime = vacationTime;
    }
}

As you can see, one of Employee's navigation properties is
public virtual ICollection<EFEmployee> Managing { get; set; }

I have a an EmployeeMap class that uses Fluent API to establish the relationships between the Employee entity and other entities. It's incomplete right now, but this is what it looks like:
public partial class EmployeeMap : EntityTypeConfiguration<EFEmployee>
{
    public EmployeeMap()
    {
        // Relations
        HasRequired(t => t.Office).WithMany(u => u.Employees);
        HasMany(t => t.Managing).WithRequired(u => u.Employees);
    }
}

The first relation with the office and employees works and makes sense, since there are many Employee entities for each Office entity. However, I'm getting an error for the second relation mapping. Specifically, the 'Employees' at the end gives an error saying

Employee does not contain a definition for 'Employees' and no extension method etc...

It's pretty obvious why I get that error. I haven't declared a property in Employee for Employees and I don't know why I would. But then how do I set up relationships between two entities of the same type? If you look back at my Employee entity class, I also have the navigation property:
public virtual EFEmployee ReportingTo { get; set; }

Here I'm also trying to set up a relation between an Employee and another Employee, but I don't know how that would work since in an entity data model the Employee entity is just represented as one table with its properties. Does anyone know what I'm talking about and how to get around it?
Answer: When you're defining relationships, the properties you use need to be the inverse of each other. In the case of Managing, I think what you're looking for is:
HasMany(t => t.Managing).WithRequired(t => t.ReportingTo);

Because I'm guessing you want:
someEmployee.ReportingTo.Managing.Contains(someEmployee) == true

and you want each EFEmployee in someManager.Managing to have ReportingTo == someManager.

If you don't actually have an inverse property defined, you don't need to have one in the model configuration:
// someEmployee can possibly have many other EFEmployees with
// ReportingTo == someEmployee, but no collection property on someEmployee to
// represent that relationship!
HasRequired(t => t.ReportingTo).WithMany();

Comment: Oh wait, that relation between Managing and ReportingTo is actually really clever but pretty obvious. I don't know how the connection between the two didn't occur to me. Thanks!


Moving projects between MonoDevelop and Visual Studio 2012

Question: I need to be able to open a project with MonoDevelop, work on it, save it, and then open the same project with Visual Studio 2012, work on that as well, save the changes, and open with MonoDevelop again.
How would I go about doing something like that? Is there some way to export a MonoDevelop project to Visual Studio?
Answer: MonoDevelop uses the same project and solution file format as Visual Studio so you should be able to switch between the two.
If in doubt use version control for your files then you can easily undo any changes.


How to become a DJ

Question: I'd like to become a DJ, and to tell the truth, I also have made many tracks using Encore notation software. But, now that I want to bring it to reality, I don't know what instruments to purchase. A synthesizer? A DJ Booth? I even have no idea what are the names of those instruments.
To become a guitarist, you need a guitar, some educational books, something to sit on (for classical guitar gesture), something to put your left leg on, an note holder, maybe a metronome, diapason for tuning and maybe additional chords in case a chord is torn apart.
Can somebody please tell me how can I start? From where should I start?
Comment: @JimR Use the flag link right above your comment.  If you have a problem with one of the closures, kindly reply to the comments on it (or flag it with a comment if there are no prior comments).
Comment: @Saaed List questions generally end up with bad answers, as exemplified by gemne's (no explanation, no references, no personal experience to relate, a random incomplete list). For this reason we prefer questions that ask how to solve a problem; "How can I become a DJ?" would be an example. You'd still need to flesh out that question with details, of course - your experience, goals, appeal for answerers' experience, criteria for good answers, etc. I think your premise here is flawed also since DJs use a variety of tools and there's no definitive list, unlike how guitarists always need a guitar.
Comment: You don't seem to have elaborated on what specifically you're looking for, which is what was asked for. There are several pages online that have some guidelines; what about them is lacking and what are you confused about?
Comment: @Matthew, I totally disagree. I think the question is certainly sufficient for a complete answer, and I could give one. There are two basic paths, each with a couple of common choices. I could definitely supply a pretty definitive answer to this question. I think if you use the guitar analogy, it's similar to the questions about electric, acoustic, type, style, amps, effects.
Comment: I think you guys here are so strict. But my apologies and respect :). I change the question from **why** to **how**
Comment: I'm afraid @Ben, I haven't found the answer to this simple question on the Internet. "What is the first step to become a DJ?". Event [this](http://www.make-your-own-dance-and-techno-songs.com/become-a-dj-3.html) answer is vague. Should I purchase a DJ Booth? Is there a book that I have to read as my first step. Look, I want to become a DJ, and as I said, I have some themes already built. Now what? I'm totally empty here. No idea to take which step now. Isn't it a normal question? Isn't it answerable?
Comment: I still think that's kind of unanswerable, Saeed. There's no one right first step. You say you've built themes, I would think what you want next is to develop them into music you can perform. Do you feel you're lacking something to bring it together musically?  Are you unsure as to how to produce a particular effect?  Do you have questions about performing?  I think if you really look at what is problematic for you at the moment you can come up with a more specific question.
Comment: @yossarian But we have individual and at least somewhat specific questions on those things. This is way too broad.  That said, I'm willing to re-open for you to answer.
Comment: How is a DJ related to music performance or theory?  I've seen much more on-topic questions closed.
Comment: @JimR he clearly doesn't mean DJ in the sense of playing records on  the radio or in a club. He wants to create electronic music, and that's fair game albeit rather broad.
Comment: @JimR - I edited the tags. But AFAIK, putting the wrong tags is not a reason to close a question if the question itself is OK. We can just edit the tags. I have no opinion about this question and very little knowledge of the subject matter, so I'll leave the validity of the question to others - meanwhile it seems to be acceptable. Certainly a lot of cases are judgment calls and you might disagree. That's why there's a Meta Site [_**Music Practice and Theory - Meta**_](https://music.meta.stackexchange.com) - air your grievances there and see what you get back.
Answer: You are really asking two different questions. Do you want to be a DJ or do you want to perform electronic music live? Those are different things. If you want to play other peoples' music and sit up in the booth at the club and get people dancing, then you need a DJ setup (technically, that's not a "booth" as the booth is the place in the club where the DJ goes, you just need the equipment). If you want to play music that you write (or remix) in a live setting, then you want a live setup, often referred to as a PA (rather confusingly).
If you want to DJ
A DJ plays other people's music and will mix two (or more) tracks together at the same time. The basics of this setup are 2 music players and 1 mixer. A classic setup would be two record players and a mixer. However, you could replace record players with cd or mp3 players. There are many, many choices.
You can also now DJ with a laptop. You put all your music on your computer and then use some software to DJ. Popular programs include Traktor and Serato, although there are many others. You could DJ in this manner just using your mouse and keyboard, but there are also many dj interfaces for software (Best Buy has even started selling these). You can also use record players or CDs as a control mechanism. There are tons of options here. The advantage is less stuff to carry around and more control, but it's harder to jump on a friends decks and if your laptop crashes, so does the party.
The biggest difference between software and traditional approaches is that software will automatically (or with some work on your part) match the beats of what you're playing. So the tempo will be the same. Some say this takes the art out of DJing, because matching beats smoothly through a long mix is hard. I think those people are pissed that their job is less secure.
If you go the software route, get a program, collect some music and start to mess around.
If you go the CD or Record route, you need to learn how to match beats. A youtube search of "how to beat match" will return lots of info. Do this first. Practice a lot. It's hard.
In either case, find a community and ask some questions. There should be a local DJ community wherever you are. Meet those people. Find people online. Start reading DJ mag or something. The traditional teaching infrastructure that almost all other instruments have does not exist for DJs. The best thing to do is make some friends who are better than you and drink beer at their place.
If you want to play your own music
Then you need a rig to play on. This can really run the gamut. You can use samplers and keyboards, midi, live effects, software, ad infinitum. This can become a huge (and I mean huge black hole for your paycheck). You can spend a literal fortune on synths.
There is good news though, you don't need to start there. To start out with, all you need is Ableton Live. This will let you play and remix songs, live, on the fly. You can do all sorts of stuff with this program (including more traditional DJing). It's about $500, but there's a free 30 day trial. You can get started by using your mouse and keyboard, but if you get serious about it, google "Ableton Controler" and pick something up.
In terms of getting started, just get the software and start screwing around. Then find some Ableton forums and start talking to people, looking for blogs, magazines, and maybe make friends with a local producer or two.
Answer: To become a DJ in 21st Century, you need

A laptop(preferably a MACbook).
Good collection of dance music.
basics of notes matching, beat matching and rhythmic tapping.
A good shout out voice for yelling "Put your hands in the air" OR "Everybody F*****G JUMP"
Knowledge about DJ equipment controls : Tempo, BPM, Gater, Flanger, Loops, Sample, Equalizer, Filters .etc.
Almost 100 hours of practice to master all the controls with right timings of songs.

That's  enough to get started in clubs and small places where most of the sound setup is pre-installed. You can build your rapport by making some good mixes.   At the advanced level, you can add more skills by taking the professional course. You will learn about :-

Speaker systems.
Amplifiers and different classes of amplification.
Sound signal generation and synthesis.
Music and melody generation : Harmonics.
Working with Digital Audio workstation.
Go for advanced training if you want to take DJ profession seriously.

How to become a DJ


Regarding convergence in probability

Question: Let $\{X_n\}_{n\geq 1}$ be a sequence of random variables s.t $X_n \to a$ in probability, where $a>0$ is a fixed constant. I'm trying to show the following:
$$\sqrt{X_n} \to \sqrt{a}$$
and
$$\frac{a}{X_n}\to 1$$
both in probability. I'm here to see if my logic was sound. Here's my work

ATTEMPT
For the first part, we have
  $$|\sqrt{X_n}-\sqrt{a}|<\epsilon \impliedby |X_n-a|<\epsilon|\sqrt{X_n}+\sqrt{a}|=\epsilon|(\sqrt{X_n}-sqrt{a})+2\sqrt{a}|$$
  $$\leq \epsilon|\sqrt{X_n}-\sqrt{a}|+2\epsilon\sqrt{a}<\epsilon^2+2\epsilon\sqrt{a}$$
  Notice that
  $$\epsilon^2+2\epsilon\sqrt{a}>\epsilon\sqrt{a}$$
  It follows then that
  $$P(|\sqrt{X_n}-\sqrt{a}|\leq \epsilon)\geq P(|X_n-a|\leq \epsilon\sqrt{a})\to 1 \;\;as\;n\to\infty$$
  $$\implies \sqrt{X_n}\to\sqrt{a} \;\;in\;probability$$
For the second part, we have
  $$|\frac{a}{X_n}-1|=|\frac{X_n-a}{X_n}|<\epsilon \impliedby |X_n-a|<\epsilon|X_n|$$
  Now, since $X_n \to a$ as $n \to \infty$, we have that $X_n$ is a bounded sequence. In other words, there exists a real number $M<\infty$ s.t $|X_n|\leq M$. Thus,
  $$|X_n-a|<\epsilon|X_n|\impliedby |X_n-a|<\epsilon M$$
  Looking at it in probability, we have
  $$P(|\frac{a}{X_n}-1|>\epsilon)=P(|X_n-a|>\epsilon|X_n|)\leq P(|X_n-a|>\epsilon M)\to 0 \;\;as\;n\to\infty$$

I'm pretty confident in the first one, but am pretty iffy on the second. Was my logic sound?
Comment: Consider the sequence $X_n$ where $\Pr(X_n=a)=1-1/n$ and $\Pr(X_n=n)=1/n$. It seems to me that since $1-1/n\to 1$ this sequence converges to $a$ in probability, but clearly it is unbounded since $\sup(X_n)=\max(a,n)\to\infty$.
Comment: Continuous mapping theorem?
Answer: The details of the proofs matter less than developing appropriate intuition and techniques.  This answer focuses on an approach designed to help do that.  It consists of three steps: a "setup" in which the assumption and definitions are introduced; the "body" (or a "crucial step") in which the assumptions are somehow related to what is to be proven, and the "denouement" in which the proof is completed.  As in many cases with probability proofs, the crucial step here is a matter of working with numbers (the possible values of random variables) rather than dealing with the much more complicated random variables themselves.

Convergence in probability of a sequence of random variables $Y_n$ to a constant $a$  means that no matter what neighborhood of $0$ you pick, eventually each $Y_n-a$ lies in this neighborhood with a probability that is arbitrarily close to $1$.  (I won't spell out how to translate "eventually" and "arbitrarily close" into formal mathematics--anybody interested in this post already knows that.)
Recall that a neighborhood of $0$ is any set of real numbers containing an open set of which $0$ is a member.
The setup is routine.  Consider the sequence $Y_n = a/X_n$ and let $\mathcal{O}$ be any neighborhood of $0$. The objective is to show that eventually $Y_n-1$ will have an arbitrarily high chance of lying in $\mathcal{O}$.  Since $\mathcal{O}$ is a neighborhood, there must be an $\epsilon \gt 0$ for which the open interval $(-\epsilon, \epsilon)\subset \mathcal{O}$.  We may shrink $\epsilon$ if necessary to ensure $\epsilon \lt 1$, too.  This will assure that subsequent manipulations are legitimate and useful.
The crucial step will be to connect $Y_n$ with $X_n$.  That requires no knowledge of random variables at all. The algebra of numeric inequalities (exploiting the assumption $a\gt 0$) tells us that the set of numbers $\{Y_n(\omega)\,|\, Y_n(\omega) - 1 \in (-\epsilon, \epsilon)\}$, for any $\epsilon \gt 0$, is in one-to-one correspondence with the set of all $X_n(\omega)$ for which
$$\frac{a}{1+\epsilon} \lt X_n(\omega) \lt \frac{a}{1-\epsilon}.$$
Equivalently,
$$X_n(\omega)-a  \in \left(-\frac{a\epsilon}{1+\epsilon}, \frac{a\epsilon}{1-\epsilon}\right) = \mathcal{U}.$$
Since $a\ne 0$, the right hand side $\mathcal{U}$ indeed is a neighborhood of $0$.  (This clearly shows what breaks down when $a=0$.)
We are ready for the denouement.
Because $X_n \to a$ in probability, we know that eventually each $X_n-a$ will lie within $\mathcal{U}$ with arbitrarily high probability.  Equivalently, $Y_n-1$ will eventually lie within $(-\epsilon,\epsilon) \subset \mathcal{O}$ with arbitrarily high probability, QED.
Comment: I apologize for such a late best answer. It's been a busy week. Thank you so for much this!!!
Answer: For the first part, take $x,a,\epsilon>0$, and note that
$$
\begin{align}
|\sqrt{x}-\sqrt{a}|\geq\epsilon &\Rightarrow |\sqrt{x}-\sqrt{a}|\geq\epsilon \frac{\sqrt{a}}{\sqrt{a}} \Rightarrow |\sqrt{x}-\sqrt{a}|\geq\frac{\epsilon\sqrt{a}}{\sqrt{x}+\sqrt{a}} \\
&\Rightarrow |(\sqrt{x}-\sqrt{a})(\sqrt{x}+\sqrt{a})|\geq\epsilon\sqrt{a}\Rightarrow |x-a|\geq\epsilon\sqrt{a}.
\end{align}
$$
Hence, for any $\epsilon>0$, defining $\delta=\epsilon\sqrt{a}$, we have
$$
  \Pr(|\sqrt{X_n}-\sqrt{a}|\geq\epsilon)\leq\Pr(|X_n-a|\geq\delta)\to 0,
$$
when $n\to\infty$, implying that $\sqrt{X_n}\stackrel{\Pr}\to\sqrt{a}$.
For the second part, take again $x,a,\epsilon>0$, and cheat from Hubber's answer (this is the key step ;-) to define
$$
  \delta = \min\left\{ \frac{a\epsilon}{1+\epsilon},\frac{a\epsilon}{1-\epsilon}\right\}.
$$
Now,
$$
\begin{align}
|x-a|<\delta &\Rightarrow a-\delta<x<a+\delta \Rightarrow a - \frac{a\epsilon}{1+\epsilon} < x < a + \frac{a\epsilon}{1-\epsilon} \\
&\Rightarrow \frac{a}{1+\epsilon} < x < \frac{a}{1-\epsilon} \Rightarrow 1-\epsilon<\frac{a}{x}<1+\epsilon \Rightarrow \left| \frac{a}{x}-1\right|<\epsilon.
\end{align}
$$
The contrapositive of this statement is
$$
  \left| \frac{a}{x}-1\right|\geq\epsilon \Rightarrow |x-a|\geq\delta.
$$
Therefore,
$$
  \Pr\!\left(\left|\frac{a}{X_n}-1\right|\geq\epsilon\right)\leq\Pr(|X_n-a|\geq\delta)\to 0,
$$
when $n\to\infty$, implying that $\frac{a}{X_n}\stackrel{\Pr}\to 1$.
Note: both items are consequences of a more general result. First of all remember this Lemma: $X_n\stackrel{\Pr}{\to}X$ if and only if for any subsequence $\{n_i\}\subset\mathbb{N}$ there is a subsequence $\{n_{i_j}\}\subset\{n_i\}$ such that $X_{n_{i_j}}\to X$ almost surely when $j\to\infty$. Also, remember from Real Analysis that $g:A\to\mathbb{R}$ is continuous at a limit point $x$ of $A$ if and only if for every sequence $\{x_n\}$ in $A$ it holds that $x_n\to x$ implies $g(x_n)\to g(x)$. Hence, if $g$ is continuous and $X_n\to X$ almost surely, then
$$
\Pr\!\left(\lim_{n\to\infty}g(X_n)=g(X)\right)\geq\Pr\!\left(\lim_{x\to\infty}X_n=X\right)=1,
$$
and it follows that $g(X_n)\to g(X)$ almost surely. Moreover, $g$ being continuous and $X_n\stackrel{\Pr}{\to}X$, if we pick any subsequence $\{n_i\}\subset\mathbb{N}$, then, using the Lemma, there is a subsequence $\{n_{i_j}\}\subset\{n_i\}$ such that $X_{n_{i_j}}\to X$ almost surely when $j\to\infty$. But then, as we have seen, it follows that $g(X_{n_{i_j}})\to g(X)$ almost surely when $j\to\infty$. Since this argument holds for every subsequence $\{n_i\}\subset\mathbb{N}$, using the Lemma in the other direction, we conclude that $g(X_n)\stackrel{\Pr}{\to}g(X)$. Hence, to answer your question you can just define continuous functions $g(x)=\sqrt{x}$ and $h(x)=a/x$, for $x>0$, and apply this result.
Comment: Zen thank you for you answer. This was very clear!
Answer: We are given that
$$\lim_{n \rightarrow \infty}P(|X_n-\alpha| > \epsilon) = 0$$
and we want to show that
$$\lim_{n \rightarrow \infty}P\left(\left|\frac {\alpha}{X_n}-1\right| > \epsilon\right) = 0$$
We have that
$$\left|\frac {\alpha}{X_n}-1\right| = \left|\frac {1}{X_n}(\alpha-X_n)\right| = \left|\frac {1}{X_n}\right|\left|X_n-\alpha\right|$$
So equivalently, we are examining the probability limit
$$\lim_{n \rightarrow \infty}P\left(\left|\frac {1}{X_n}\right|\left|X_n-\alpha\right| > \epsilon\right) = \;?\;0$$
We can break the probability into two mutually exclusive joint probabilities
$$P\left(\left|\frac {1}{X_n}\right|\left|X_n-\alpha\right| > \epsilon\right) =\\ P\left(\left|\frac {1}{X_n}\right|\left|X_n-\alpha\right| > \epsilon,|X_n| \geq 1 \right)  + P\left(\left|\frac {1}{X_n}\right|\left|X_n-\alpha\right| > \epsilon,|X_n| < 1 \right)$$
For the first element we have the series of inequalities
$$P\left(\left|\frac {1}{X_n}\right|\left|X_n-\alpha\right| > \epsilon,|X_n| \geq 1 \right) \leq P\big[\left|X_n-\alpha\right| > \epsilon,|X_n| \geq 1 \big] \leq P\big[\left|X_n-\alpha\right| > \epsilon \big]$$
The first inequality comes from the fact that we are considering the region where $|X_n|$ is higher than unity and so its reciprocal is smaller than unity. The second inequality because a joint probability of a set of events cannot be greater than the probability of a subset of these events.
The limit of the rightmost term is zero (this is the premise), so the limit of the leftmost term is also zero. So the first element of the probability that interests us is zero.
For the second element we have
$$P\left(\left|\frac {1}{X_n}\right|\left|X_n-\alpha\right| > \epsilon,|X_n| < 1 \right) = P\left(\left|X_n-\alpha\right| > \epsilon|X_n|,|X_n| < 1 \right)$$
Define $\delta \equiv \epsilon\cdot \max |X_n|$.  Since here $|X_n|$ is bounded, it follows that $\delta$ can be made arnitrarily small or large, and so it is equivalent to $\epsilon$.
So we have the inequality
$$P\big[\left|X_n-\alpha\right| > \delta,|X_n| < 1 \big] \leq  P\big[\left|X_n-\alpha\right| > \delta \big]$$
Again, the limit on the right side is zero by our premise, so the limit on the left side is also zero. Therefore the second element of the probability that interests us is also zero. QED.

Regarding convergence in probability


How to have recognized all the libraries Rpy2 R

Question: How to have recognized all the libraries Rpy2 R.
Rpy2 not recognizing the libraries, utils, and tools.
import rpy2.robjects as robjects

R = robjects.r

>>> R['library']("utils")

RVector - Python:0x7f65fc85cfc8 / R:0x19bb980

>>> R['library']("tools")

RVector - Python:0x7f65fc85f5a8 / R:0x2419140

(>>> from rpy2.robjects.packages import importr
Traceback (most recent call last):
  File "", line 1, in
ImportError: No module named packages
)
as I can update Rpy2 to load all the libraries without problems or R that can be done.
PS: I use R 2.10 and python 2.6 on ubuntu
Answer: In order to get the importr command to work, you probably need to upgrade your version of rpy2 -- try checking your version:
print rpy2.__version__

I believe you need version 2.1.0 or greater. The following works for me under 2.1.7 but not on 2.0.3:
In [1]: import rpy2.robjects as robjects

In [2]: R = robjects.r

In [3]: from rpy2.robjects.packages import importr

In [4]: importr("utils")
Out[4]: <rpy2.robjects.packages.SignatureTranslatedPackage object at 0x1e96310>

I'm not sure what you're trying to do, as those libraries should work without any extra importing, as Gavin has mentioned.
Comment: You may want to consider storing the object returned by importr() (e.g., utils = importr('utils') ). That object is module-like, and wrap the R objects with extra niceties ('.' replaced by '_' in the names, including parameter names for functions)
Answer: Unless I am mistaken - I don't use Rpy2 - these packages (they are not libraries by the way) are loaded automatically when R is started; you do not need to do anything else to make use of them. All the user-visible functions in these packages are made available during R start up.
Also, you can't update these packages - they are R. You only get updates when you update R itself. In this they differ from the Recommended packages (like nlme, mgcv, MASS etc) which are also on CRAN and which are updated more frequently in between R version updates.


Alternativas ao uso de transações no MyISAM

Question: Tenho uma aplicação que se encontra numa hospedagem que não me dá suporte ao mecanismo de armazenamento InnoDB, logo, fico a mercê do uso de MyISAM.
Existe uma alternativa segura ao uso de transações numa base de dados com o tipo de mecanismo MyISAM?
Answer: De forma geral não tem. Você pode fazer um mecanismo complexo na aplicação para tentar simular isto, mas é extremamente difícil fazer certo, dá muito trabalho, terá uma enorme perda de performance e um problema até maior na mão.
Tem uma solução simples: troque de hospedagem.
Antes pense se realmente precisa das transações. Nem sempre ela é tão necessária assim, o uso sem não é tão trágico quanto dizem, só não é 100%.
Ou mude para o SQLite que tem transações, é mais simples e performático (só não sei se resolve tudo o que precisa).


Multiply polynomials

Question:
Show how to multiply two linear polynomials $ax+b$ and $cx+d$ using only three multiplications.
Give a divide-and-conquer algorithms for multiplying two polynomials of degree-bound n that runs in time Θ(n^(lg3).  The algorithm should divide the input polynomial coefficients into a high half and a low half.
(ax+b)(cx+d)=ac x^2+((a+b)(c+d)-ac-bd)x+bd
We let p and q be the vectors of coefficients of the first and second polynomial P and Q, respectively.
We assume that both of these vectors are of length n=max{ length(P), length(Q)} and we let m=ceil(n/2).
Then P=A x^m+B, where A=p_m+p_(m+1) x+ .... + p_(n-1) x^(n-1-m), B=p_0+p_1 x+ ...s+p_(m-1)x^(m-1) and Q=Cx^m+D, where C=q_m+q_(m+1) x+ ...+ q_(n-1) x^(n-1-m) and D=q_0+q_1 x+ ... + q_(n-1) x^(n-1)=q_0+q_1 x+ ... + q_(m-1) x^(m-1).

Using the previous result, it holds that (Ax^m+B)(Cx^m+D)=AC x^(2m)+((A+B)(C+D)-AC-BD) x^m+BD (1)$.
I found the following algorithm (link)
Algorithm(p,q){
   n=size(p)
   m=ceil(n/2)
   if n==1 return p*q
   else{
         a=p[m,n-1]
         b=p[0,m-1]
         c=q[m,n-1]
         d=q[0,m-1]
         tmp1=Algorithm(a+b,c+d)
         tmp2=Algorithm(a,c)
         tmp3=Algorithm(b,d)
   return tmp2<<n+(tmp1-tmp2-tmp3)<<m+tmp3

So we suppose that  a,b,c,d  are vectors, right?
Could you explain me why we make these recursive calls:
 tmp1=Algorithm(a+b,c+d)
 tmp2=Algorithm(a,c)
 tmp3=Algorithm(b,d)

I haven't really understood it... Also, how could we elsewhise shift a number to the left by a specific number of digits?
Comment: I'm voting to close this question as off-topic because it appears to be about math in general, not about programming.
Comment: It should be mentioned somewhere that this algorithm is known as **Karatsuba multiplication**.
Answer: Let's say you have two polynomials of maximum degree n, and you want to find the polynomial that is their product. Furthermore, you want to use a divide and conquer approach in order to optimize your solution.
How can we break the problem of multiplying two polynomials of degree n into analogous subproblems that involve less work? Well, we can turn them into a larger number of smaller polynomials. Given a polynomial of degree n, you can turn it into two smaller polynomials by following the reasoning below.
Given a polynomial P of degree n as follows:

Let:

We can factor out x^m from the "second half" of the polynomial. Or, continuing with our notation:

Or, if we let:

We have:

We've managed to express our polynomial of degree n in terms of two smaller polynomials, of degree m. Why is this useful?
Well, let us return to the original problem for a second. Recalling that we are given two polynomials to find the product of, let us split them as seen above. Let A, B denote the first and second "halves" of the first polynomial P, and let C, D denote the two halves of the second polynomial Q.*
Rearranging the product of P and Q:

Awesome! We've managed to express the product of our two large polynomials as a sum of three products of smaller...well...polynomials. That's not so great, is it. So when you want to compute AC, or BD, or (A+C)(B+D), you have the same problem you started out with: "take these two polynomials and multiply them".
But this is the very problem we are solving! Assuming our method is properly implemented to return (the coefficient vector of) the product of two polynomials, we can just pass it the three products we need to compute. This is why you have three recursive calls to Algorithm, for each of A, C, B, D and A+B, C+D.
Finally, regarding the left shift: I am fairly certain this is referring to leftward shifting within the coefficient vector, and not bitwise left shift. Since the index within the coefficient vector represents the power of x of the term the coefficient applies to, we can represent multiplication of some polynomial by a given power of x by shifting the terms in its coefficient vector leftwards by a corresponding amount.
*Note that both polynomials are treated as having the exact same degree, i.e. the degree of the higher order polynomial, among P and Q. All the missing terms in the other polynomial have coefficient zero.
Comment: Should the limit on the second summations be `n-m` instead of `m-n`?
Answer: The recursive calls are for polynomial multiplication, which has to be done when you compute AC, etc., in order to evaluate the formula AC x^n, in which AC is a polynomial. (You should probably think in terms of replacing n with a larger even number, if necessary, in which case the leading coefficient of the polynomial might be 0. Then you always have n=2m.) Just walk through it with a product of second degree polynomials; it should be obvious.
As for the shift operator, it's pseudocode, so there is some latitude in interpretation. For polynomials, the shift operator << n means multiply by x^n, which also corresponds to a left shift of the vector of coefficients.
The reason the shift operator is used here is because the real interesting part is if we interpret this in the context of integer multiplication. We can represent integers as polynomials; e.g., 6 = 1 * 2^2 + 1 * 2^1 + 0 * 2^0 which corresponds to the polynomial 1 * x^2 + 1 * x^1 + 0 * x^0 under the correspondence x=2. Then integer multiplication corresponds to polynomial multiplication (but with carries) and multiplication by x corresponds to multiplication by 2 which corresponds to left shift. (We don't have to worry about the carries because they're taken care of by the + operator in the context of integer addition.)
Comment: Why if we replace n with a larger even number, might the leading coefficient of the polynomial be 0?   Also, would it  be right if we returned the following? tmp2*x^n+(tmp1-tmp2-tmp3)*x^m+tmp3
Comment: Yes, leading coefficient might be 0, but that's OK in this context. It would be right to return the polynomial for the polynomial question, but the idea here is to make the same algorithm do double duty (or multiple duty) in multiple different contexts; that's the idea behind *generic programming*. I strongly recommend Stepanov's *From Math to Generic Programming*.

Multiply polynomials


How do I change priority of two different implementations of hook_node_access()?

Question: I am using the Node View Permissions module, which implements hook_node_access(). I am also using a custom module (mymodule.module) which is implementing the same hook. node_view_permissions_node_access() is always invoked after mymodule_node_access().
How can I change the hook invocation order? mymodule_node_access() should be executed after node_view_permissions_node_access().
Answer: Use hook_module_implements_alter():

This hook is invoked during module_implements(). A module may implement this hook in order to reorder the implementing modules, which are otherwise ordered by the module's system weight.

Example:
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_access') {
    // Move your module's implementation to the end of the list
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }
}

In the possible event that another module also implements hook_module_implements_alter to move its own implementation of hook_node_access to the end of the list, you can get cunning and make sure your implementation of the alter hook runs last too:
  if ($hook == 'node_access' || $hook == 'module_implements_alter') {
    // Move your module's implementation to the end of the list
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }


How to prevent piping to `less` in Rust from overwriting the shell prompt?

Question: Running this program:
use std::process::{Command, Stdio};
use std::io::{self, Write};

fn main() -> io::Result<()> {
    let mut child = Command::new("less")
        .args(["--quit-if-one-screen"])
        .stdin(Stdio::piped())
        .spawn()?;
    let child_stdin = child.stdin.as_mut().unwrap();
    child_stdin.write_all(b"Hello, world!\n")?;
    drop(child_stdin);

    Ok(())
}

Overwrites the prompt with the output being piped to less, e.g., it looks something like this, and I have to hit enter a couple of times to get my prompt back:
% cargo run --bin pager
   Compiling single v0.1.0 (/Users/robenkleene/Developer/Scratch/Rust/single)
    Finished dev [unoptimized + debuginfo] target(s) in 0.13s
     Running `target/debug/pager`
Hello, world!

I want it to look like this, e.g., the prompt re-appears correctly after the program runs:
% cargo run --bin pager
   Compiling single v0.1.0 (/Users/robenkleene/Developer/Scratch/Rust/single)
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/pager`
Hello, world!
%

Comment: I suggest adding `child.wait()?;` at the end.
Comment: For me, its working correctly. i.e after the bytes are written to stdin of child process. program completes and prompt appears right after it.
Comment: The shell and terminal emulator you use might be relevant, can reproduce on `alacritty`+`bash` but not on `zsh` maybe how you setup your promt there, too.
Comment: @SvenMarnach `child.wait()?;` solved it. If you add this as an answer I'll accept it. Thank you!
Answer: Using drop on a &mut does nothing. You probably want to drop the actual stdin handle, which you can do by taking it out of the Child struct.
let mut child_stdin = child.stdin.take().unwrap();
child_stdin.write_all(b"Hello, world!\n")?;
drop(child_stdin);

Comment: Well you can't use the reference any more after that (unlike with a shared one which is `Copy`) but you're right it probably doesn't have the desired effect. The problem is that doesn't help with the prompt being overwritten.


Dúvida - SaveChanges não funciona, apenas retorna 0

Question: Segue código:
using (var db = new Entities())
{
    var result = db.
        Tabela1
        .Where(x => x.Id == 1)
        .Select(x => new SuaClasse
        {
            Coluna1 = x.Coluna1,
        })
        .FirstOrDefault();

    if (result.Coluna1 != string.Empty)
    {
        result.Coluna2 = "Novo valor";
    }

    var num = db.SaveChanges(); // aqui retorna 0
}

Classe:
public class SuaClasse
{
    public string Coluna1 { get; set; }
    public string Coluna2 { get; set; }
}

Quero apenas selecionar uma coluna e depois atualizar valor da coluna2, acontece nada, só retorna 0. O que eu fiz de errado ?
Answer: Você não precisa fazer um select em um objeto anonimo ou de uma classe diferente para em seguida executar um update.
Basta executar o select, alterar o campo, e update em seguida.
using (var db = new Entities())
{
    var result = db.
        Tabela1
        .Where(x => x.Id == 1).FirstOrDefault();

    if (result.Coluna1 != string.Empty)
    {
        result.Coluna2 = "Novo valor";
    }

    var num = db.SaveChanges(); // aqui retorna 0
}

Comment: @MatheusMiranda esse varbinary é imagem ? arquivo ? pelo que andei lendo, pra contornar esse problema você deveria colocar essa propriedade em outra entidade, mesmo que seja de relação 1:1. Aí é mais questão da sua necessidade... se é mais fácil fazer outra entidade ou utilizar a query. Vlw
Answer: O Entity Framework não alterar objetos anônimos, e sim só altera aquele que ele tem conhecimento e está contido em seu contexto. Nesse código por exemplo, acontece isso a criação de um tipo que o Entity não conhece.
Se precisa alterar campos individualmente, pode escrever o update e mandar o Entity Framework executar.
Exemplo:
using (var context = new BloggingContext())
{
    context.Database.ExecuteSqlCommand(
        "UPDATE dbo.Blogs SET Name = 'Another Name' WHERE BlogId = 1");
}

também pode trazer informações, exemplo:
using (var context = new BloggingContext())
{
    var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}

e a maneira que o Entity Framework faz é materializar todo o objeto (como já explicado, contido no seu contexto) e depois pode fazer alterações no campo e mandar salvar, no seu código algo assim:
using (var db = new Entities())
{
    var result = db.Tabela1.Where(x => x.Id == 1).FirstOrDefault();
    if (result != null)
    {
        result.Coluna2 = "Novo valor";
        var num = db.SaveChanges();
    }
}

Referencia:

Entity Framework Raw SQL Queries
Executing SQL Query in Entity Framework
Anonymous Types (C# Programming Guide)
Comment: Uma das vantagens de usar o Entity Framework não é evitar de ter de usar SQL?
Comment: @ramaral você perguntou bem, evitar, mas, não quer dizer que não possa usar, e em desenvolvimento de sistemas não temos um regra plena pra tudo, esse maneira por exemplo talvez seja melhor do que materializar objetos e somente alterar um campo... Vai depender da ocasião, mas, não é regra que não possa ser utilizado tanto é que o próprio `framework` promove isso.
Comment: @MatheusMiranda é recomendavel usar em momentos que precisa ser utilizados, não existe uma regra para não usar, mas, existe aonde é necessário usar, um exemplo de usar isso se você tiver que alterar um lote de informações aonde você precise setar um valor padrão para 1000 registros, as duas primeiras opções da resposta tem um desempenho melhor do que a 3 forma. No seu caso em especifico com a pesquisa deve retornar um item, ela é talvez nesse caso a melhor, porque a só altera um item da sua tabela, então dizer "Não é recomendavel" está errado, ele pode ser usado ou não depende dos casos ...
Comment: @MatheusMiranda não é só funcionar, é utilizar da maneira e momento correto ... entendeu! As 3 opções são funcionais e corretas, cada uma no seu momento. A sua duvida da pergunta é antes por isso dos exemplos.
Comment: @MatheusMiranda pode usar as primeira ou a terceira, como você vai alterar um vídeo por vez acredito que essas duas são satisfatória. Para não ter trabalho adicional, faça com a 3 opção, porque se fizer com a primeira você deve criar um SQLParameter e dizer o tipo para gravar. Agora se você entender que a recuperação é muito lenta e só quer alterar, pode usar a primeira. Faça o teste para ver se existe muita diferença no desempenho.
Comment: Agora a resposta está quase como eu esperava que fosse: usar SaveChanges()` e, em alternativa, quando se justifique, recorrer ao SQL bruto.
Comment: O duro é o que as pessoas acabam não entendendo @ramaral, só quis demonstrar que existe caminhos que podem ser seguidos, mas, não como regra geral. Talvez ele tenha duvidas de como é isso ou aquilo, acho que o meu contexto é melhor explicado, mas, muitos não veem assim e temos que respeita, obrigado pelo seu comentário.
Comment: Virgilio, não entenda mal os meus comentários. A sua resposta está/estava boa, até porque começava com a explicação do porquê de `SaveChanges()` não funcionar. Eu só acho que, em vez de ter apresentado uma solução com SQL bruto, deveria ter apresentado uma com `SaveChanges()`. A alternativa com SQL é válida e útil em várias situações mas tem de haver uma justificação para usá-la, a pergunta não indiciava alguma.
Comment: @ramaral não entendi mal os comentários, a pergunta não indicava, e não dizia um caminho, estava em aberto, faltou eu colocar a terceira opção, que seria implícita no desenvolvimento com Entity Framework, mas, que aqui deve ser observada.
Comment: É isso, parece então que estamos de acordo:)
Comment: Virgílio, porque a o seu primeiro exemplo de código ou segundo exemplo, não são recomendado a usar (alguns dizem) ? Mais funciona ! Por causa da ORM ?
Comment: Entendo, tenho um campo com arquivo muito grande com tipo varbinary, é um vídeo. Por isso usei `Select()` para evitar o vídeo grande. Nesse caso é recomendável usar no primeiro exemplo do seu código ? Porque com entity framework sem `Select()` traz todos os campos, daí a memória não agradece.


Google App Engine Tutorial, 403 Forbidden: BadAuthentication on upload data

Question: I am following the guide at: https://cloud.google.com/solutions/mobile/how-to-build-mobile-app-with-app-engine-backend-tutorial/ using Android Studio.
I have followed the tutorial from beginning up to 'Populate the datastore with data'.
I navigated to the correct directory, successfully ran gcloud auth login from terminal, and logged in via the browser which was created. I then attempted to run the first command given:
/home/XXXX/google_appengine/appcfg.py upload_data --config_file bulkloader.yaml --url=http://mobileassistant-1026/remote_api --filename places.csv --kind=Place -e firstname.lastname@example.com

where the XXXXs are my username and email address respectively.
The terminal returns (with me entering the password half way):
12:25 PM Uploading data records.
[INFO    ] Logging to bulkloader-log-20150805.122507
[INFO    ] Throttling transfers:
[INFO    ] Bandwidth: 250000 bytes/second
[INFO    ] HTTP connections: 8/second
[INFO    ] Entities inserted/fetched/modified: 20/second
[INFO    ] Batch Size: 10
Password for email@example.com:
Error 403: --- begin server output ---
403 Forbidden: BadAuthentication
--- end server output ---

Does anybody know how to get past this error?
I am completely new to App Engine, and backends in general, so please assume no knowledge in any answers!
Thanks in advance for any help.
Answer: I think this issue due to 2-step verification for your gmail account.
Please add another member(gmail)as owner in your console.developers.google.com project and try it will work...as i did same thing and it worked for me.


Transformar texto em RegExp

Question: Existe uma forma de transformar um texto qualquer que contém um regex válido em um regex?
Exemplo simples, poderia ser qualquer outro RegExp válido:
let regex = '/ola/g'
let texto = 'ola mundo, ola mundo!'
console.log(texto.replace(new RegExp(regex), 'olá')) // ola mundo, ola mundo!

Veja que mesmo tendo um regex como um texto, e passando para o construtor new RegExp(regex) não faz a substituição, o resultado esperado deveria ser:
// olá mundo, olá mundo!

Comment: Leia o link que indiquei, principalmente a seção "*ReDoS e os perigos de criar regex com entradas de usuário*" - veja que o problema ocorre com uma regex válida
Comment: Como já comentado abaixo, ao aceitar qualquer texto como regex, tem que tomar alguns cuidados: https://pt.stackoverflow.com/q/458289/112052
Comment: @hkotsubo Sim, mas no texto eu especifico que sempre vai ser um regex válido.
Comment: @AugustoVasques Fiz algumas alterações no texto, veja se consegue entender.
Answer: A estrutura deve ser new RegExp(pattern, flags), a parte do pattern é o que está entre /.../ e as flags/modificadores são os que estão após a última /, então basta separar a string e ajustar corretamente conforme o método funciona, um exemplo simples aplicável:

var input = '/olá/g';

// Verifica aonde aonde o pattern termina
var endPos = input.lastIndexOf('/');

// Remove o primeiro caractere e remove a parte do modificador
var pattern = input.substring(1, endPos);

// Pega o modificador após o pattern
var flags = input.substring(endPos + 1);

console.log('pattern:', pattern, 'flags:', flags);

// Cria uma regex
var re = new RegExp(pattern, flags);

// Testa
console.log(re.test('olá'));
console.log(re.test('hello'));

Note que permitir entrada do usuário para gerar expressões regulares podem causar problemas, como ReDos.

Evitando Negação de Serviço de Expressão Regular (ReDoS)
Conforme explicado em Runaway Regular Expressions: Catastrophic Backtracking e Preventing Regular Expression Denial of Service (ReDoS), se o servidor aceitar regexs do usuário, o usuário poderá facilmente fornecer uma expressão que leve a um retrocesso catastrófico.
Se o servidor aceitar expressões enviadas pelos usuários, eles poderão fornecer entradas que acionam retrocesso catastrófico em expressões regulares usados pelo servidor, se esses expressões regulares estiverem predispostos a retrocesso catastrófico o servidor fica suscetível à negação de serviço de expressão regular (ReDoS). Por exemplo, se um número elevado de usuários (ou um ator disfarçado de muitos usuários) fornece expressões regulares maliciosos e/ou sujeitos para correspondência, o servidor gasta quase todos os seus ciclos de CPU tentando corresponder a esses expressões regulares.
A única defesa real é usar um mecanismo de regex direcionado a texto. Esses motores não retrocedem. Seu desempenho depende do comprimento da string enviada pelo usuário, não da complexidade da expressão regular. Mas eles também não suportam recursos como backreferences que dependem de backtracking e que muitos usuários esperam.
Se seu aplicativo usa um mecanismo de retrocesso com expressões regulares fornecidas pelo usuário, você só pode atenuar as consequências do retrocesso catastrófico e você realmente precisa fazer isso. É muito fácil para pessoas com habilidades limitadas de regex criar acidentalmente um que degenere em retrocesso catastrófico.
Você precisará usar um mecanismo regex que aborte a tentativa de correspondência quando ocorrer um retrocesso catastrófico, em vez de executar até que o script trave ou o sistema operacional o elimine.
O mecanismo PCRE permite definir limites de recursão. Quanto mais baixos seus limites, melhor a proteção contra ReDoS, mas maior o risco de abortar expressões regulares legítimos que encontrariam uma correspondência válida com um pouco mais de tempo. Limites baixos de recursão podem impedir correspondências longas de regex. Tempos limite baixos podem abortar pesquisas em arquivos grandes muito cedo.
Linguagens/configurações para poder limitar o tempo:

Ruby: https://www.ruby-lang.org/en/news/2022/04/03/ruby-3-2-0-preview1-released/
PHP: https://www.php.net/manual/en/pcre.configuration.php
.NET: https://learn.microsoft.com/pt-br/dotnet/api/system.text.regularexpressions.regex.-ctor#system-text-regularexpressions-regex-ctor(system-string-system-text-regularexpressions-regexoptions-system-timespan)

Transformar texto em RegExp


CUDA Graph Problem: Results not computed for the first iteration

Question: I am trying to utilize CUDA Graphs for the computation of Fast Fourier Transform (FFT) using CUDA's cuFFT APIs.
I modified the sample FFT code present on Github into the following FFT code using CUDA Graphs:
#include <cuda.h>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include "device_functions.h"
#include <iostream>
#include <cufft.h>

// Complex data type
typedef float2 Complex;
static __device__  inline Complex ComplexScale(Complex, float);
static __device__  inline Complex ComplexMul(Complex, Complex);
static __global__ void ComplexPointwiseMulAndScale(Complex*, const Complex*, int, float);

#define CUDA_CALL( call )               \
    {                                       \
    cudaError_t result = call;              \
    if ( cudaSuccess != result )            \
        std::cerr << "CUDA error " << result << " in " << __FILE__ << ":" << __LINE__ << ": " << cudaGetErrorString( result ) << " (" << #call << ")" << std::endl;  \
    }

#define CUDA_FFT_CALL( call )               \
    {                                       \
    cufftResult result = call;              \
    if ( CUFFT_SUCCESS != result )            \
        std::cerr << "FFT error " << result << " in " << __FILE__ << ":" << __LINE__ << ": " <<  result  << std::endl;  \
    }

// The filter size is assumed to be a number smaller than the signal size
#define SIGNAL_SIZE        10
#define FILTER_KERNEL_SIZE  4

static __device__ inline Complex ComplexScale(Complex a, float s)
{
    Complex c;
    c.x = s * a.x;
    c.y = s * a.y;
    return c;
}

// Complex multiplication
static __device__ inline Complex ComplexMul(Complex a, Complex b)
{
    Complex c;
    c.x = a.x * b.x - a.y * b.y;
    c.y = a.x * b.y + a.y * b.x;
    return c;
}

// Complex pointwise multiplication
static __global__ void ComplexPointwiseMulAndScale(Complex* a, const Complex* b, int size, float scale)
{
    const int numThreads = blockDim.x * gridDim.x;
    const int threadID = blockIdx.x * blockDim.x + threadIdx.x;
    for (int i = threadID; i < size; i += numThreads)
    {
        a[i] = ComplexScale(ComplexMul(a[i], b[i]), scale);
    }
}

int main()
{
    printf("[simpleCUFFT] is starting...\n");

    int minRadius = FILTER_KERNEL_SIZE / 2;
    int maxRadius = FILTER_KERNEL_SIZE - minRadius;
    int padded_data_size = SIGNAL_SIZE + maxRadius;

    // Allocate HOST Memories
    Complex* h_signal = (Complex*)malloc(sizeof(Complex) * SIGNAL_SIZE); //host signal
    Complex* h_filter_kernel = (Complex*)malloc(sizeof(Complex) * FILTER_KERNEL_SIZE); //host filter
    Complex* h_padded_signal= (Complex*)malloc(sizeof(Complex) * padded_data_size); // host Padded signal
    Complex* h_padded_filter_kernel = (Complex*)malloc(sizeof(Complex) * padded_data_size); // host Padded filter kernel
    Complex* h_convolved_signal = (Complex*)malloc(sizeof(Complex) * padded_data_size); // to store convolution RESULTS
    memset(h_convolved_signal, 0, padded_data_size * sizeof(Complex));

    //Allocate DEVICE Memories
    Complex* d_signal; //device signal
    cudaMalloc((void**)&d_signal, sizeof(Complex) * padded_data_size);
    Complex* d_filter_kernel;
    cudaMalloc((void**)&d_filter_kernel, sizeof(Complex) * padded_data_size); //device kernel

    //CUDA GRAPH
    bool graphCreated = false;
    cudaGraph_t graph;
    cudaGraphExec_t instance;
    cudaStream_t stream;
    cudaStreamCreate(&stream);

    // CUFFT plan
    cufftHandle plan;
    CUDA_FFT_CALL(cufftPlan1d(&plan, padded_data_size, CUFFT_C2C, 1));
    cufftSetStream(plan, stream); // bind plan to the stream

    // Initalize the memory for the signal
    for (unsigned int i = 0; i < SIGNAL_SIZE; ++i)
    {
        h_signal[i].x = rand() / (float)RAND_MAX;
        h_signal[i].y = 0;
    }

    // Initalize the memory for the filter
    for (unsigned int i = 0; i < FILTER_KERNEL_SIZE; ++i)
    {
        h_filter_kernel[i].x = rand() / (float)RAND_MAX;
        h_filter_kernel[i].y = 0;
    }

    //REPEAT 3 times
    int nRepeatationsNeeded = 3;
    for (int repeatations = 0; repeatations < nRepeatationsNeeded; repeatations++)
    {
        std::cout << "\n\n" << "Repeatation ------ " << repeatations << std::endl;

        if (!graphCreated)
        {
            //Start Graph Recording --------------!!!!!!!!
            CUDA_CALL(cudaStreamBeginCapture(stream, cudaStreamCaptureModeGlobal));

            //Pad Data
            CUDA_CALL(cudaMemcpyAsync(h_padded_signal + 0, h_signal, SIGNAL_SIZE * sizeof(Complex), cudaMemcpyHostToHost, stream));
            memset(h_padded_signal + SIGNAL_SIZE, 0, (padded_data_size - SIGNAL_SIZE) * sizeof(Complex));
            //CUDA_CALL(cudaMemsetAsync(h_padded_signal + SIGNAL_SIZE, 0, (padded_data_size - SIGNAL_SIZE) * sizeof(Complex), stream));

            CUDA_CALL(cudaMemcpyAsync(h_padded_filter_kernel + 0, h_filter_kernel + minRadius, maxRadius * sizeof(Complex), cudaMemcpyHostToHost, stream));
            /*CUDA_CALL(cudaMemsetAsync(h_padded_filter_kernel + maxRadius, 0, (padded_data_size - FILTER_KERNEL_SIZE) * sizeof(Complex), stream));*/
            memset(h_padded_filter_kernel + maxRadius, 0, (padded_data_size - FILTER_KERNEL_SIZE) * sizeof(Complex));
            CUDA_CALL(cudaMemcpyAsync(h_padded_filter_kernel + padded_data_size - minRadius, h_filter_kernel, minRadius * sizeof(Complex), cudaMemcpyHostToHost, stream));

            // MemCpy H to D
            CUDA_CALL(cudaMemcpyAsync(d_signal, h_padded_signal, sizeof(Complex) * padded_data_size, cudaMemcpyHostToDevice, stream)); //Signal
            CUDA_CALL(cudaMemcpyAsync(d_filter_kernel, h_padded_filter_kernel, sizeof(Complex) * padded_data_size, cudaMemcpyHostToDevice, stream)); //Kernel

            //COMPUTE FFT
            CUDA_FFT_CALL(cufftExecC2C(plan, (cufftComplex*)d_signal, (cufftComplex*)d_signal, CUFFT_FORWARD)); // Transform signal
            CUDA_FFT_CALL(cufftExecC2C(plan, (cufftComplex*)d_filter_kernel, (cufftComplex*)d_filter_kernel, CUFFT_FORWARD)); // Transform kernel
            ComplexPointwiseMulAndScale << <64, 1, 0, stream >> > (d_signal, d_filter_kernel, padded_data_size, 1.0f / padded_data_size); // Multiply and normalize
            CUDA_CALL(cudaGetLastError());
            CUDA_FFT_CALL(cufftExecC2C(plan, (cufftComplex*)d_signal, (cufftComplex*)d_signal, CUFFT_INVERSE)); // Transform signal back

            // Copy device memory to host
            CUDA_CALL(cudaMemcpyAsync(h_convolved_signal, d_signal, sizeof(Complex) * padded_data_size, cudaMemcpyDeviceToHost, stream));

            //END Graph Recording
            CUDA_CALL(cudaStreamEndCapture(stream, &graph));
            CUDA_CALL(cudaGraphInstantiate(&instance, graph, NULL, NULL, 0));
            graphCreated = true;
        }
        else
        {
            CUDA_CALL(cudaGraphLaunch(instance, stream));
            CUDA_CALL(cudaStreamSynchronize(stream));
        }
        //verify results
        for (int i = 0; i < SIGNAL_SIZE; i++)
            std::cout << "index: " << i << ", fft: " << h_convolved_signal[i].x << std::endl;
    }

    //Destroy CUFFT context
    cufftDestroy(plan);

    // cleanup memory
    cudaStreamDestroy(stream);
    free(h_signal);
    free(h_filter_kernel);
    free(h_padded_signal);
    free(h_padded_filter_kernel);
    cudaFree(d_signal);
    cudaFree(d_filter_kernel);

    return 0;
}

PROBLEM: The Output of the above program is below, in which it can be seen that the values of the result are also ZEROS for the first iteration. How can I resolve this?
Answer: The results are zero for the first iteration, because for the first iteration, the work is all issued in capture mode.
In capture mode, no CUDA work actually gets done.  From here:

When a stream is being captured, work launched into the stream is not enqueued for execution.

I pointed you to this same area of the documentation in a comment to your last question.  You might wish to read the entire programming guide section on graphs, and there are also blogs available.
Comment: Thanks for pointing it out again. I did read the blog a few times (always take your suggestions seriously) but somehow just skipped from my mind....Thanks again :)


How to plot complicated graphs? (applied-mathematics for physicists)

Question: I'm studying Electrical & Computer Engineering and I'm amidst my preparation for an exam in applied-mathematics for physicists.
I can't quite put the finger on how to plot "by hand" some complicated graphs and was wondering if anyone could share some of their knowledge on how to begin dealing with such functions.
Here are some examples:
$$
f(x)=\arctan(e^x)\\
g(x)=\tanh(\frac1x)\\
h(x)=\ln(\cos(x))\\
k(x)=\ln(e^x-1)\\
$$
Any help would be much appreciated.
Comment: You know that $y=e^x$ is always positive, increasing and concave up. You know that $\arctan$ only gives values between $\pm\frac{\pi}{2}$ so you should expect $y=\arctan\left (e^x\right)$ to approach a horizontal asymptote $y=0$ as $x\to-\infty$ and a horizontal asymptote $y=\pi/2$ as $x\to+\infty.$
Comment: Are you asking how to plot these functions "by hand"?  There are of course calculators that will plot these functions, online software packages, etc.  It isn't clear how this might be connected with your exam preparation.
Comment: Yes, I am asking how to plot these functions by hand.
Comment: Okay here are couple of things you should do: evaluate the behavior of your function at $-\infty ,+ \infty ,0$. Also try to find extrema/critical points by differentiation.
Comment: I'm familiar with all the elementary graphs (hyperbolic functions included). It's just that I don't understand what are the steps that I should be taking to sketch such a graph. Lets say I can sketch $e^x$ which is rather simple, how does it affect the way $\arctan$ behaves?
Comment: When you took calculus you learned that functions were increasing when their first derivative is positive, concave up when second derivatives were positive, etc. If plotting by hand you should make use of the techniques you learned in algebra, trigonometry and calculus.
Comment: Thanks John.
I am familiar with the way functions behave at their limits and what their cycle is (in case there is one).
But I still can't quire understand how to sketch a graph based on that information. If we take a look at $\ln(\cos(x))$, I am well aware that $\cos(x)>0$ is a requirement. From that I can conclude that every cycle will be a repetition of the graph in between $[\frac{-\pi}2,\frac{\pi}2] \pm 2\pi*k$ but I still don't understand how $\ln(\cos(x))$ behaves in this range.
Comment: You know it will be symmetrical wrt the $y$-axis because $\cos(x)$ is. It will h ave vertical asymptotes at $\pm\pi/2$. It will be concave down over the entire interval $(-\pi/2,\pi/2)$ and contain the origin as its maximum point.
Answer: All your examples involve composition of two functions. There are a number of things which will assist you in sketching such graphs by hand. This in not an exhaustive list:
(1) Determine the domain and range of the functions. For example, on $\ln(\cos(x))$ you know that $x$ can be any real number but $\cos(x)$ will always have a value between $\pm1$. You know that the domain of $\ln$ is the positive real numbers, so $y=\ln(\cos(x))$ will only be defined for value of $x$ for which $\cos(x)>0$. You know that $\ln(1)=0$ and that for $0<x<1$, $\ln(x)<0$  and that $\ln(x)\to-\infty$ as $x\to0^+$.
(2) Try to determine any $x$ or $y$ intercepts of the graph
(3) Try to decide if there are any vertical or horizontal asymptotes
(4) Try to decide if there are some intervals where the graph is positive and some where it is negative.
(5) Find the first and second derivatives to find out where the graph is increasing, decreasing, concave up, concave down.
(6) Check for symmetry. Is $f(-x)=f(x)$? Is $f(-x)=-f(x)$?
(7) Plot a few points
Answer: For example, let's try $f(x) = \ln(\cos(x))$ for $-\pi/2 < x < \pi/2$ (as you mentioned, the full graph consists of translates of this on every interval $(2n-1/2) \pi < x < (2n+1/2) \pi$).
Symmetry: $f(-x) = f(x)$.  So it suffices to plot for $0 \le x < \pi/2$ and reflect across the $y$ axis.
$f(0) = \ln(1) = 0$.
$\lim_{x \to \pi/2} f(x) = \lim_{t \to 0+} \ln(t) = -\infty$.
$f'(x) = -\tan(x)$  This is decreasing on $(0, \pi/2)$, $0$ at $x=0$ and tending to $-\infty$ as $x \to \pi/2-$.  Thus $f$ is decreasing and concave on $(0, \pi/2)$.
Answer: Each of your "outer" functions—$\arctan$, $\tanh$, and $\ln$—is strictly monotone. You therefore obtain a graph of each type
$$
y = \arctan \phi(x),\qquad
y = \tanh \phi(x),\qquad
y = \ln \phi(x),
$$
by graphing $y = \phi(x)$, then suitably distorting in the vertical direction, sending $(x, y)$ to $(x, \arctan y)$, etc.

For $\arctan$, the plane is squeezed into the strip $|y| < \pi/2$. Points where $|\phi(x)|$ is large are mapped to points near $y = \pm\pi/2$. Points where $|\phi(x)|$ is small do not move much, because $\arctan y \approx y$ if $y \approx 0$.
The function $\tanh$ is similar, except it squeezes the plane into the strip $|y| < 1$.
The logarithm stretches the open half-plane $y > 0$ onto the entire plane; the half-plane $y > 1$ maps to the upper half-plane, and the strip $0 < y < 1$ maps to the lower half-plane. Any portion of the graph of $\phi$ lying on or below the $x$-axis disappears, and points where $\phi(x) = 0$ become vertical asymptotes. Every point moves downward since $\ln y < y$ for all $y > 0$. Visually, the result looks as if you've melted the plane so that the $x$-axis has "dropped to height $-\infty$".


Instanciar classe fora do namespace

Question: Tenho uma classe com o namespace definido:
namespace App;
class AppSessionHandler {
    private $db;
    //...
    $this->db = Utils::ZendDB();  >>>>>> LINHA 12
}

O seguinte erro ocorre:

Class 'App\Utils' not found in /Class/Utils/class.AppSessionHandler.php on line 12

A classe Utils não está incluída em nenhum namespace.
Como instancia-la dentro da classe AppSessionHandler?
Answer: Por estar dentro do namespace App ao instanciar a classe Util o PHP está procurando pela classe App\Util, que não existe. É preciso especificar que na verdade você deseja utilizar a classe Util.
Isso pode ser feito de duas formas:
Importe essa classe utilizando use
<?php

namespace App;

use Utils;

class AppSessionHandler {

    private $db;

    //...

        $this->db = Utils::ZendDB();
}

Ou referencie o nome completo da classe a partir do escopo global (\):
<?php
namespace App;

class AppSessionHandler {

    private $db;

    //...

        $this->db = \Utils::ZendDB();
}

Caso você vá utilizar a classe Util em outros métodos da classe, o primeiro método é mais eficiente. No seu exemplo você está importando a classe Util, mas essa poderia ser uma classe de outro namespace como Zend\Db\Connection\Utils. Utilizar o use simplifica as proximas utilizações na classe pois não será necessário usar o nome completo da classe:
<?php

namespace App;

use Zend\Db\Connection\Utils;

class AppSessionHandler {

    //...

        $this->db = Utils::ZendDB();
}

Se for utilizar essa classe somente uma vez, o nome completo a partir do global \ já resolve. Porém não fica tão claro no inicio da classe a sua dependência com a classe Utils
Mais informações de como trabalhar com namespaces você pode consultar na documentaçãoen.
Comment: Só fiz uma correção no seu código, não é "using" e sim "use".
Comment: Depois de aprender este básico para uso de outros Namespaces, Filipe Moraes, veja com atenção a PSR-0 e PSR-4
Comment: ao colocar \NomeDaClasse (a barra no inicio) isso indica o que? Que não há namespace?
Comment: Filipe, enriqueci a resposta com mais alguns detalhes.

Instanciar classe fora do namespace


Como fazer form filho alterar valores no form pai C#?

Question: Tenho um cadastro em C#. Existe um botão "pesquisa rua" que abre um form filho de pesquisa. Ao se executar a pesquisa, apresenta o resultado no datagrid desse form filho. Gostaria que o evento cell_click do datagrid completasse a combobox existente no form pai.
Answer: É possível resolver o seu problema passando a referência do pai para o filho. Imagino que você cria uma instância dessa Form filha dentro da Form pai, sendo assim, basta passar a referência da seguinte forma:
Na Form pai
FormFilha container = new FormFilha(this);

Na Form filha
private FormPai parent = null;
public FormFilha(FormPai _parent){
  this.parent = _parent;
}

A partir daí é possível controlar a Form pai de dentro da Form filha, inclusive elementos que estejam internos a FormPai, como o ComboBox por exemplo, desde que a referência para esse elemento tenha nível de encapsulamento public.
Comment: quando digito o `this` em `new FormFilha(this)`, recebo um erro: "Keyword 'this' is not available in the current context.".
Answer: Nesse caso você pode passar o form pai como parâmetro para a classe, e através desse parâmetro (no caso o objeto do form pai) você pode interagir com o form pai.
Codigo do Form1:
public Form1()
{
       InitializeComponent();
}
    //botao que ABRE o FORM B
private void button1_Click(object sender, EventArgs e)
{
    Form2 formB = new Form2(this); //this, significa que estou passando ESSA classe (instância dela) como param
    formB.Show();
}

Codigo do Form2:
public partial class Form2 : Form
{
    Form1 instanciaDoForm1; //objeto do tipo FORM 1, que será usado dentro da classe
    //inicializador do FORM
    public Form2(Form1 frm1) //recebo por parametro um objeto do tipo FORM1
    {
        InitializeComponent();
        instanciaDoForm1 = frm1; //atribuo a instancia recebida pelo construtor a minha variavel interna
        //associo o mesmo texto do tbxTextBoxFormA ao meu FORM B
        txtTextBoxFormB.Text = instanciaDoForm1.txtTextBoxFormA.Text.ToString();
    }
    //botao alterar
    private void button1_Click(object sender, EventArgs e)
    {
        //passo para a textbox do FORM A o mesmo texto que está na minha do FORM B
        instanciaDoForm1.txtTextBoxFormA.Text = txtTextBoxFormB.Text.ToString();
        instanciaDoForm1.txtTextBoxFormA.Refresh(); //recarrego ela
    }
}

Assim é possível interagir com o grid da mesma forma que foi feita com o textbox.
Artigo adaptado do meu amigo Fernando Passaia
http://www.linhadecodigo.com.br/artigo/1741/trocando-informacoes-entre-windows-forms-em-csharp.aspx
Answer: Não é uma boa prática delegar essa responsabilidade para o formulário filho. Em geral seria responsabilidade do formulário pai (que contém o combobox) modificar o conteúdo deste combo. Você pode criar o formulário filho como uma fonte de dados (o trabalho dele seria listar os itens e dizer qual foi selecionado)
Ao exibir o formulário com um "ShowDialog" você recebe um enum com o resultado daquele form (OK, Cancelar, etc) e pode usar esta flag para saber se o usuário não fechou a tela sem selecionar nada.
Para obter o item selecionado você pode, através de propriedades, expor o conteúdo do form filho. Isso permite que esse formulário filho seja utilizado por qualquer formulário pai.
public class Cidade
{
    public string Nome { get; set; }
}

public partial class FormPai : Form
{
    private void btnObterCidade_Click(object sender, EventArgs e)
    {
        var seletorCidade = new SeletorCidade();
        var resultadoSeletor = seletorCidade.ShowDialog();

        if (resultadoSeletor == DialogResult.OK)
        {
            var cidadeSelecionada = seletorCidade.CidadeSelecionada;
            comboCidade.SelectedItem = cidadeSelecionada;
        }
    }
}

public partial class SeletorCidade : Form
{
    public Cidade CidadeSelecionada { get; set; }

    private void btnOk_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
    }

    private void btnCancelar_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.Cancel;
    }
}

Answer: Uma boa maneira de fazer isso em C# é criar um evento no Form filho.
Por exemplo:
public event Action<String> EnderecoSelecionado;

Quando você criar o Form filho no Form pai, você se registra neste evento:
formFilho.EnderecoSelecionado += enderecoSelecionado_event;

Quando o usuário clicar no grid do Form filho, você verifica se existe funções registradas no evento, se houver você o executa:
if( EnderecoSelecionado != null ) {
    EnderecoSelecionado( o_endereco_selecionado );
}

Desta forma a interface entre Pai e Filho ficará bem explicita e o mesmo evento pode ser reaproveitado em outras partes da sua aplicação.
Este é uma expressão idiomatica comum do C# e poucas vezes me arrempedi de usa-la.
Answer: O jeito mais fácil de fazer isso é criar uma variável publica no FormFilho e usar o ShowDialog() para chamaer ele com o DialogResult, assim, quando clicar no datagrid vc chama este código:
Declaração no formFilho
public int codigo { get; set; }

Comando do click
codigo = valor;
DialogResult = DialogResult.OK;

Chamada do formFilho no FormPai
Form2 formFilho = new Form2();
if (formFilho.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
     comboBox1.SelectedValue = formFilho.codigo;
}

Answer: Pra mim funcionou assim.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    // no meu caso quis pegar um Objeto do form filho.
    private Cliente cliente = null;
    public Cliente Cliente {
        get { return cliente; }
        set { cliente = value; }
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        Form2 filho = new Form2();
        filho.Pai = this;
        filho.Show();
        Visible = false;
    }
}

Agora no Form filho.
public partial class Form2 : Form
{
    public Form2
    {
        InitializeComponent();
    }

    private Form1 pai = null;
    public Form1 Pai {
        get { return pai; }
        set { pai = value }
    }

    private void Button1_click(object sender, EventArgs e)
    {
        Cliente cliente = new Cliente(long.parse(textBox1.Text));
        pai.Cliente = cliente;
        pai.Visible = true;
        this.Close();
    }
}

desta forma eu chamo o filho, passo o pai para um atributo dentro do filho e retorno um objeto para o form pai.
tentei de outras formas porém no meu Visual Studio 2017 essas outras formas estavam iniciando um Form vazio que não era o que eu estava iniciando.
e na hora de passar o Objeto do Filho para o pai, estava dando um erro de estância nula(null).
espero ter ajudado.
Answer: Você pode fazer via Eventos / delegados [a qual acho mais robusto], retorno de valores com variável estática em classe terceira, passagem do formulário via argumento para alteração de propriedades e, também há uma possibilidade que ninguém cita - acho que é a mais complicada - você PODE acessar a informação diretamente através da lista de formulários abertos [Application.OpenForms], encontrá-lo e alterar a propriedade.
O Ponto negativo é, se você mudar o nome do controle ou formulário, terá que alterá-lo também no código, tornando mais complicado a manutenção.
Fiz um projeto de exemplo para ficar mais simples o entendimento:

frmMain - formulário Pai
frmSearch - form pesquisa
No frmMain, crio um TextBox, com nome txtEx
Chamo o formulário Pesquisa frmSearch . Aberto o frmSearch , chamo o clique de botão e nele Tento alterar o controle pai:

Exemplo:
// Inicio
private void button1_Click(object sender, EventArgs e)
    {
        TextBox myText = (TextBox)Application.OpenForms["frmMain"].Controls["txtEx"];

        myText.Text = "10";

        this.Dispose();
    }

Pronto, quando retorno ao formulário frmMain, o valor "10" está escrito no TextBox.
Tenha cuidado, se você errar o nome do formulário ou do controle, irá se deparar com o lançamento de um System.NullReferenceException. Trate este código.
Uso:
// Acesse: Application.OpenForms["NomeDoFormulário"]  e Controls["NomeDoControle"]
// Declara um controle TextBox, que servirá de ponteiro para o seu controle no formulário pai
// Faz a Conversão explícita de tipo de Controle (para poder alterar as propriedades) [(TextBox) ObjetoXYZ]
TextBox myText = (TextBox) Application.OpenForms["frmMain"].Controls["txtEx"];

// Altera de fato a propriedade
myText.Text = "XYZ";

// Encerra seu formulário Filho
this.Dispose();

Simplificando:
(Application.OpenForms["frmMain"].Controls["txtEx"] as TextBox).Text = "Meu valor";


Simulating and estimating a mixed effects model: poor estimates of time fixed effects

Question: I am simulating data from a basic mixed effects model
$$
y_{it}=\alpha_i+\beta_t+\gamma x_{it}+\varepsilon_{it}.
$$
I then estimate a corresponding fixed effects model on the simulated data. I get good estimates for individual fixed effects but poor estimates for time fixed effects. Why could that be?
(Actually, the estimates of fixed effects are all biased. I am not worried about that as I think the location is not identified.)

R code:
#---------- Simulation

# Set the number of individuals and the number of time periods:
n=100; T=100

# Generate parameter values:
set.seed(1); alphas=runif(n=n,min=-1,max=1)
set.seed(2); betas =runif(n=T,min=-1,max=1)
             gamma =1

# Generate covariate x and error term eps
set.seed(3); x     =rnorm(n=n*T); X  =matrix(x  ,nrow=n,byrow=TRUE)
set.seed(4); eps   =rnorm(n=n*T); Eps=matrix(eps,nrow=n,byrow=TRUE)

# Obtain the dependent variable y
Y=matrix(NA,ncol=T,nrow=n)
for(i in 1:n){
 for(t in 1:T){
  Y[i,t]=alphas[i]+betas[t]+gamma*X[i,t]+Eps[i,t]
 }
}
y=c(t(Y))

# Create identifiers of individuals (obj) and time periods (time)
obj =c(1,rep(0,T-1)); obj =rep(obj,n); obj =cumsum(obj)
time=c(1:T); time=rep(time,n)

#---------- Fixed effects estimation

# Estimate by accounting for the individual heterogeneity using a FE model
m3=lm(y~-1+factor(obj)+factor(time)+x)
summary(m3)
# Extract estimates of individual and time fixed effects
alphas_hat3=m3$coef[1:n]
betas_hat3 =m3$coef[(n+1):(n+T)]
cor(alphas,alphas_hat3)^2
cor(betas, betas_hat3 )^2
# Plot them against the true parameter values
dev.new(); mar1=c(4,4,3,0.5); par(mfrow=c(2,1),mar=mar1)
 plot(x=alphas,y=alphas_hat3,xlab="true",ylab="fitted",main="Individual fixed effects"); abline(a=0,b=1)
 plot(x=betas ,y=betas_hat3 ,xlab="true",ylab="fitted",main="Time fixed effects"      ); abline(a=0,b=1)
par(mfrow=c(1,1))

Comment: Related: https://stats.stackexchange.com/questions/593605
Answer: In theory, the columns of the design matrix of m3 would be linearly dependent since the sum of the column vectors identifying the objects and the sum of the the column vectors identifying the time points both equal $\mathbf{1}_{n\cdot T}$. However,  lm calls model.matrix internally, which in turn drops one column$-$in this case the one indicating time point 1$-$to generate a design matrix of full column rank. But this means that m3 contains the estimated coefficients of a model without $\beta_1$ (i.e., in which $\beta_1$ is forced to equal zero).
The new parameters in terms of the original parameters are given by
$$
\tilde{\alpha}_i = \alpha_i + \beta_1 \;\;\forall\, i \in \left\{1,\ldots,n\right\},\\
\tilde{\beta}_t = \beta_t - \beta_1 \;\;\forall\, t \in \left\{2,\ldots,T\right\}.
$$
One could therefore consider something like
alphas_hat3 <- m3$coef[1:n] - betas[1]
betas_hat3 <- m3$coef[(n+1):(n+T-1)] + betas[1]
betas <- betas[-1]

which, with your seeds, yields
cor(alphas, alphas_hat3)^2
# 0.984594
cor(betas, betas_hat3)^2
# 0.98608

and the following plot

Other seeds also generate plots in which the estimated coefficients are more evenly spread around the identity line.
Comment: Perfect, thank you! If you have time, perhaps you could also help me with a related one: https://stats.stackexchange.com/questions/593605?


Mudar status de acordo com a data

Question: Estou com uma tremenda dúvida de como eu poderia resolver/criar a solução.
Eu poderia fazer manualmente criando um select do lado e mudando o status da corrida após submit, mas a ideia é a seguinte:
Como eu posso criar uma condição, seja ela no back-end/php  que ao chegar a data mencionada mudar/preencher o STATUS para "CORRIDA EFETUADA".
Meu banco existem os 2 campos abaixo:

No BD:
date type: varchar;
status: varchar;

Campos html:

    1° - Data e Hora
    <input type="datetime-local" name="dt_corrida1" id="data_corrida"
        class="form-control" value="<?php echo $row[0]['dt_corrida1']; ?>"
        placeholder="Data Corrida">

    STATUS
    <input type="text" name="status" id="status" class="form-control"
        value="<?php echo $row[0]['status']; ?>">

EDIT:
Imagem de como está no banco de dados. O Type não está como datetime porque eu não consegui trazer a informação no input com a type "datetime-local", somente com varchar.

Informação registrada no BD:

INPUTS:
DATA CORRIDA VINDO DO BD puxando a partir da row.
<input type="datetime-local" name="dt_corrida1" id="data_corrida" class="form-control" value="<?php echo $row[0]['dt_corrida1']; ?>"  placeholder="Data Corrida">

STATUS:
<input readonly type="text" name="status" id="status" class="form-control" value="">

EDIT IMAGEM DOS INPUTS E STATUS - troquei os ids que foi solicitado e o js substitui conforme editado.

Obrigado desde já!
Answer: Dai você adiciona para não perder o input do data_corrida, creio que vc já fez isso no $row[0]['dt_corrida1'];, mas enfim faz uma function que ao carregar ela é executada. O modelo em que fica o input type datetime-local é ANO-MÊS-DIATHORA:MINUTOS, dai pega o ano atual, o mês atual, o dia atual, a hora atual e os minutos atuais, e transforma em tudo em uma string do mesmo modelo que fica no input, compara e quando eles forem iguais aparece o "CORRIDA EFETUADA". A e adicionei a tag readonly no input do status, para quem estiver acessando não conseguir digitar nele.
Edição:
Utilize o slice() para "recortar" a string e pegar o ano, mes, dia... e faz que quando a data atual seja maior apareça o "CORRIDA EFETUADA", e se ainda a data não chegou o status fica vazio.

function compararData(){
var data = new Date();
var month = data.getUTCMonth() + 1;
var day = data.getUTCDate();
var year = data.getUTCFullYear();
var hour = data.getHours();
var min = data.getMinutes();
if (min < 10) {
   min = "0" + min
}
if (day < 10){
    day = "0" + day
}
if (month < 10){
    month = "0" + month
}

agora = year + "-" + month + "-" + day + "T" + hour + ":" + min

for (let i =1; i<=15; i++){
dataCorrida = document.getElementById('data_corrida'+i)
StatusCorrida =  document.getElementById('status'+i)

    if (dataCorrida.value.length >= 16) {
    if (dataCorrida.value == agora){
        StatusCorrida.value = "CORRIDA EFETUADA"
    }
    if (year > dataCorrida.value.slice(0,4)){
            StatusCorrida.value = "CORRIDA EFETUADA"
    }
    if (dataCorrida.value.slice(0,4) == year && month > dataCorrida.value.slice(5,7)){
            StatusCorrida.value = "CORRIDA EFETUADA"
    }
    if (dataCorrida.value.slice(0,4) == year && dataCorrida.value.slice(5,7) == month && day > dataCorrida.value.slice(8,10)){
            StatusCorrida.value = "CORRIDA EFETUADA"
    }
    if (dataCorrida.value.slice(0,4) == year && dataCorrida.value.slice(5,7) == month && dataCorrida.value.slice(8,10) == day && hour > dataCorrida.value.slice(11,13)) {
           StatusCorrida.value = "CORRIDA EFETUADA"
    }
    if (dataCorrida.value.slice(0,4) == year && dataCorrida.value.slice(5,7) == month && dataCorrida.value.slice(8,10) == day && dataCorrida.value.slice(11,13) == hour && min > dataCorrida.value.slice(14,16)) {
           StatusCorrida.value = "CORRIDA EFETUADA"
    }
    }
    }
    setInterval(compararData,500)
}

        1° - Data e Hora
        <input type="datetime-local" name="dt_corrida1" id="data_corrida1" class="form-control"  placeholder="Data Corrida">

        STATUS
        <input readonly type="text" name="status" id="status" class="form-control" value="">

OBS: Retirei os trechos em PHP só para vc testar ai no Stack
espero ter ajudado
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](https://chat.stackexchange.com/rooms/118037/discussion-on-answer-by-noface-mudar-status-de-acordo-com-a-data)

Mudar status de acordo com a data


Multiple SPNEGO authenticated web servers on one host name

Question: I was trying to set up a Java service using the SPNEGO servlet filter and a listen port of 8080 for authentication on a host that is also running web applications hosted in IIS7.
I followed the SPNEGO installation instructions and created an SPN for HTTP/canonical.host.name, bound to the user performing the authentication for the Java service.
After this change, the Java service is able to authenticate clients via SPNEGO, but IIS7 application pools running with custom identities (i.e. user names instead of ApplicationPoolIdentity) are suddenly unable to authenticate.
What I don't understand here:

How does Kerberos authentication work for IIS when there is no SPN for HTTP/canonical.host.name defined using (as checked via setspn -Q)? Clients still request and receive tickets for exactly this SPN.
Out of interest, we tried running the application pools with the identity of the Java service that successfully authenticates. It still did not work as long as the SPN was defined - attempts to authenticate with a Kerberos ticket failed with a KRB_AP_ERR_MODIFIED returned. Running the application pool as the user that the SPN was registered to did not change this behaviour.
Microsoft specifies SPNs to include a port number, but IE does not conform to this and never sends a port number in the SPN (Firefox and Chrome follow in this behaviour).

So, is there any way to have multiple independent SPNEGO authenticated services on the same host?
Answer: Last first: For multiple SPNEGO-authenticated services on the same host, without fiddling with IE registry keys, use different names.

•How does Kerberos authentication work for IIS when there is no SPN for HTTP/canonical.host.name defined using (as checked via setspn -Q)? Clients still request and receive tickets for exactly this SPN.

This is an automatic fallback based on the HOST\boxname SPN , which is created for all computers at domain join time - if the DC doesn't find a match for SPECIFICSERVICE\boxname as requested by the client application, it'll provide a ticket based on HOST\boxname.
Use SETSPN -L boxname to list the SPNs associated with a security principal (user or computer account).

•Out of interest, we tried running the application pools with the identity of the Java service that successfully authenticates. It still did not work as long as the SPN was defined - attempts to authenticate with a Kerberos ticket failed with a KRB_AP_ERR_MODIFIED returned. Running the application pool as the user that the SPN was registered to did not change this behaviour.

The default for IIS 7 is with useAppPoolCredentials=false, and useKernelMode=true ; one or both of these have to be toggled in order for the app pool identity to be used to decode kerberos tickets.

•Microsoft specifies SPNs to include a port number, but IE does not conform to this and never sends a port number in the SPN (Firefox and Chrome follow in this behaviour).

And coming back to the real crux of the matter: when everything else is fixed, IE and others still won't include port numbers by default, so the least-modification solution is simply to run different host headers on the same box.
Note also that due to another IE behaviour (with the same argument against changing all your clients' registry settings), CNAMEs aren't a good choice, use A records instead.
More here and here and to a lesser extent, here.
Answer: Have you got the reg keys from this KB http://support.microsoft.com/default.aspx?scid=kb;EN-US;908209 configured on the client? Else IE wont request the correct ticket. Just to be clear, the reg keys came with IE6+hotfix but apply to all versions of IE since then.
I am not sure I understand your configuration. Is the HTTP/canonical.host.name SPN configured on the service account used for the "Java service"?
You can have multiple services running on the box using different identities. So you can have a service called HTTP/host1.host.name and HTTP/host2.host.name both on the same host. You may register the SPNs involved on the same service account or different service accounts if you so choose.
Requests for HTTP SPN are mapped to objects with the HOST based SPN if the HTTP SPN is not explicitly set anywhere. This mapping happens by the SPNMappings attribute on an object that looks like CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=forest1,DC=local (forest1.local is forest name here) as per http://msdn.microsoft.com/en-us/library/cc220898(v=PROT.13).aspx.
Tristan's blogs are great. You might also find the troubleshooting blogs and other kerberos related blogs at http://blogs.technet.com/b/askds/archive/tags/kerberos/ useful.
Comment: Thanks. I had a good chuckle at the "we fixed it in IE6, but let IE7 and IE8 revert to unfixed unless you set an obscure registry key" behaviour, that's classic Microsoft. Details on failure mode added.
Comment: Tristan's answer is spot on. I will just add some further clarification which may help.


Como retornar uma lista em que o tamanho é definido de acordo com um número digitado no input em python?

Question: Gostaria que o código que escrevi me retorne uma quantidade de tuplas de acordo com o valor inserido no input, por exemplo, se o input é 3, o retorno terá que ser 3 pares de tuplas. A imagem a seguir deixará mais claro.

Aqui o meu código:
"""Números primos gêmeos são pares de números primos (p1, p2) tais que p2=p1+2.

Implemente uma função chamada primos_gemeos que recebe um número inteiro n e
retorna os n primeiros pares de números primos gêmeos, conforme formatação indicada abaixo."""
def primos_gemeos(num):
  valor = False
  for n in range(2, num):
     if num % n == 0:
        break
  else:
     valor = True
  return valor

entrada = int(input())
i = 0
lista = []
while i < entrada:
  for j in range(3, entrada + 1, 2):
     if primos_gemeos(j) and primos_gemeos(j + 2):
        lista.append((j, j + 2))
        i += 1
print(lista)

primos_gemeos(entrada)

No meu código o que tentei fazer foi um while que repete enquanto i < entrada e incrementa 1 após o append, porém o retorno está repetindo os pares, por exemplo, quando a entrada é 3, a saída teria que ser assim:
[(3, 5), (5, 7), (11, 13)]
Mas na saída do meu código está sendo assim:
[(3, 5), (3, 5), (3, 5)]
Onde eu errei?
Answer: Um dos problemas do código (e talvez o único, sem ter testado) é não estares a alterar (incrementar) o valor de j, por isso acabas sempre com os mesmos valores.
O que são Números Primos Gémeos?
Uma implementação pode ser feita assim:
def e_primo(num): # verificar se e primo
    return all(num%i!=0 for i in range(2,num))

qtd_tuples = 10 # input
results = [] # armazenar resultados
curr_prime = 1
while len(results) < qtd_tuples: # enquanto a quantidade de tuplas for inferior ao nosso input
    curr_prime += 2
    if(e_primo(curr_prime) and e_primo(curr_prime+2)):
        results.append((curr_prime, curr_prime+2))

print(results)

Output:
[(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), (59, 61), (71, 73), (101, 103), (107, 109)]

DEMONSTRAÇÃO
Answer: Fazer um teste de mesa já faria com que você percebesse o erro: entrada é a quantidade de pares que você deve retornar, mas no for você está usando range(3, entrada + 1, 2), ou seja, esse for só verifica os números até entrada.
Portanto, quando entrada é 3, o range só vai até 3, e dentro do for, como você testa j e j + 2, nesse caso sempre estará testando apenas 3 e 5.
Então na verdade você deveria usar entrada apenas para controlar a quantidade de pares já gerados. Já os números a serem testados não devem ter limite, pois você não sabe qual o número que estará no enésimo par.
Outros pontos a melhorar é que você pode começar no 3 (pois eu sei que (2, 3) não são primos gêmeos). E o algoritmo dá para melhorar um pouco: como eu já começo excluindo o 2, não preciso testá-lo, e também não preciso testar os números pares. Além disso, a partir do 5, todos os números primos são da forma 6k - 1 ou 6k + 1 (ou seja, são antecessores ou sucessores de um múltiplo de 6), então posso verificar apenas esses valores. E o loop pode ir até a raiz quadrada do número.
Então ficaria:
from math import sqrt

# ATENÇÃO: **nesse caso específico**, como eu não testo o 2,
# estou deliberadamente ignorando ele e os demais números pares
def primo(n):
    if n == 3:
        return True
    if n % 3 == 0:
        return False

    i = 5
    limite = int(sqrt(n)) + 1
    while i < limite:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6

    return True

quantidade = int(input())
lista = []
# começo no 3, pois sei que (2, 3) não são gêmeos
n = 3
while True:
    if primo(n) and primo(n + 2):
        lista.append((n, n + 2))
        if len(lista) == quantidade: # se já tenho a quantidade de pares, interrompe o while
            break
    n += 2

print(lista)

Atenção: Como eu só chamo a função primo passando números ímpares, então dentro dela eu não verifico se o número é par. Mas se fosse uma função de uso geral, para verificar se qualquer número é primo, aí teria que verificar (ficaria assim).

Só tem um detalhe: veja que no while eu testo n e n + 2.
Isso quer dizer que na primeira iteração eu testo se 3 e 5 são primos. Depois, na segunda iteração, eu testo se 5 e 7 são primos, depois eu testo 7 e 9, depois 9 e 11, etc. Repare que há vários números sendo testados 2 vezes, sem necessidade. Então você pode otimizar um pouco, fazendo com que eles sejam testados apenas uma vez, e reaproveitar esta informação na próxima iteração:
lista = []
proxPrimo = None
# começo no 3, pois sei que (2, 3) não são gêmeos
n = 3
atualPrimo = primo(n)
while True:
    proxPrimo = primo(n + 2)
    if atualPrimo and proxPrimo:
        lista.append((n, n + 2))
        if len(lista) == quantidade:
            break
    atualPrimo = proxPrimo
    n += 2

print(lista)

Comment: Muito bom. Presumo que possamos descartar também os pares logo? https://ideone.com/CheTnL
Comment: @Miguel Nesse caso específico, como estou chamando a função `primo` somente para números ímpares, ignorei os pares de propósito (veja o comentário no código: "*como eu não testo o 2, estou deliberadamente ignorando ele e os demais números pares*". Mas para uma função de uso geral, aí sim, deveria testar se o número é par e descartar logo de cara - a única exceção é o próprio 2, então teria que ser assim: https://ideone.com/zlnWdd
Comment: Ha pois claro, claro... Distração minha
Comment: @Miguel De qualquer forma, editei a resposta, deixando mais claro esse ponto. Obrigado!


Newton form of the interpolation polynomial?

Question: Let $ f(x)=\sin(x) $ and let $ p_1 $ be the first degree polynomial that interpolates $ f $ at $0$ and $\pi/2$. Then $ p_1(x)=(2/pi)x. $
How did they get this result; how is $ p_1(x) $ found?
Comment: $f(0)=0$ and $f(\pi/2) = 1$. Take $p_1(x) = ax+b$ and solve $p_1(0) = 0$ and $p_1(\pi/2) = 1$
Comment: Having understood the above comment and the answer, I would add $f(\pi/4) = \sqrt{2}/2$ and try to find $p_2(x) = ax^2+bx+c$.
Answer: $p_1(x)=ax+b$. We want $p_1(0)=f(0)=0$ and $p_1(\pi/2)=f(\pi/2)=1$. Thus, you get $0=b$, $1=a\pi/2+b=a\pi/2$, so $a=2/\pi$.
Comment: How do you get 0=b?
Comment: @user1961722: Evaluate $p_1(0)$...
Comment: But we're trying to find $ p_1(x) $, how can we use it?
Comment: @user1961722: if you are trying to figure out a degree $n$ polynomial you need $n+1$ equations. In your case the degree is 1, so you need 2 equations.
Comment: Okay thanks. Do you know what the general formula is to find a degree $ n $ interpolating polynomial?
Comment: @user1961722: you need $n+1$ different points. The general term for this is Lagrange Interpolation: http://en.wikipedia.org/wiki/Lagrange_polynomial


Create CGContext for CoreText

Question: I was trying to render some CoreText in a CALayer, so that i can adjust the alpha of that layer explicitly.  I tried overriding the drawRect: method but that, as far as i know, only draws on the root layer of the view, and i have two sublayers, a bg image and the CoreText.  Here's the method that attempts to draw the CoreText layer: (which works in drawRect if i remove the createContext code)
-(void) drawTextLayer
{
    //get context
UIGraphicsBeginImageContextWithOptions(CGSizeMake(250.0, 137.0), YES, 1.0);
CGContextRef context = UIGraphicsGetCurrentContext();

//draw text
//attribute string
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:displayTxt];

//get font
NSString *fontPath = [[NSBundle mainBundle] pathForResource:@"idolwild"
                                                     ofType:@"ttf"];

CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)fontPath, kCFURLPOSIXPathStyle, false);
CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(url);
CGFontRef theCGFont = CGFontCreateWithDataProvider(dataProvider);
CTFontRef idolwild = CTFontCreateWithGraphicsFont(theCGFont, 16.0, &CGAffineTransformIdentity, nil);

CFRelease(theCGFont);
CFRelease(dataProvider);
CFRelease(url);

[attrStr addAttribute:(id)kCTFontAttributeName
                value:(id)idolwild
                range:NSMakeRange(0, [attrStr length])];

//create paragraph style and assign text alignment to it
CTTextAlignment alignment = kCTCenterTextAlignment;
CTParagraphStyleSetting _settings[] = {    {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment} };
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(_settings, sizeof(_settings) / sizeof(_settings[0]));

//set paragraph style attribute
[attrStr addAttribute:(id)kCTParagraphStyleAttributeName
                value:(id)paragraphStyle
                range:NSMakeRange(0, [attrStr length])];

[attrStr addAttribute:(id)kCTForegroundColorAttributeName
                value:(id)[UIColor clearColor].CGColor
                range:NSMakeRange(0, [attrStr length])];

[attrStr addAttribute:(id)kCTForegroundColorAttributeName
                value:(id)[UIColor blackColor].CGColor
                range:NSMakeRange(0, [[wordRanges objectAtIndex:currentTextindex] intValue])];

//layout master
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrStr);

//bounding eclipse
CGMutablePathRef boundingEclipse = CGPathCreateMutable();
CGPathAddEllipseInRect(boundingEclipse, NULL, boundingEclipseRect);

//ctframe
CTFrameRef bubbleFrame = CTFramesetterCreateFrame(framesetter,
                                                  CFRangeMake(0, 0),
                                                  boundingEclipse, NULL);

// flip the coordinate system
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

    //fill bg to visual
    CGContextAddPath(context, boundingEclipse);
    [[UIColor greenColor] setFill];
    CGContextFillPath(context);

//draw
CTFrameDraw(bubbleFrame, context);

//add to layer
UIImage *tempImage = UIGraphicsGetImageFromCurrentImageContext();
textLayer.contents = tempImage;

//cleanup
CGPathRelease(boundingEclipse);
CFRelease(framesetter);
CFRelease(bubbleFrame);
CFRelease(idolwild);
CGContextRelease(context);

[attrStr release];
}

--any theory on CALayers and CGContexts is much appreciated
Answer: I can suggest three different methods:

Subclass CALayer and implement its drawInContext:.
Set an object that is not a UIView as the sublayer's delegate, then implement drawLayer:inContext:.
Create a CGImage and set it as the layer's contents:
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();

/// draw

UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

sublayer.contents = (id)image.CGImage;

Comment: i like suggestion #3. One question about the first two suggestion, the drawInContext: method, Does that draw the CALayer as an image into the Context, or does it draw the CALayer using the param context?

Create CGContext for CoreText


Cannot login to turn off maintenance mode after 7.24

Question: I am new to Drupal, and although I managed to understand most of its principles, it seems I broke my site when trying to update it to the latest 7.24 release.
As instructed in UPDATE.txt, I entered maintenance mode and deleted all folders except sites/, which I had backup of course. I then copypasted all the new folders (including .htaccess) to my installation, and tried to run the update script. However, the update script said there were no pending updates. After that, the site was in maintenance mode, and even from my already logged in account I could not turn it off. I tried logging in again, and now I'm stuck in maintenance mode, and /user page redirects me to the main one. I tried emptying the cache tables, but nothing happened. I also tried copying the folders again, with no results. I enabled "update_free_access", and tried running the update script again, but no results.
Is there any way to avoid a blank installation?
Answer: 7.24 has a security update and needs to add or change your .htaccess file for you public and temp files directory.
See what you have to add/change in drupal.org and here. I haven't done the 7.24 update yet so, this is as much i can help.
Answer: If you had previously enabled clean URL's, you may need to uncomment the re-write base again in .htaccess.
Try scrolling down the page, and finding the line, # RewriteBase / then remove the hash.
Or, try accessing your login page via www.yourdomain.com/q?=user
Comment: You tipped me towards the right direction. I have my site on a domain subfolder, so I needed to uncomment the # RewriteBase /drupal line!
Comment: Glad I could help! :-)