Solve matrix equations of the form: $X^T A X = B_1$ and $X A X^T = B_2$

Question: I have trouble solving the following two matrix equations for unknown $X \in \mathbb{R}^{n \times n}$:
$$X^T A X = B_1$$
$$X A X^T = B_2$$
where, $A$, $B_1$ and $B_2$ are all $n \times n$ symmetric matrices such that $A^n = I_n$, and $B_1 \neq B_2$
There is a solution for $X$ if $A$ and the $B$'s are positive-definite, but is there an analytical solution for any matrices?
Edit:
Is there a way to solve this when $A^n \neq I_n$? I'm interested in the case where $A$, $B_1$, $B_2$ and $X$ are matrices of one-to-one mappings, i.e., $A_{ij}=A_{ji}=1$ if $i$ maps to $j$, and $0$ otherwise.
For example: $$A = \begin{bmatrix}
    0 & 1 & 0 & 0 & 0 \\
    1 & 0 & 0 & 0 & 0 \\
    0 & 0 & 0 & 1  & 0\\
    0 & 0 & 1 & 0  & 0\\
    0 & 0 & 0 & 0  & 1
\end{bmatrix}$$
Answer: Here are some observations.

Since $A$ is real symmetric and $A^n=I_n$, it is necessarily equal to $I_n$ when $n$ is odd and it is orthogonally similar to some $I _r\oplus -I_{n-r}$ when $n$ is even. At any rate, when $A=I_n$, the system of equations is solvable if and only if $B_1$ and $B_2$ are positive semidefinite matrices with the same spectrum, and the general solution is given by $X=Q\sqrt{B_1}$ where $Q$ is any orthogonal matrix such that $QB_1Q^T=B_2$.
In general, the system of equations implies that $B_1A=X^TAXA$ and $B_2A=XAX^TA$. Therefore it is solvable only if $B_1A$ and $B_2A$ have the same spectrum.
If we left-multiply the first equation by $XA$ and right-multiply the second one by $AX$, we obtain $XAB_1=XAX^TAX=B_2AX$. Hence $\operatorname{vec}(X)\in\ker\big((B_1A)\otimes I_n-I_n\otimes(B_2A)\big)$.
In relation to points 2 and 3, consider the case where $AB_1$ and $B_2A$ are diagonalisable matrices with a common spectrum $\{\lambda_1,\ldots,\lambda_n\}$ consisting of distinct real eigenvalues. For each $\lambda_i$, let $v_i$ be a corresponding left eigenvector of $AB_1$ and $u_i$ be a corresponding right eigenvector of $B_2A$. Since the $\lambda_i$s are distinct, $\ker\big((B_1A)\otimes I_n-I_n\otimes(B_2A)\big)$ has dimension $n$. Thus the general solution to $XAB_1=B_2AX$ is given by $X=\sum_ic_iu_iv_i^T=U\operatorname{diag}(c)V^T$. Our system of equations can then be rewritten as
$$
\begin{aligned}
\operatorname{diag}(c)A_1\operatorname{diag}(c)&=S_1,\\
\operatorname{diag}(c)A_2\operatorname{diag}(c)&=S_2,\\
\end{aligned}
$$
where
$$
A_1=U^TAU,\quad A_2=V^TAV,\quad S_1=V^{-1}B_1(V^T)^{-1},\quad S_2=U^{-1}B_2(U^T)^{-1}.
$$
That is,
$$
(cc^T)\circ A_1=S_1,\quad (cc^T)\circ A_2=S_2.
$$
Thus a necessary condition for solvability is that $(S_1)_{ij}=0$ whenever $(A_1)_{ij}=0$ and $(S_2)_{ij}=0$ whenever $(A_2)_{ij}=0$. If $A_1$ and $A_2$ happen to be entrywise nonzero, the system of equations is solvable if and only if the entrywise division of $S_1$ by $A_1$ and the entrywise division of $S_2$ by $A_2$ are both equal to some rank-one positive semidefinite matrix $cc^T$.
Comment: Thank you @user1551. What happens when the condition $A^n=I_n$ doesn't apply, instead $A$ is a symmetric matrix that represents a one-to-one mapping, i.e., $A_{ij}=A_{ji}=1$ if $i$ maps to $j$, and $0$ otherwise?
Comment: @Danish Sorry. When $A$ is indefinite, I have no idea yet.
Comment: Can u tell how in point 2, $B_1A$, $B_2A$ have the same spectrum ?
Comment: @Balajisb In general, if $P$ and $Q$ are two square matrices of the same size, $PQ$ and $QP$ have the same spectrum. Now put $P=X^TA$ and $Q=XA$.
Comment: Thanks. I also see: https://math.stackexchange.com/questions/2029376/do-ab-and-ba-have-the-same-eigenvalues


profile 2 module with services module

Question: i am creating a web service for user registration. I just add some fields in user registration form using profile2 module. How can i integrate this with services module. i just want to make a services with the new fields
Answer: I'm assuming you're familiar with Services.  In your endpoint,
Copy the pattern here:
<code>                    array(
                        'name' => 'username',
                        'type' => 'string',
                        'description' => 'A valid username',
                        'source' => array('data' => 'username'),
                        'optional' => FALSE,
                    ),
                    array(
                        'name' => 'password',
                        'type' => 'string',
                        'description' => 'A valid password',
                        'source' => array('data' => 'password'),
                        'optional' => FALSE,
                    ),
</code>
For your arguments, and add your field machine names.
Inside your callback, you can set $form_state['values'][...] with the passed values, and then use
<code> drupal_form_submit('user_register_form', $form_state);
</code>
To register the user.

profile 2 module with services module


VScode shortcut to select up to next space?

Question: You can select entire words with the shortcut Ctrl + Shift + [Right/Left arrow] but is there a shortcut to select everything up to next space? Say I want to select the text foo/bar the previous shortcut will stop at the / slash symbol, but I want to select up to the end of the expression, which in this case, will end at the next space.
I tried the vscode-powertools solution from this post but couldn't make it work.
Edit: I'm working on Windows 10
Answer: you can use the extension I wrote: Select By
Add this keybinding:
  {
    "key": "ctrl+shift+alt+right",
    "when": "editorTextFocus",
    "command": "selectby.regex",
    "args": {
      "forward": " ",
      "forwardInclude": false
    }
  }

Comment: Do you know how to make it work backwards? That is, selecting from right to left up to next space
Comment: @Darvid Have you read the extension doc page: use `backward` and `backwardInclude`
Answer: If Ctrl+D doesn't select everything you want (it depends on the separator between words),
then hit your Ctrl+Shift+right/leftArrow.

Or you could try this extension I wrote, Jump and Select.
Using the default keybinding Shift+Alt+F the command will select everything from the cursor to whatever character you type next - in your case a Space.
Answer: Are you working with mac? Let's use CMD + pattern rather than Ctrl + pattern
Comment: No, I have Windows 10


Profile2 profile

Question: I am very new to Drupal but am good with coding (PHP, JS, whatever is required).
I want to set up a simple registration page that allows users to register using minimal fields (name, email, password, etc). ONCE THEY ARE registered and verified/okayed, I would like to give them an OPTION to fill in a profile form, which will have many optional fields they might want to share about themselves.
The profile form will always be available to registered users to edit/change.
What is the best way to achieve this? It seems the PROFILE2 module only adds fields to the registration page.
Answer: Oy, embarrasing. In the profile2 view, "edit" the individual profile, disable "Show during user account registration."
If those more experienced than me think this will help others, keep it... O/W delete this thread.
Comment: it's unlikely anyone with that authority will see this individual question, so I suggest you mark your own answer as accepted, so at least it doesn't keep showing up as unanswered.

Profile2 profile


Java implicit try-with-resources

Question: I am wondering if the following code uses the try-with-resources correctly.
try (ResultSet rs = new QueryBuilder(connection, tableName(), getPaths(), searchQuery()).add(constraint).build().executeQuery()) {
    while (rs.next()) {
        beans.add(createBean(rs));
    }
}

The arguments are not important, the only important thing is:

new QueryBuilder().build(); returns a PreparedStatement.

I completely understand that rs will be closed, but will the PreparedStatement also be closed, and if so, for what reason? Because the ResultSet closes or because of the try-with-resources?
Answer: PreparedStatement#close() will automatically close any associated result sets but the reverse is not true because statements are reusable after their result sets are closed.
Look at the javadoc of ResultSet#close():

Note: A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed

And then Statement#close():

Note: When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

This usage looks very crappy to me :
ResultSet rs=conn.createStatement().executeQuery();

If executed enough times it will leak all of the available cursors, because cursors are associated with the Statement not with ResultSet.
Hence to close the underlying PreparedStatement with try-with-resources statement , just declare it within the try statement :

A try-with-resources statement is parameterized with variables (known as resources) that are initialized before execution of the try block and closed automatically.

Look at this answer from assylias, declare the PreparedStatement as well as ResultSet inside the try statement.
Since you are not looking for a memory leak, but a resource leak . The memory of the PreparedStatement will be collected eventually and it's memory freed, as it is not referenced anymore after execution of your method given the way it is initialized , however, the resources hold by the Statement is not closed .
Answer: You can include several resources in the try, and they will all be closed - which is necessary if you want the PreparedStatement to be closed:
try (PreparedStatement ps = new QueryBuilder(connection, tableName(), getPaths(), searchQuery()).add(constraint).build();
        ResultSet rs = ps.executeQuery();) {
    while (rs.next()) {
        beans.add(createBean(rs));
    }
}

Comment: I've had that (and will have again now), but I was kind of trying to avoid two different declarations.
Comment: @skiwi I actually find splitting it in two statements more readable, not less.
Comment: Do you actually need to declare the ResultSet in the try-with-resources?  Can't it be safely declared in the body of the try block and automatically closed by the PreparedStatement when it is closed?  Not trying to nit-pick your code, I'm just not sure if that's how it'll work or not.
Comment: @GregH I'm never 100% sure of what happens to the ResultSet when the Statement is closed and I think I've read that some drivers do not release resources as you would expect. It doesn't cost anything to also close the ResultSet so I just do it. But you are right that it should be safe to place `ResultSet rs = ps.executeQuery()` in the body of the try block because it should get closed when you close the PreparedStatement.
Answer: According to the documentation here - tryResourceClose, as I read it, it is specific to resources that are declared.
The try-with-resources statement is a try statement that declares one or more resources.
Reading further down you see:
You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:
 try (
      java.util.zip.ZipFile zf =
         new java.util.zip.ZipFile(zipFileName);
    java.io.BufferedWriter writer =
        java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
  ) {

I suggest the correct answer to you issue is the following:
try{
  PreparedStatement statement = new QueryBuilder(connection, tableName(), getPaths(), searchQuery())
       .add(constraint).build();
  ResultSet rs = statement.executeQuery())
}

Answer: As you correctly stated, rs will be closed. This means actually that the close() method will be invoked on rs. So the try-with-ressource statement doesn't explictly close the PreparedStatement in your case.
If it's closed otherwise (in context of the rs.close()) is kind of hard to say without knowing the implementation ;-)
EDIT
As @TheNewIdiot correctly found out, your PreparedStatement won't be closed.

Java implicit try-with-resources


Does Wirth's law still hold true?

Question: Adage made by Niklaus Wirth in 1995:
«Software is getting slower more rapidly than hardware becomes faster»

Do you think it's actually true?
How should you measure "speed" of software? By CPU cycles or rather by time you need to complete some task?
What about software that is actually getting faster and leaner (measured by CPU cycles and MB of RAM) and more responsive with new versions, like Firefox 3.0 compared with 2.0, Linux 2.6 compared with 2.4, Ruby 1.9 compared to 1.8. Or completely new software that is order of magnitude faster then old stuff (like Google's V8 Engine)? Doesn't it negate that law?
Answer: Yes I think it is true.
How do I measure the speed of software? Well time to solve tasks is a relevant indicator. For me as a user of software I do not care whether there are 2 or 16 cores in my machine. I want my OS to boot fast, my programs to start fast and I absolutely do not want to wait for simple things like opening files to be done. A software has to just feel fast.
So .. when booting Windows Vista there is no fast software I am watching.
Software / Frameworks often improve their performance. That's great but these are mostly minor changes. The exception proves the rule :)
In my opinion it is all about feeling. And it feels like computers have been faster years ago. Of course I couldn't run the current games and software on those old machines. But they were just faster :)
Comment: For example Ruby 1.9 is 2.5x faster then 1.8. Minor change?
Comment: As I said: The exception proves the rule. I know there are also great efforts in optimizing JavaScript engines at the moment but I very often don't feel the speedups. I buy a new computer, start it and think "Hum, seems slower than the previous one". May be just a matter of wrong OS.
Comment: My Ubuntu box does go from power on to login in half the time of my XP box. Admittedily the Ubuntu box has a slightly faster CPU but has less RAM.
Answer: It's not that software becomes slower, it's that its complexity increases.
We now build upon many levels of abstraction.
When was the last time people on SO coded in assembly language?
Most never have and never will.
Comment: There are good abstractions and bad abstractions. The big part of the problem is the open-closed principle. Which is still taught at programming courses, but it's outdated nowadays. If OCP is taken seriously, then programmers will stack up layers instead of adding new features at the right layer and refactoring the code.
Answer: In general, the law holds true. As you have stated, there are exceptions "that prove the rule". My brother recently installed Win3.1 on his 2GHz+ PC and it boots in a blink of an eye.
I guess there are many reasons why the law holds:

Many programmers entering the profession now have never had to consider limited speed / resourced systems, so they never really think about the performance of their code.
There's generally a higher importance on getting the code written for deadlines and performance tuning usually comes last after bug fixing / new features.

I find FF's lack of immediate splash dialog annoying as it takes a while for the main window to appear after starting the application and I'm never sure if the click 'worked'. OO also suffers from this.
There are a few articles on the web about changing the perception of speed of software without changing the actual speed.
EDIT:
In addition to the above points, an example of the low importance given to efficiency is this site, or rather, most of the other Q&A sites. This site has always been developed to be fast and responsive and it shows. Compare this to the other sites out there - I've found phpBB based sites are flexible but slow. Google is another example of putting speed high up in importance (it even tells you how long the search took) - compare with other search engines that were around when google started (now, they're all fast thanks to google).
It takes a lot of effort, skill and experience to make fast code which is something I found many programmers lack.
Comment: "Win3.1 on his 2GHz+ PC" there is no doubt about it. But AFAIR, Win3.1 on it's contemporary PC did take a lot longer to start. And there was no suspend-to-RAM, nor hibernation.
Comment: And nowadays, Win3.1 won't recognize half the hardware, so you have essentially an expensive brick that boots fast.
Comment: The Win3.1 install did work - I think he wanted to play some old game that wouldn't work under XP.
Comment: Google is clear example where raw hardware power is cheaper and better than "optimal" solution. See for example http://www.databasecolumn.com/2008/01/mapreduce-a-major-step-back.html
Comment: (that link is dead; see http://databasecolumn.vertica.com/database-innovation/mapreduce-a-major-step-backwards/ )
Answer: It is wrong. Correct is
Software is getting slower at the same rate as hardware becomes faster.
The reason is that this is mostly determined by human patience, which stays the same.
It also neglects to mention that the software of today does more than 30 years ago, even if we ignore eye candy.
Comment: Nah, IMO human patience is most likely fading away. Did you ever have to use your favorite bloated IDE at grandma's computer (say, in a week-end emergency) ? Frustrating, at the very least.
Answer: From my own experience, I have to disagree with Wirth's law.
When I first approached a computer (in the 80'), the time for displaying a small still picture was perceptible. Today my computer can decode and display 1080p AVCHD movies in realtime.
Another indicator is the frames per second of video games. Not long ago it used to be around 15fps. Today 30fps to 60 fps are not uncommon.
Comment: +1. You did pick two areas where developers are still shying fancy new languages and VMs in favor of C++ and assembly, though.
Comment: FPs is a rather bad indicator (it can be changed in the same game on the same hardware by playing with option menus), besides running an early 3D game on modern hardware tends to generate FPS well beyond use (e.g. 100-200)
Comment: @MSalters graphic engines -- yes, but lot of games have logic written in Lua.
Answer: One of the issues of slow software is a result of most developers using very high end machines with multicore CPUs and loads of RAM as their primary workstation.  As a result they don't notice performance issues easily.
Part of their daily activity should be running their code on slower more mainstream hardware that the expected clients will be using.  This will show the real world performance and allow them to focus on improving bottlenecks.  Or even running within a VM with limited resources can aid in this review.
Faster hardware shouldn't be an excuse for creating slow sloppy code, however it is.
Answer: Quoting from a UX study:

The technological advancements of 21 years have placed modern PCs in a completely different league of varied capacities. But the "User Experience" has not changed much in two decades. Due to bloated code that has to incorporate hundreds of functions that average users don't even know exist, let alone ever utilize, the software companies have weighed down our PCs to effectively neutralize their vast speed advantages.

Detailed comparison of UX on a vintage Mac and a modern Dual Core: http://hubpages.com/hub/_86_Mac_Plus_Vs_07_AMD_DualCore_You_Wont_Believe_Who_Wins
Answer: My machine is getting slower and clunkier every day.  I attribute most of the slowdown to running antivirus.  When I want to speed up, I find that disabling the antivirus works wonders, although I am apprehensive like being in a seedy brothel.
Comment: Antivirus scanning can be disk-intensive. Get a SSD, or turn off the antivirus. It's not hard to keep your personal Windows machine pristine. Antivirus is for everybody else.
Answer: I think that Wirth's law was largely caused by Moore's law - if your code ran slow, you'd just disregard since soon enough, it would run fast enough anyway. Performance didn't matter.
Now that Moore's law has changed direction (more cores rather than faster CPUs), computers don't actually get much faster, so I'd expect performance to become a more important factor in software development (until a really good concurrent programming paradigm hits the mainstream, anyway). There's a limit to how slow software can be while still being useful, y'know.
Answer: Yes, software nowadays may be slower or faster, but you're not comparing like with like. The software now has so much more capability, and a lot more is expected of it.
Lets take as an example: Powerpoint. If I created a slideshow with Powerpoint from the early nineties, I can have a slideshow with pretty colours fairly easily, nice text etc. Now, its a slideshow with moving graphics, fancy transitions, nice images.
The point is, yes, software is slower, but it does more.
The same holds true of the people who use the software. back in the 70s, to create a presentation you had to create your own transparencies, maybe even using a pen :-). Now, if you did the same thing, you'd be laughed out of the room. It takes the same time, but the quality is higher.
This (in my opinion) is why computers don't give you gains in productivity, because you spend the same amount of time doing 'the job'. But if you use todays software, your results looks more professional, you gain in quality of work.
Comment: Shouldn't that be able to load when necessary though, and not at startup? I wonder if the next big programming language (tm) will incorporate syntax that make this extremly easy.
Answer: Skizz and Dazmogan have it right.

On the one hand, when programmers try to make their software take as few cycles as possible, they succeed, and it is blindingly fast.
On the other hand, when they don't, which is most of the time, their interest in "Galloping Generality" uses up every available cycle and then some.

I do a lot of performance tuning. (My method of choice is random halting.) In nearly every case, the reason for the slowness is over-design of class and data structure.
Oddly enough, the reason usually given for excessively event-driven and redundant data structure is "efficiency".
As Bompuis says, we build upon many layers of abstraction. That is exactly the problem.
Answer: Yes it holds true. You have given some prominent examples to counter the thesis, but bear in mind that these examples are developed by a big community of quite knowledgeable people, who are more or less aware of good practices in programming.
People working with the kernel are aware of different CPU's architectures, multicore issues, cache lines, etc. There is an interesting ongoing discussion about inclusion of hardware performance counters support in the mainline kernel. It is interesting from the 'political' point of view, as there is a conflict between the kernel people and people having much experience in performance monitoring.
People developing Firefox understand that the browser should be "lightweight" and fast in order to be popular. And to some extend they manage to do a good job.
New versions of software are supposed to be run on faster hardware in order to have the same user experience. But whether the price is just? How can we asses whether the functionality was added in the efficient way?
But coming back to the main subject, many of the people after finishing their studies are not aware of the issues related to performance, concurrency (or even worse, they do not care). For quite a long time Moore law was providing a stable performance boost. Thus people wrote mediocre code and nobody even noticed that there was something wrong with inefficient algorithms, data-structures or more low-level things.
Then some limitations came into play (thermal efficiency for example) and it is no longer possible to get 'easy' speed for few bucks. People who just depend on hardware performance improvements might get a cold shower. On the other hand, people who have in-depth knowledge of algorithms, data structures, concurrency issues (quite difficult to recruit these...) will continue to write good applications and their value on the job market will increase.
The Wirth law should not only be interpreted literally, it is also about poor code bloat, violating the keep-it-simple-stupid rule and people who waste the opportunity to use the 'faster' hardware.
Also if you happen to work in the area of HPC then these issues become quite obvious.
Comment: Exactly in area of HPC issues do not became obvious. From economical point of view it's a lot cheaper to add nodes to cluster, than have to pay same 20-50 times more to have the code run 30% faster. Skilled mathematicians and software developers don't come cheap.
Comment: Then it depends on the work culture and policies - in some places there is more focus on putting new hardware, in others it is on squeezing out last bit of performance out of it ;)
Comment: Or if your target hardware is fixed, for example if it's already in the customer's hands and they're not going to upgrade.
Comment: @Crashwork -- in HPC? In HPC customer will rather upgrade his blades to new CPU for $50K and have immediate performance boost of 50%, then pay developers $500K and have 25% performance boost in 6 months.
Answer: In some cases it is not true: the frame rate of games and the display/playing of multimedia content is far superior today than it was even a few years ago.
In several aggravatingly common cases, the law holds very, very true. When opening the "My Computer" window in Vista to see your drives and devices takes 10-15 seconds, it feels like we are  going backward.  I really don't want to start any controversy here but it was that as well as the huge difference in time needed to open Photoshop that drove me off of the Windows platform and on to the Mac.  The point is that this slowdown in common tasks is serious enough to make me jump way out of my former comfort zone to get away from it.
Comment: I wish people would stop going on about Vista, my machine has little lag opening my computer (2~3 seconds on occasion). As for Photoshop I have a machine where it opens at a reasonable speed (it is a large program), and a 3 year old machine where it takes ages, but I wouldn't call it a common task!
Answer: Can´t find the sense. Why is this sentence a law?
You never can compare Software and Hardware, they are too different.
Hardware is genuine material and Software is a written code.
The connection is only that Software has to control the performance of Hardware. After an executed step in Hardware the Software needs a completion-sign, so the next order of Software can be done.
Why should I  slow down Software? We allways try to make it faster !
It´s a lot of things to do in real physical way to make Hardware faster (changing print-modules or even physical parts of a computer).
It may be senseful,if Wirth means: to do this in one computer (= one Software- and Hardware-System).
To get a higher speed of Hardware it´s necessary to know the function of the Hardware, amount of parallel inputs or outputs at one moment and the frequency of possible switches in one second. Last not least it´s important that different Hardware-prints have the same or with a numeric factor multiplicated frequeny.
So perhaps the Software may slow down automaticaly very easy if You change something in the Hardware. - Wirth was thinking much more in Hardware, he is one of the great inventors since the computer is existing in the German-speaking area.
The other way is not easy. You have to know the System-Software of a computer very exactly to make the Hardware faster by changing the Software (=System-Software, Machine-Programs) of a computer. And if You use more layers you nearly have no direct influence in the speed of the Hardware.
Perhaps this may be the explanation of Wirth´s Law-Thinking....I got it!

Does Wirth's law still hold true?


Different random effects in nlme and nlmer

Question: I estimated a nonlinear exponential $f(t)=\alpha-(\alpha-\beta)*\exp(-\gamma*t)$ random effects model in R. I estimated the same model form using the identical data set but with nlme() from the nlme library and nlmer() from the lme4 library.
The fixed effect estimates are quite similar comparing nlme with nlmer:
nlme:
Fixed effects: alpha + beta + gamma ~ 1
          Value Std.Error   DF  t-value p-value
alpha 29.508227 0.4166492 3498 70.82272       0
beta   5.082116 0.1584696 3498 32.06998       0
gamma  0.313008 0.0070209 3498 44.58244       0

nlmer:
Fixed effects:
      Estimate Std. Error t value
alpha  30.0432     0.5432   55.31
beta    4.9541     0.2110   23.47
gamma   0.2551     0.0135   18.90

However, the random effects estimates along with their correlation matrix are different. This is a consistent finding. It also holds for other nonlinear functions and other data. See e.g. the correlation between alpha and gamma. It is also striking how large the variances in nlmer are -- they actually appear to be far too large
nlme:
> VarCorr(model)
Subject = pdLogChol(list(alpha ~ 1,beta ~ 1,gamma ~ 1))
         Variance    StdDev   Corr
alpha    42.19955753 6.496119 alpha  beta
beta      4.84969745 2.202203  0.494
gamma     0.01055961 0.102760 -0.643  0.202
Residual  1.94836594 1.395839

nlmer:
Random effects:
 Groups   Name  Variance  Std.Dev. Corr
 Subject  alpha 72.551249 8.51770
          beta   9.840010 3.13688   0.458
          gamma  0.043274 0.20802  -0.195  0.142
 Residual        1.716048 1.30998
Number of obs: 3750, groups: Subject, 250

What is the problem here? Why are the variances in nlmer almost twice as large as those given in the nlme solution?
Comment: I think you should reconsider the statement that the fixed effects are similar.  Look at gamma.  They differ by many standard deviations.
Answer: Short: It's lack of precision in nlmer
In order to obtain the same results as nlme I needed to move away form the laplacian approximatoin which is set with nAGQ=1. According to the nlmer manpage the nAGQ sets the number of points per axis for the evaluation of the adaptive Gauss-Hermite approximation. Basically, increasing the number of points per axis increases precision.
With nAGQ=2 random and fixed effects are virtually the same - this is also the case for the SD of the fixed effecs, as John had noted. In the present case increasing the nAGQ to 2 or 3 does the trick, however, larger numbers will slow down the computation and maybe reach the iteration limit without convergence.
I guess it's good practice to run the model with the standard settings and then go back and increase the precision to see if, and how strong the parameter estimates change.
For the present model it takes

10 sec with nAGQ=1
22 sec with nAGQ=2
24 with nAGQ=3

nAGQ=4 does not converge within the given iterations.
In my case, the results obtained from nAGQ=2 and nAGQ=3 were the same.
As a comparison,

in nlme it takes 3.8 seconds

to obtain the result, which I find quite surprising because in the past I had the impression that nlmer is faster than nlme.
Bottom line: It's probably safer to use nlme, as long as lme4 and with it nlmer is under development.


Combining two Odds ratios with the same control group

Question: I am doing a meta-analysis of observational studies. As the disease I am working on has different stages, some of the studies reported ORs (95%CI) for each stage separately in comparison to a single (shared) control population. I wonder if we can combine these two ORs (and their 95%CI) given that they reflect two case groups but a single control group. Some other info:

The sample size for each case group is different.
We have the sample size for each of the groups but not the frequency of exposure (otherwise we could use just the raw data).
Please note that I have no problem combining the ORs, but simply combining two ORs without taking into account that they both have the same control group will cause narrowing of the 95%CI and overweighting of the study in the analysis.

Any ideas?
Answer: The chapter on stochastically dependent effect sizes by Gleser and Olkin (2009) in The handbook of research synthesis and meta-analysis (2nd ed.) describes how multiple-treatment and multiple-endpoint studies can be meta-analyzed. Your case can be covered by the "multiple-treatment" part -- that is, you can look at the two disease stages as two different 'treatments' that are both compared against a common control group. In essence, you will have to compute the covariance between the two (log) ORs and take that into consideration when you want to include the two ORs in your meta-analysis.
If you work with R, you may find the metafor package useful. On the metafor package website, you can find code that will reproduce the methods described in the Gleser and Olkin chapter: http://www.metafor-project.org/doku.php/analyses:gleser2009. That should help to get you started.


How to disable the Submit button on a the delete page form?

Question: I made a form_alter and trying to disable the submit button by greying it out by using the #disabled option on the form api. I know i can just do a unset() on the submit button, but was wondering how to use the #disabled. I tried the following:
$form['actions']['submit']['#disabled'] = TRUE;
But that doesn't do anything it seems. Here' my krumo output:
Answer: Yes, you are understanding the behavior of the '#disabled' key correctly. I tried the code you describe and it "just worked."
<code>function custom_form_node_delete_confirm_alter(&$form, $form_state) {

  dsm($form['actions']['submit']);
  $form['actions']['submit']['#disabled'] = TRUE;
  dsm($form['actions']['submit']);
}
</code>

My guess as to why the alteration is not creating the desired end result is that your function signature is not using the "&" with the $form variable. That character is needed for the $form variable to be "passed by reference" which allows for the changes to the variable to stick outside the function.
Answer: By referring Drupal 7 disable submit button your code is correct. Plz refer this or just try  Hide submit button module..
Comment: i wanted to grey it out so you cannot click it. i thought tats built into drupal? what does #disable do then? is it the same as unset()?
Comment: i referred [this](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#actions),


Show the url obtained from a form to image in the result php

Question: sorry for the inconvenience, I have no knowledge of php or html, but I have investigated and can not find anywhere
I have this code of a simple form in the index.html
<form enctype="multipart/form-data" action="/movie/envio.php" method="POST">
  Imagen obtenida:
  <input type="text" id="urlimage" name="urlimage" value="https://image.tmdb.org/t/p/w500{{movie.poster_path}}">

 Sinopsis:
  <input type="text" id="sinopsis" name="sinopsis" value="{{movie.overview}}">

<input type="submit" />

</form>

In the shipment.php
Imagen Obtenida: <?php echo htmlspecialchars($_POST['urlimage']); ?>

Sinopsis: <?php echo htmlspecialchars($_POST['sinopsis']); ?>

If you go to [https://uniq.edu.mx/movie1
and select a movie, it will take you to the photo and synopsis, I extract that information with the form
The extracted information is sent to envio.php correctly.

How do I do so that instead of showing me the complete url of the image, it shows it as an image inserted in the destination page?
Answer: You need to output HTML image tag for that:
<img src="<?= $_POST['urlimage']; ?>"/>


What are the relation properties of  = {(, ) | gcd(, ) = 1}

Question: I am guessing that it is reflexive since it relates to itself $gcd(x,y)=gcd(x,y)$

But I can't think of a way to picture the relation to find if it's transitive and symmetric.
Comment: If x is greater than 1, does x relate to itself? I'd guess no since the gcd would be x that is greater than 1. Symmetric is easier to show as the order doesn't matter so $xRy=yRx$.
Comment: @JBKing how would you show that it doesn't relates to itself, since there are two variables?
Comment: Symmetry and non-reflexivity directly imply non-transitivity, since $x R y$ and $y R x$ should imply $x R x$, but this is not true by non-symmetry. So the relation is only reflexive.
Comment: Also it isn't transitive.  Consider 2R3,3R4 and 2R4
Comment: Consider $x=y=3$ and see that the relation doesn't hold in this case.
Comment: @QthePlatypus when you say $2R3$, do you mean $x=2$ and $y=3$?
Comment: @PhoxKiD Yes 2R3 means x=2 and y=3.
Comment: @QthePlatypus oic, so $2R3$ means that they satisfy condition
Comment: Yes for for something to be transitive $ xRy \wedge yRz \implies xRz$ which the above is a counter example of.
Answer: I think you've mixed up "reflexive" which asserts every element is related to itself $xRx$ (and is not true here) with "symmetric" which says all relations are two-way, $xRy \iff yRx$ (which is true).
Because the relation is symmetric but not reflexive, we immediately know that it is not transitive, since $xRy$ and $yRx$ do not lead to $xRx$.
As for picturing the relation, in plain words it says $x$ and $y$ are coprime, or have no common factors greater than $1$. Since $x$ definitely has a common factor with itself, that eliminates reflexivity easily, and the rest follows as above.
Comment: Is it by definition that if the relation is symmetric and not reflexive it must be not transitive?
Comment: It's not by definition. @Joffan proved it in his answer.
Comment: Unless it's empty, that immediately follows


How to convert a sequence of space-separated numbers in a string to ints

Question: I am trying to convert string element to integer using stoi function in C++11 and using it as parameter to pow function, like this:
#include <cstdlib>
#include <string>
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    string s = "1 2 3 4 5";

    //Print the number's square
    for(int i = 0; i < s.length(); i += 2)
    {
        cout << pow(stoi(s[i])) << endl;
    }
}

But, i got an error like this:
error: no matching function for call to
'stoi(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'
cout << pow(stoi(s[i])) << endl;

Anyone know what is the problem with my code?
Comment: The problem is that `s[i]` is, obviously, a `char`. One character. Now take a look at what the parameter to `stoi`() must be, and you should be able to figure it out by yourself.
Comment: `stoi` works with `std::string` (and `std::wstring`), but `s[i]` is a `char`.
Comment: @AkhmadZaki Yes, `substr` will work.
Comment: Does it work if I use `substr` function because from what I read, it returns string type?
Comment: Are you sure your integers need to be in a string? It'd be better to use array of integers if possible.
Answer: The problem is that stoi() will not work with char. Alternatively you can use std::istringstream to do this. Also std::pow() takes two arguments the first being the base and the second being the exponent. Your comment says the number's square so...
#include <sstream>

string s = "1 2 3 4 5 9 10 121";

//Print the number's square
istringstream iss(s);
string num;
while (iss >> num) // tokenized by spaces in s
{
    cout << pow(stoi(num), 2) << endl;
}

Edited to account for numbers larger than single digit in the original string s, since the for loop approach breaks for numbers larger than 9.
Comment: It's better to use `std::istringstream` and not `std::stringstream` so the compiler can detect an accidental `<<`.
Comment: What if s contains a number > 9 ?
Comment: yes, I forgot to include the exponent. Thanks for the answer.
Comment: Is the above code still work for integer with number of digit > 1 ?
Comment: @AkhmadZaki yes it does
Answer: stoi() works fine if you use std::string.
So,
string a = "12345";
int b = 1;
cout << stoi(a) + b << "\n";

Would output:
12346

Since, here you are passing a char you can use the following line of code in place of the one you are using in the for loop:
std::cout << std::pow(s[i]-'0', 2) << "\n";

Comment: This trick is only guaranteed to work as long as every character in the string is in the range `'0'` to `'9'`. A single space in the string and you risk undefined behaviour. It's also harder to read.
Comment: This one should be accepted as the answer in an engineering way
Comment: Thanks for the answer.
Answer: Something like:
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string s = "1 2 3 4 5";
    istringstream iss(s);
    while (iss)
    {
        string t;
        iss >> t;
        if (!t.empty())
        {
            cout << pow(stoi(t), 2) << endl;
        }
    }
}

Comment: Thanks for the answer.


Understanding comparisons of clustering results

Question: I'm experimenting with classifying data into groups. I'm quite new to this topic, and trying to understand the output of some of the analysis.
Using examples from Quick-R, several R packages are suggested. I have tried using two of these packages (fpc using the kmeans function,  and mclust). One aspect of this analysis that I do not understand is the comparison of the results.
# comparing 2 cluster solutions
library(fpc)
cluster.stats(d, fit1$cluster, fit2$cluster)

I've read through the relevant parts of the fpc manual and am still not clear on what I should be aiming for. For example, this is the output of comparing two different clustering approaches:
$n
[1] 521

$cluster.number
[1] 4

$cluster.size
[1] 250 119  78  74

$diameter
[1]  5.278162  9.773658 16.460074  7.328020

$average.distance
[1] 1.632656 2.106422 3.461598 2.622574

$median.distance
[1] 1.562625 1.788113 2.763217 2.463826

$separation
[1] 0.2797048 0.3754188 0.2797048 0.3557264

$average.toother
[1] 3.442575 3.929158 4.068230 4.425910

$separation.matrix
          [,1]      [,2]      [,3]      [,4]
[1,] 0.0000000 0.3754188 0.2797048 0.3557264
[2,] 0.3754188 0.0000000 0.6299734 2.9020383
[3,] 0.2797048 0.6299734 0.0000000 0.6803704
[4,] 0.3557264 2.9020383 0.6803704 0.0000000

$average.between
[1] 3.865142

$average.within
[1] 1.894740

$n.between
[1] 91610

$n.within
[1] 43850

$within.cluster.ss
[1] 1785.935

$clus.avg.silwidths
         1          2          3          4
0.42072895 0.31672350 0.01810699 0.23728253

$avg.silwidth
[1] 0.3106403

$g2
NULL

$g3
NULL

$pearsongamma
[1] 0.4869491

$dunn
[1] 0.01699292

$entropy
[1] 1.251134

$wb.ratio
[1] 0.4902123

$ch
[1] 178.9074

$corrected.rand
[1] 0.2046704

$vi
[1] 1.56189

My primary question here is to better understand how to interpret the results of this cluster comparison.

Previously, I had asked more about the effect of scaling data, and calculating a distance matrix. However that was answered clearly by mariana soffer, and I'm just reorganizing my question to emphasize that I am interested in the intrepretation of my output which is a comparison of two different clustering algorithms.
Previous part of question:
If I am doing any type of clustering, should I always scale data? For example, I am using the function dist() on my scaled dataset as input to the cluster.stats() function, however I don't fully understand what is going on. I read about dist() here and it states that:

this function computes and returns the distance matrix computed by using the specified distance measure to compute the distances between the rows of a data matrix.
Comment: Are you looking for further clarifications or are you unhappy with @mariana's response? I guess it concerns your very first question (2nd §). If this is the case, maybe you should update your question so that people understand why you're setting a bounty on this question.
Comment: @chl I will update it to make it clearer. I'm just looking for some guidance on interpreting the clustering comparisons, as don't understand what the output means. @mariana's response was very helpful explaining some of the terms associated with this method.
Answer: First let me tell you that I am not going to explain exactly all the measures here, but I am going to give you an idea about how to compare how good the clustering methods are (let's assume we are comparing 2 clustering methods with the same number of clusters).

For example the bigger the diameter of the cluster, the worst the clustering, because the points that belong to the cluster are more scattered.
The higher the average distance of each clustering, the worst the clustering method. (Let's assume that the average distance is the average of the distances from each point in the cluster to the center of the cluster.)

These are the two metrics that are the most used. Check these links to understand what they stand for:

inter-cluster distance (the higher the better, is the summatory of the distance between the different cluster centroids)
intra-cluster distance (the lower the better, is the summatory of the distance between the cluster members to the center of the cluster)

To better understanding the metrics above, check this.
Then you should read the manual of the library and functions you are using to understand which measures represent each of these, or if these are not included try to find the meaning of the included. However, I would not bother and stick with the ones I stated here.
Let's go on with the questions you made:

Regarding scaling data: Yes you should always scale the data for clustering, otherwise the different scales of the different dimensions (variables) will have different influences in how the data are clustered, with the higher the values in the variable, the more influential that variable will be in how the clustering is done, while indeed they should all have the same influence (unless for some particular strange reason you do not want it that way).
The distance functions compute all the distances from one point (instance) to another. The most common distance measure is Euclidean, so for example, let's suppose you want to measure the distance from instance 1 to instance 2 (let's assume you only have 2 instances for the sake of simplicity). Also let's assume that each instance has 3 values (x1, x2, x3), so I1=0.3, 0.2, 0.5 and I2=0.3, 0.3, 0.4 so the Euclidean distance from I1 and I2 would be: sqrt((0.3-0.2)^2+(0.2-0.3)^2+(0.5-0.4)^2)=0.17, hence the distance matrix will result in:
    i1    i2
i1  0     0.17
i2  0.17  0

Notice that the distance matrix is always symmetrical.
The Euclidean distance formula is not the only one that exists. There are many other distances that can be used to calculate this matrix. Check for example in Wikipedia Manhattain Distance and how to calculate it. At the end of the Wikipedia page for Euclidean Distance (where you can also check its formula) you can check which other distances exist.
Comment: @marianasoffer the link to the Stanford page doens't work. Please update it or make it accessible. Thank you
Comment: Thank you for your very comprehensive answer - it's very helpful.
Comment: I am really happy it was helpfull for you.
Answer: I think the best quality measure for clustering is the cluster assumption, as given by Seeger in Learning with labeled and unlabeled data:

For example, assume X = Rd and the validity of the "cluster assumption", namely that two points x, x should have the same label t if there is a path between them in X which passes only through regions of relatively high P(x).

Yes, this brings the whole idea of centroids and centers down. After all, this are rather arbitrary concepts if you think about the fact that your data might lie within a non-linear submanifold of the space you are actually operating in.
You can easily construct a synthetic dataset where mixture models break down. E.g. this one: .
Long story short: I'd measure the quality of a clustering algorithm in a minimax way. The best clustering algorithm is the one which minimizes the maximal distance of a point to its nearest neighbor of the same cluster while it maximizes the minimal distance of a point to its nearest neighbor from a different cluster.
You might also be interested in A Nonparametric Information Theoretic Clustering Algorithm.
Comment: How do I go about examining a cluster fit using a minimax approach? My knowledge level of clustering is very basic, so at the moment I'm just trying to understand how to compare two different clustering approaches.
Comment: Could you please share the R code for the attached figure?
Comment: @Andrej My guess is a Gaussian cloud (`x<-rnorm(N);rnorm(N)->y`) split into 3 parts by r (with one of them removed).
Comment: I don't know of a practical algorithm that fits according to that quality measure. You probably still want to use K-Means et al. But if the above measure breaks down, you know that the data you are looking at is not (yet!) suitable for that algorithm.
Comment: @Andrej I don't use R (coming from ML rather than stats :) but what mbq suggests seems fine.


The lattice $\displaystyle \Lambda $ associated to the pendulum equation is rectangular

Question: The pendulum equation (for a suitable choice of parameters) is $\dot{\theta}^2 − \cos \theta = E.$
Taking $u = \cos \theta$, we get $$\dot{u}^{2} =( u+E)\left( 1-u^{2}\right)$$
It is well known that the solution to the above is $u = a \cdot  \wp_{\Lambda}(t-t_0) +b$, where $\wp_{\Lambda}$ is the Weierstrass function associated with the lattice $\Lambda$. The values of $a,b,\Lambda$ depends on $E$, while the value of $t_0$ depends on the initial conditions.
The question is:

Show that the lattice $\displaystyle \Lambda $ is rectangular, i.e. generated by 1 and $\displaystyle iq$ for some $\displaystyle q\  >\ 0$, and that for physically meaningful solutions the imaginary part of the constant of integration $\displaystyle t_{0}$ must be $\displaystyle q/2$.

[From Riemann Surfaces by S. K. Donaldson, page 96]

What is special about the pendulum equation that makes its lattice rectangular?
I presume by constant of integration they mean $t_0$ (mentioned above). Why does $\text{Im}(t_0)$ have to $q/2$ and why is $t_0$ called "the constant of integration".

When trying to find the answer to 1, I came across a book which mentioned that the lattice is rectangular for any elliptic curve $y^2 = f(x)$, where $f$ is real and has 3 distinct roots. If one can prove this, we are done.
(Ref: Elliptic Curves: Number Theory and Cryptography, Second Edition. Page 286)
Answer: For the first part, let $$v = -u-E/3$$ so that $$v'^2 =v^3-v(1+E^2/3)+2E/3-2 E^3/27 $$
which corresponds to the elliptic curve
$$C:y^2=x^3-Ax-B, \qquad A = 1+\frac{E^2}3,\quad B=\frac{2E}3- \frac{2E^3}{27} $$

$A > 0$ since $E$ is real

$\Delta=4A^3-27B^2 = \prod_{i<j} (\gamma_i-\gamma_j)^2$ is $\in (-\infty,4A^3]$ since $A,B$ are real, and $\Delta> 0$ because the RHS cubic polynomial has 3 distinct real roots $\gamma_1,\gamma_2,\gamma_3$.

The $j$-invariant is $$j(C) = 1728 \frac{4a^3}{4a^3-27b^2}\ge 1728$$

As $j(ir)$ is $(0,\infty)\to \Bbb{R}$, continuous, and $j(i)=1728,j(i\infty)=+\infty$, we get that $$j(C)=j(\tau)$$ for some $\tau$ purely imaginary.
The lattice $\Bbb{Z}+\tau \Bbb{Z}$ is rectangular and
its Weierstrass function satisfies $$\wp_\tau'^2 = \wp_\tau^3-4 g_2 \wp_\tau/4-16 g_3$$ with $4 g_2=c^4 A,16 g_3=c^6 B$ for some $c$.
I don't see why $1$ should be in $\Lambda$, I think we need to set $v(z)=c^2 \wp_\tau(z/c+z_0)$.


Windows XP: How can I get the system language from command-line?

Question: I want to use the command line to install something, we have 2 OS's in 2 languages. To install the package in correct language I need to find out what the system language is.
How do I get the system language from the command line?
Answer: This is done by REG QUERY HKLM\System\CurrentControlSet\Control\Nls\Language /v InstallLanguage
Then you get a number with the following meanings (no guarantee of completeness and correctness):
0436 = "af;Afrikaans"
041C = "sq;Albanian"
0001 = "ar;Arabic"
0401 = "ar-sa;Arabic (Saudi Arabia)"
0801 = "ar-iq;Arabic (Iraq)"
0C01 = "ar-eg;Arabic (Egypt)"
1001 = "ar-ly;Arabic (Libya)"
1401 = "ar-dz;Arabic (Algeria)"
1801 = "ar-ma;Arabic (Morocco)"
1C01 = "ar-tn;Arabic (Tunisia)"
2001 = "ar-om;Arabic (Oman)"
2401 = "ar-ye;Arabic (Yemen)"
2801 = "ar-sy;Arabic (Syria)"
2C01 = "ar-jo;Arabic (Jordan)"
3001 = "ar-lb;Arabic (Lebanon)"
3401 = "ar-kw;Arabic (Kuwait)"
3801 = "ar-ae;Arabic (you.A.E.)"
3C01 = "ar-bh;Arabic (Bahrain)"
4001 = "ar-qa;Arabic (Qatar)"
042D = "eu;Basque"
0402 = "bg;Bulgarian"
0423 = "be;Belarusian"
0403 = "ca;Catalan"
0004 = "zh;Chinese"
0404 = "zh-tw;Chinese (Taiwan)"
0804 = "zh-cn;Chinese (China)"
0C04 = "zh-hk;Chinese (Hong Kong SAR)"
1004 = "zh-sg;Chinese (Singapore)"
041A = "hr;Croatian"
0405 = "cs;Czech"
0406 = "the;Danish"
0413 = "nl;Dutch (Netherlands)"
0813 = "nl-be;Dutch (Belgium)"
0009 = "en;English"
0409 = "en-us;English (United States)"
0809 = "en-gb;English (United Kingdom)"
0C09 = "en-au;English (Australia)"
1009 = "en-ca;English (Canada)"
1409 = "en-nz;English (New Zealand)"
1809 = "en-ie;English (Ireland)"
1C09 = "en-za;English (South Africa)"
2009 = "en-jm;English (Jamaica)"
2809 = "en-bz;English (Belize)"
2C09 = "en-tt;English (Trinidad)"
0425 = "et;Estonian"
0438 = "fo;Faeroese"
0429 = "fa;Farsi"
040B = "fi;Finnish"
040C = "fr;French (France)"
080C = "fr-be;French (Belgium)"
0C0C = "fr-ca;French (Canada)"
100C = "fr-ch;French (Switzerland)"
140C = "fr-lu;French (Luxembourg)"
043C = "gd;Gaelic"
0407 = "de;German (Germany)"
0807 = "de-ch;German (Switzerland)"
0C07 = "de-at;German (Austria)"
1007 = "de-lu;German (Luxembourg)"
1407 = "de-li;German (Liechtenstein)"
0408 = "el;Greek"
040D = "he;Hebrew"
0439 = "hi;Hindi"
040E = "hu;Hungarian"
040F = "is;Icelandic"
0421 = "in;Indonesian"
0410 = "it;Italian (Italy)"
0810 = "it-ch;Italian (Switzerland)"
0411 = "ja;Japanese"
0412 = "ko;Korean"
0426 = "lv;Latvian"
0427 = "lt;Lithuanian"
042F = "mk;FYRO Macedonian"
043E = "ms;Malay (Malaysia)"
043A = "mt;Maltese"
0414 = "no;Norwegian (Bokmal)"
0814 = "no;Norwegian (Nynorsk)"
0415 = "pl;Polish"
0416 = "pt-br;Portuguese (Brazil)"
0816 = "pt;Portuguese (Portugal)"
0417 = "rm;Rhaeto-Romanic"
0418 = "ro;Romanian"
0818 = "ro-mo;Romanian (Moldova)"
0419 = "ru;Russian"
0819 = "ru-mo;Russian (Moldova)"
0C1A = "sr;Serbian (Cyrillic)"
081A = "sr;Serbian (Latin)"
041B = "sk;Slovak"
0424 = "sl;Slovenian"
042E = "sb;Sorbian"
040A = "es;Spanish (Traditional Sort)"
080A = "es-mx;Spanish (Mexico)"
0C0A = "es;Spanish (International Sort)"
100A = "es-gt;Spanish (Guatemala)"
140A = "es-cr;Spanish (Costa Rica)"
180A = "es-pa;Spanish (Panama)"
1C0A = "es-do;Spanish (Dominican Republic)"
200A = "es-ve;Spanish (Venezuela)"
240A = "es-co;Spanish (Colombia)"
280A = "es-pe;Spanish (Peru)"
2C0A = "es-ar;Spanish (Argentina)"
300A = "es-ec;Spanish (Ecuador)"
340A = "es-cl;Spanish (Chile)"
380A = "es-uy;Spanish (Uruguay)"
3C0A = "es-py;Spanish (Paraguay)"
400A = "es-bo;Spanish (Bolivia)"
440A = "es-sv;Spanish (El Salvador)"
480A = "es-hn;Spanish (Honduras)"
4C0A = "es-ni;Spanish (Nicaragua)"
500A = "es-pr;Spanish (Puerto Rico)"
0430 = "sx;Sutu"
041D = "sv;Swedish"
081D = "sv-fi;Swedish (Finland)"
041E = "th;Thai"
0431 = "ts;Tsonga"
0432 = "tn;Tswana"
041F = "tr;Turkish"
0422 = "uk;Ukrainian"
0420 = "your;Urdu"
042A = "vi;Vietnamese"
0434 = "xh;Xhosa"
043D = "ji;Yiddish"
0435 = "zu;Zulu"

Answer: If you want to actually test for the system language, you might consider using WMIC:
wmic.exe os get locale, oslanguage, codeset

yields on my machine:
CodeSet  Locale  OSLanguage
1252     0409    1033

For instance, if you wanted to test for Japanese (locale 0411), you might place the following in a batch program:
wmic os  get locale, oslanguage,  codeset | grep 0411 > nul && @echo Japanese Language installed!

Test for both locale's and issue goto's if they are found. Error out if they are not.
You're probably looking for a Locale rather than the OSLanguage or Codeset, but i included them here because of the way your question and the accepted answer are worded.


What order types can well-ordered proper classes have?

Question: Ordinals are order types of well-ordered sets.  Proper classes can be well-ordered too, though, the most famous example being the class of all ordinals under the standard ordering.  So my question is, what order-types can well-ordered proper classes have?  If we let $\Omega$ be the order type of the ordinals, how much bigger than $\Omega$ can we go?
I'm guessing that the order types of well-ordered proper classes cannot be put in one-to-one correspondence with the class of all sets, just as the order types of well-ordered countable sets cannot be put in one-to-one correspondence with the set of natural numbers.
EDIT: I am asking my question in the context of Morse-Kelly set theory.
Comment: Your question is unclear. Well-ordered by what? What is your foundational system? NBG? MK?
Comment: @user21820 I edited my question to specify MK.  And by a well-ordered proper class I mean a proper class $X$ together with a class relation, i.e. a proper class of ordered pairs of elements of $X$, which is a well-ordering.
Comment: Ok. It's now clear.
Answer: To make things clearer I'm going to rephrase the question as follows (it's  not hard to translate between this question, which is asked in the ZFC context, and your question as you've phrased it):

Suppose $M$ is a transitive model of ZFC. Let $\alpha_M$ be the supremum - calculated in $V$ - of the ordertypes of the definable (-in-the-sense-of-$M$) well-orderings of subsets (-in-the-sense-of-$V$) of $M$. What can we say about $\alpha_M$?

(This is closely related to this old Mathoverflow question.)
A good first observation is the following:

Let $N$ be the least admissible set above $M$ - that is, $N$ is the smallest transitive model of Kripke-Platek set theory with $M\in N$. Then $\alpha_M\le N\cap Ord$.

(I'll write "$\omega_1^{CK}(M)$" for $N\cap Ord$.)
This is a more-mysterious-looking special case of a general fact: if $A$ is an admissible set and $S$ is a structure in $A$, then every $S$-definable well-ordering of a subset of $S$ is an element of $A$.

OK, now is that sharp? Let's especially focus on the case when $M=L_\gamma$ for some ordinal $\gamma$; in this case we have $\alpha_M$ is just the least admissible ordinal $>\gamma$, which I'll call $\omega_1^{CK}(\gamma)$, where an ordinal $\gamma$ is admissible if $L_\gamma$ is an admissible set. (The standard notation is, sadly, "$\gamma^+$." I know, I know, ...)
It's worth pointing out at this point that our experiences from classical computability theory are wildly misleading here. Specifically, we classically have that $\omega_1^{CK}$ (= the least admissible ordinal $>\omega$) is the supremum of the classically-computable ordinals. This suggests that in general we should have that $\omega_1^{CK}(\gamma)$ should be the supremum of the "$\gamma$-computable" ordinals, that is, of the ordinals which are (the ordertype of) a well-ordering of $\gamma$ which is $\Sigma_1$-definable over $L_\gamma$. (At least, for "reasonably closed" $\gamma$ - say, admissible $\gamma$. Note that if $M\models ZFC$ then $M\cap Ord$ is trivially admissible, and indeed much more, so this isn't really a meaningful restriction in our context.)
This is very false in general, however; see e.g. this old Mathoverflow answer of mine. The takeaway from this is that the next admissible is generally really really big - in particular, we should be very suspicious of the upper bound above!
Indeed, the upper bound above is generally not sharp:

We have $$\alpha_{L_{\omega_1}}<\omega_1^{CK}(\omega_1).$$

(Incidentally, the ordinal $\omega_1^{CK}$ is also called "$\omega_{\omega_1+1}^{CK}$.")
The proof is via a nice trick: if $w$ is a non-well-ordering in $L_{\omega_1}$, then there is a descending sequence through $w$ which is also in $L_{\omega_1}$ (Mostowski absoluteness + regularity of $\omega_1$). This means that in $L_{\omega_1^{CK}(\omega_1)}$ we can computably tell whether a formula $\varphi$ with parameters in $L_{\omega_1}$ defines (in $L_{\omega_1}$) a well-ordering: search simultaneously for descending sequences through $\varphi^{L_{\omega_1}}$ and for isomorphisms between $\varphi^{L_{\omega_1}}$ and some ordinal. This lets us build a copy of $\alpha_{L_{\omega_1}}$ inside $L_{\omega_1^{CK}(\omega_1)}$.

More generally, if $M$ is a transitive model of ZFC with $M^\omega\subseteq M$, then:

$\alpha_M<\omega_1^{CK}(M)$, and
more generally the supremum of the $\Sigma_k$-definable well-orderings of $M$ (in the sense of $M$) has a copy which is $\Sigma_{k+1}$-definable over $M$.

In general, I suspect that both these phenomena hold for all models of ZFC, but I don't see it immediately.

So what is a good upper bound? Well, unfortunately there aren't really many natural ordinals below the next admissible but above all the "small $\omega_1^{CK}$ analogues." So I don't really have any good candidates.
Comment: So how does this result translate to my question, which isn't about set models of ZFC, but about what's actually true in the standard model of ZFC, which is a class model?
Comment: @KeshavSrinivasan Yes, I'm aware. Per my first line, "local" results of this type translate nicely to "global" results in the MK context - in fact, we often *gain* nuance when this happens since MK really only lets us talk about "one level up" from $V$. Essentially what the above says is that in a very strong way the collection of all classes **cannot** form an "admissible structure above $V$" - the ordinals so produceable are just too small. But the "flatness" of MK makes it hard to say more.
Comment: So is this basically a way of putting a (qualitative, if not quantitative) upper bound on the order types of well-ordered proper classes?  And if classes aren't enough to produce an admissible structure above $V$, how many layers do we need to produce such a structure?  Second-level classes, third-level classes, omega-level classes, or what?
Comment: Also, what is the answer to my question about whether the order-types of well-ordered proper classes can be put in one-to-one correspondence with the class of all sets?
Comment: I'm not sure what you mean by "qualitative" - I'd rather say, "not (in general) sharp." Unfortunately I think one of the takeaways from the argument above is that there's not going to be a snappy description of the relevant ordinal.
Comment: Meanwhile, your additional question is difficult to answer - what sort of thing is that "one-to-one correspondence"? Is it definable, and if so, in what sense? (Note that this all becomes vastly easier to talk about in the "local" analogue - I suggest *first* attacking that and *then* moving to the "$V$-version.")
Comment: I think I'm asking about the truth value of a specific statement in the language of MK: there exists a two-place class relation $R$ and a three-place class relation $S$ such that for any fixed $x$, the two-place relation $S(x,y,z)$ is a well-ordering on the class of all $y$ such that $R(x,y)$, and such that for any class $C$ and any class well-ordering $T$ on $C$, there exists an $x$ such that the two-place relation $S(x,y,z)$ is order-isomorphic to $T$.  And I'm guessing that that statement is false.
Comment: I just posted that as a follow-up question: https://math.stackexchange.com/q/3564954/71829


Como percorrer uma árvore dinâmica em javascript definindo o valor de suas propriedades?

Question: Boa noite, eu possuo a seguinte árvore definida pelo JSON:
  [
       {
          "roleName":"CCA",
          "children":[
             {
                "roleName":"Data_Final_Índices_CCA",
                "$$hashKey":"object:2183",
                "children":[
                   {
                      "roleName":"Datas_Índices_CCA",
                      "$$hashKey":"object:2192"
                   }
                ],
                "collapsed":true
             },
             {
                "roleName":"Data_Inicial_Índices_CCA",
                "$$hashKey":"object:2184",
                "children":[
                   {
                      "roleName":"Datas_Índices_CCA",
                      "$$hashKey":"object:2195"
                   }
                ],
                "collapsed":true
             },
             {
                "roleName":"IGPM",
                "$$hashKey":"object:2185"
             }
          ],
          "$$hashKey":"object:2179",
          "collapsed":true
       }
    ]

Cada nó "pai" pode ter n filhos e todos os filhos podem ter outros filhos.
Preciso setar o valor "false" em todos os nós com a a propriedade "collapsed", para isso preciso percorrer todos os nós, como posso fazer isso usando alguma função em Javascript? A arvore não possui tamanho nem quantidade de nós fixos.
Comment: Edite a pergunta e coloque um [mcve] com sua tentativa em abordar o problema. Anexe as mensagens de erro e tente destacar em que linha acha que o código está dando erro.
Answer: A maneira mais simples, é converter esse objeto numa String e mudar o texto com uma RegExp. Ten a vantagem adicional de não alterar o objeto inicial.

const obj = [{
  "roleName": "CCA",
  "children": [{
      "roleName": "Data_Final_Índices_CCA",
      "$$hashKey": "object:2183",
      "children": [{
        "roleName": "Datas_Índices_CCA",
        "$$hashKey": "object:2192"
      }],
      "collapsed": true
    },
    {
      "roleName": "Data_Inicial_Índices_CCA",
      "$$hashKey": "object:2184",
      "children": [{
        "roleName": "Datas_Índices_CCA",
        "$$hashKey": "object:2195"
      }],
      "collapsed": true
    },
    {
      "roleName": "IGPM",
      "$$hashKey": "object:2185"
    }
  ],
  "$$hashKey": "object:2179",
  "collapsed": true
}];

const modificado = JSON.parse(JSON.stringify(obj).replace(/"collapsed":true/g, '"collapsed":false'));

console.log(modificado);

A maneira mais complexa é criar uma função recursiva que procure essas chaves e mude o valor. O problema que isso pode gerar é mudar o objeto internamente e caso esse objeto seja usado noutro código ele não ser o que se está à espera. Podes sempre criar uma cópia antes com JSON.parse(JSON.stringify(obj));.

const obj = [{
  "roleName": "CCA",
  "children": [{
      "roleName": "Data_Final_Índices_CCA",
      "$$hashKey": "object:2183",
      "children": [{
        "roleName": "Datas_Índices_CCA",
        "$$hashKey": "object:2192"
      }],
      "collapsed": true
    },
    {
      "roleName": "Data_Inicial_Índices_CCA",
      "$$hashKey": "object:2184",
      "children": [{
        "roleName": "Datas_Índices_CCA",
        "$$hashKey": "object:2195"
      }],
      "collapsed": true
    },
    {
      "roleName": "IGPM",
      "$$hashKey": "object:2185"
    }
  ],
  "$$hashKey": "object:2179",
  "collapsed": true
}];

function recursiveSetter(obj, key, newValue) {
  if (typeof obj !== 'object') return;
  Object.keys(obj).forEach(k => {
    if (k === key) {
      obj[key] = newValue;
    } else {
      if (typeof obj[k] === 'object') {
        recursiveSetter(obj[k], key, newValue);
      }
    }
  });
}

recursiveSetter(obj, 'collapsed', false);

console.log(obj);


Is there any term used for multiple hat tricks?

Question: If a bowler takes more than three sequential wickets (say six wickets) in one over, would this be called as two hat-tricks or does this feat, however unlikely, has a different name?
Comment: It isn't remotely official or widespread, but one of my relatives came up with the term _qua-trick_ to refer to 4 wickets in 4 balls. After doing some Google searching, it appears that the term is occasionally used in football.
Comment: @Spinner, interesting. Never heard that, but it makes sense, and does appear quite after on the web :-)
Answer: Six wickets in six balls would in fact be 4 hat tricks.

1) Balls 1, 2 & 3,
2) Balls 2,3 & 4,
3) Balls 3,4 & 5 and
4) Balls 4, 5 & 6.

There is no term used other than "hat trick" for 3 consecutive wickets.
Comment: Wrong! If you take 6 wickets in 6 balls it doesn't count as 4 hat-tricks but it is count as two different hat-trick. Have a look at [this list of ODI Hat-tricks](http://stats.espncricinfo.com/ci/content/records/263626.html). Here SL Malinga's hat-trick is counted only one even he took 4 wickets in 4 balls.
Comment: @user1672694 You got me there. Nonetheless, the main purpose of my comment toward you is to keep the criticism constructive and not derisive, and ways to do that *in general* are through downvoting and commenting. "Invalid" or "pointless" or not, the purpose remains applicable.
Comment: @hims056 no you are wrong. Theres a reason why there is an asterisk. Every commentator I have ever hear commentate a hattrick then proceeds to say 'Can they get the double hattrick?'.
Comment: @user1672694 - Have you read the links I have provided?
Comment: @hims056 read my comment again
Comment: @user1672694 - I really don't understand what do you want to say.
Comment: @user1672694 [Downvoting](http://sports.stackexchange.com/help/privileges/vote-down) is an acceptable way to address "an answer that is clearly and perhaps dangerously incorrect," and [commenting](http://sports.stackexchange.com/help/privileges/comment) is an acceptable way to provide "constructive criticism that guides the author in improving the post."
Comment: Generally you do not count each goal/wicket more than once for hat tricks. For example, most people do not consider 4 goals/wickets to be "2 hat tricks" (or a "double hat trick").
Comment: @edmastermind29 let me know when downvoting comments is possible then
Comment: @user1672694 Comments are not downvoted. The privilege to downvote questions/answers are "Awarded At: 125 Reputation." You are on your way.
Comment: @edmastermind29 I was simply pointing out the invalidity of your comment. I know comments can't be downvoted, making your comment pointless
Answer: Definition of Hat-Trick by Wikipedia

a bowler taking a wicket off each of three consecutive deliveries that he bowls in a single match (whether in the same over or split up in two consecutive overs, or two overs in two different spells, or even spread across two innings of a test match or first-class cricket game).

So a single hat-trick means taking a wicket off each of three consecutive deliveries. So if a bowler takes six wickets in six consecutive deliveries, it will be considered as two [different] hat-tricks. There is no special name for this since no one has achieved this feat but we may say it double hat-trick. However if a bowler takes four wickets in four consecutive deliveries it is called as four in four but the term double hat-trick has also been used in the media*. So there is no special term for that. Everyone refer them in their own term.
* taken from Wikipedia
Comment: I am fairly sure that "double-hat trick" is conventionally used for 4 wickets in 4 balls. Note that Wikipedia _itself_ (in the bottom of the subsection linked by you; so it is not just the media) refers to five wickets in five balls as a triple hat-trick. But I think that any hat-trick, be it of the normal (3), double (4) or triple (5) variety, still counts as _one_ hat-trick. I am unsure about the quadruple (6) hat-trick, through. (Whether that would count as one trick or two tricks.) :)
Answer: A 'perfect over' of 6 wickets taken with 6 consecutive ballsbbc was achieved by Australian Aled Carey on 21 January 2017 while bowling for his club Golden Point against East Ballarat. This perfect over consisted of 2 catches, an LBW and 3 bowled.
Wikipedia and his club Golden Point tweet states this as quadruple Hat-Trick, while few media like deccanchronicle, thenews and article.wn states this as 2 hat-tricks in an over and some other media like zeenews, scroll and financialexpress states this as double hat-trick.
So, as hims056 said in his answer, there is no special term for that. Everyone refer to these hat-tricks in their own term.
Answer: 4 wickets in 4 balls may be called qadri-trick; 5 wickets in 5 balls penta-trick ; Then there is change in the over.Yet, for 6 successes in 6 consecutive events may be called hexa-trick; 7 in 7 hepta-trick; 8 in 8 octa-trick; 9 in 9 nona-trick; 10 in 10 deca-trick; 11 in 11 undeca-trick and 12 in 12 dodeca-trick! How's that!
Comment: Do you have a reference for where any of these terms have been used?
Answer: A bowler taking six consecutive wickets in a over means two hatricks not a term like double hatrick.
Comment: Do you have any references which you can use to support this answer? At the moment, this sounds like it is simply your opinion, which is not the sort of answer we look for on Stack Exchange.


Como criar aplicativo Android que utiliza softwares nativos do celular, como câmera, galeria, etc

Question: Como eu faço para utilizar os recursos do celular ?
Por exemplo:
Eu crio um app, que quando o usuario clicar em "Tal" botao, abrir a camera do celular... ou a galeria... ou despertador.
Queria aprender isso, mas nao sei nem o que pesquisar.
Comment: O que você já tentou?
Comment: Nada... mas queria conhecer esses recursos. Exemplo, eu nao sei nem o que pesquiser, ou como pesquisar pra aprender entende ? Queria que me dessem apenas um norte aqui para começar.
Comment: Pesquise primeiro como criar um app android, você pode ver a documentação também, [neste link em inglês](http://developer.android.com/intl/pt-br/develop/index.html) mas de fácil entendimento. Antes de aprender recursos, você deve aprender a mexer na ferramenta, conhecer a linguagem, seu funcionamento em si, neste link você tem tudo isso e muito mais. No mais, [tutoriais no google](https://goo.gl/b70pvx) tem bastante para começar e para tirar dúvidas ao se aventurar em criar um app, o SOpt sempre estará a disposição :)
Answer: O que você quer é resolvido usando o Intent
Uma Intent é uma descrição abstrata de uma operação a ser executada. Pode ser usada com startActivity para lançar um Activity, o broadcastIntent para enviar para qualquer componente BroadcastReceiver e startService(Intent) ou bindService(Intent, ServiceConnection, int) para comunicar com o serviço (Service) no background.
Segue a documentação: http://developer.android.com/reference/android/content/Intent.html
Antes de mais nada recomendo que estude Android e Java primeiro, segue um bom link pra isto:

https://pt.stackoverflow.com/tags/android/info

Segue alguns exemplos do uso do Intent pra estudo (não testei, faz um tempo que não trabalho com Android):
Abre a calculadora:
// activity name and package for stock calculator
private static final String CALCULATOR_PACKAGE_NAME = "com.android.calculator2";
private static final String CALCULATOR_CLASS_NAME = "com.android.calculator2.Calculator";

public void launchCalculator() {

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
     intent.setComponent(new Component Name(CALCULATOR_PACKAGE_NAME,
             CALCULATOR_CLASS_NAME));
     try {
         this.start Activity(intent);
     } catch (ActivityNotFoundException noSuchActivity) {
         // handle exception where calculator intent filter is not registered
     }
 }

Seleciona um áudio:
public void launchMusicPlayer(View view) {
    Intent intent = new Intent();
    intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
    intent.setDataAndType(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            AUDIO_MIME_TYPE);
    startActivityForResult(intent, FIND_SONG_INTENT);
}

Editor de texto:
public void launchTextEditor() {
    try {
        Intent intent = new Intent(Intent.ACTION_EDIT);
        Uri uri = Uri.parse("file:///sdcard/somefile.txt");
        intent.setDataAndType(uri, "text/plain");
        start Activity(intent);
    } catch (ActivityNotFoundException e) {
        Toast toast = Toast.makeText(this, "No editor on this device",
                Toast.LENGTH_SHORT);
         toast.show();
     }
 }

Visualizar PDF:
public void launchPDFViewer() {
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.parse("file:///sdcard/Download/somefile.pdf");
        intent.setDataAndType(uri, "application/pdf");
        start Activity(intent);
    } catch (ActivityNotFoundException e) {
        Toast toast = Toast.makeText(this, "No viewer on this device",
                Toast.LENGTH_SHORT);
         toast.show();
     }
 }

Fonte: http://www.intertech.com/Blog/android-intents-for-app-integration-call-a-calculator-play-video-open-an-editor/
Comment: Pela resposta dele nos comentarios, aparentemente ele nem sabe como programar em java para android, ou se sabe, não ficou muito claro pela pergunta e nem pela resposta nos comentarios.
Comment: @DiegoFelipe Obrigado, resposta editada.
Comment: Cara, MUITO obrigado, era exatamente isso que eu queria... Otima explicação!


Linear Regression Doubt

Question: I'm studying about Linear Regression and searching about it I found an example that was a graphics that the axis X was the Year and the axis Y was Price, but my doubt is: When we are talking about Year we need to treat that as a Time Series problem, yes? Also, Linear Regression applies just when the variables are continuous, yes?
Comment: Statistics is not that simple.  The type of data does not determine what procedure to apply.  The *problem you want to solve* is the principal consideration; everything else flows from that.
Comment: When which variables are continuous?
Answer: You can relate Price to Year using time series regression.
A time series regression model for the setting you mention could be formulated like so:
$Price_t = \alpha_0 + \beta_0 Year_t + \epsilon_t$
where $\epsilon_t$ could be temporally correlated and t = 1, ..., n. For example, $\epsilon_t$ could follow an AR(1) process.
In practice, you would need to determine what kind of process best captures the temporal dependence of the model errors.
Usually, with data collected every year, people assume that the underlying process is something like an ARIMA(p,d, q) process and then they determine the values of p, d and q which are best supported by the data.
See here for an example of time series regression with ARIMA errors in R:https://otexts.com/fpp2/regarima.html.
Comment: If you found this answer helpful, then please consider
[upvoting](https://stats.stackexchange.com/help/why-vote)
and/or
[accepting](https://stats.stackexchange.com/help/accepted-answer)
it.
Comment: Amazing! But in this case that I showed, is it wrong? Because when we are treating about ''Year'' and ''Price'' we need to use time series regression instead of linear regression, right?
Comment: Cause and effect nearly always takes place over time even for cross sectional data. Just because it does, does not require time series. In practice time series is used in specific cases, when you have specific issues to deal with. For example when X has an impact on Y at different lags rather than just immediately. As an exception to another point, Linear Probability Models are used with a dependent variable that is not interval. Whether that is legitimate is debated. You need to look carefully at the assumptions of linear regression which are often ignored.
Comment: Victor, the example you gave is consistent with trying to detect whether there is a yearly trend in the values of a continuous variable. In that setting, you could start by fitting a simple linear regression model which assumes independent errors and then check whether the ACF and PACF plots of the residuals exhibit signs of temporal correlation. If they do, you need to upgrade the model to a time series model with ARIMA errors.  There are some issues to consider in the context of time series models - check out "spurious time series regression".
Comment: Time series regression comes in different flavours, but you have to start somewhere simple when you are just beginning to learn about this subject.
Comment: in all the years I have read time series I have never encountered any I would call easy :)
Comment: I said "simple", not "easy".

Linear Regression Doubt


"Object not found" error in gls

Question: As the R very beginner I'd like to ask if anyone could help me with the following problem?
library(foreign)
reg1 <- read.spss("URL of the spss file")
library(nlme)
model1 <- gls(v1 ~ x1 + x2 + x3 + x4 + x5 + x6, correlation=corARMA(p=1), data=reg1)

Error in eval(expr, envir, enclos) : object 'v1' not found
All the variables v1 to x6 are present in the spss file. Thanks in advance for help.
Thanks Nick. I can't share the file. I tried the procedure, but I got the similar result:

library(foreign)
library(nlme)
reg1 <- read.spss("URL", to.data.frame=TRUE)
class(reg1) #check that it is indeed a data.frame
  [1] "data.frame"
colnames(reg1) #check that all column names are properly imported
  ....

[17] "x1"            "x2"            "x3"            "x4"
 [21] "x5"            "x6"
....
[97] "...."          "v1"            "...."          "...."
....

model1 <- gls(v1 ~ x1 + x2 + x3 + x4 + x5 + x6, correlation=corARMA(p=1), data=reg1)

Error in eval(expr, envir, enclos) : object 'img4' not found
Comment: It may be better to either show the _actual_ code you ran, to avoid these kinds of confusions (all too often, an assumption during the 'translation' turns out to be the real culprit). Either way: I cannot debug this since I can't run it, so your only option is to use the traceback, or do actual debugging.
Comment: The error has indeed changed (v1 -> img4). It is not clear where this last error comes from, but: re-run your code, and right after you get the error, run traceback(). This might give you/us a hint on what's wrong (as it displays the call stack at the time of the error).
Comment: Well, actually I've 'debranded' the variables' names (so as the brands were impossible to identify). img4 is not a brand, but I also substituted the name of this variable for v1 writing my post. I just forgot to change it in the message about error. So, basically, the error has not changed.
Answer: From the documentation of ?gls:
data: an optional data frame
In relation, the documentation of ?read.spss shows a parameter to.data.frame, whose default is FALSE, so typically reg1 will be a list instead of a data.frame.
The code you provided is not useful for testing on my system (as you do not provide the actual dataset), but this will probably work (disregarding library statements):
reg1 <- read.spss("URL of the spss file", to.data.frame=TRUE)
class(reg1) #check that it is indeed a data.frame
colnames(reg1) #check that all column names are properly imported
model1 <- gls(v1 ~ x1 + x2 + x3 + x4 + x5 + x6, correlation=corARMA(p=1), data=reg1)

"Object not found" error in gls


Number of possible analysis for lat, long, data for different periods in R

Question: I have a dataset here with latitude, longitude and salinity for an area. I have these data for three different cases. First case is for normal flow conditions, second is for high flow and third case is for waterlevelrise.
I want to understand how can we use these data and then make some type of analysis.
My data set is uploaded on https://www.dropbox.com/s/285iuyv6bugm48p/dataanalysisforthreetimes.csv
Some of the things that come up to my mind are:

Find the increase or decrease of salinity for each time or even say a pattern.
Mean salinity under different conditions

The code that I used to start in R is as follows:
mydata <- read.csv("dataanalysisforthreetimes.csv")
head(mydata)
library(reshape2)
data1 <- melt(mydata,"Lat","Long")

Would you suggest if I can fit any linear model to my data? Any suggested techniques are highly appreciated.
I want to use R to do the analysis. Can you suggest any reading as well?
Comment: if you make this less of a *"how can should I analyse my data"* question and more of a *"here is an example of my data I am trying to this specifically, but cannot find how to do it"*, you will probably get an answer.
Comment: flagged for migration to [cross validated](http://stats.stackexchange.com/)...
Comment: what does it mean by flagged for mig ?
Comment: Thanks for your explanation. I would try to rephrase my question.
Answer: mean salinity for all three conditions:
data1 <- melt(mydata,id=c("Lat","Long"))

aggregate(value ~ variable, mean, data=data1)
#   variable     value
#1  Highflow  4.039384
#2 Levelrise 32.238867
#3    Normal 21.153334

here is how you get the mean fro your conditions. As for linear models, you are probably best googling linear models with spatial autocorrelation in R to get your started.
Comment: Thank you so much for your time. May be this time I didn't put up question properly. I will try to make questions more precise and clear next time.


how to validate Persian Slug in laravel?

Question: My project need to validate slug and Laravel does not handle Persian slug validator.So I have to use Regex.My slugs are like These:
<code>/sony-صوتی-و-تصویری-15
/لباس-خوشگل-مجلسی
/songs-birds-15
</code>
I not found regex for pass this slugs.
Do you have a solution?
Comment: What type of validation are you looking for?
Comment: i meant ValidatesRequests but I just want a regex to match the above slugs.like this https://laravel.com/docs/7.x/validation#rule-regex
Comment: Those are very different slugs - it's difficult to help you without seeing some code
Comment: Does this answer help you? https://stackoverflow.com/q/10561590
Comment: Do you want your slug is like `product-id-value`?
Comment: each product have  slug and It is entered by the user as desired.
Answer: In this example, it only accepts Persian letters
An error is displayed if there are English letters
<code> $validate = Validator::make($request->all(), [
            'name' => 'required|regex:/^[\x{پچجحخهعغفقثصضشسیبلاتنمکگوئدذرزطظژؤإأءًٌٍَُِّ }]*$/u',

        ],
            [
                'name.regex' => 'نام باید به فارسی وارد شود',
            ]);
        if ($validate->fails()) {
            return [
                "status" => false,
                "error" => ['message' => $validate->errors()->messages()]
            ];
        }
</code>


object for my simple money recording app

Question: I am trying to make an app where people owe money to each other. let say person buy movies tickets for his friends and each ticket cost was 20 dollar. Now every one of his friend owe that person 20$.
I did made an object but, i think it is not right way to approach it. I would like know if there is a better way i can do it.
for Example
person1 to person2: $20.
person3 to person2: $20.
person2 to person1: $0.
person2 to person3: $0.
i have approached like this
<code>    var person1 = new User(1, "person1", [{"name": "person2", "amount": 0}, {"name": "person3, "amount": 0}]);
var person2 = new User(2, "person2", [{"name": "person1", "amount": 0}, {"name": "person3, "amount": 0}]);
var person3 = new User(3, "person3", [{"name": "person1", "amount": 0}, {"name": "person2", "amount": 0}]);
</code>
Comment: Not to demotivate you from creating, but you realize this already exists? https://venmo.com/
Comment: I don't think the OP is planning on releasing this commercially. I often code experiments to see how things work/for fun, to push my understanding of how existing apps work. Keep up the good work, Ismail.
Comment: I am just coding it for fun. I am learning node, express and hogan. So just using this application idea to get my hands dirty.
Answer: I wouldn't recommend to tie the "transactions" to the user itself. Keep them separately. Maybe just like this.

<code>// just an quick example using typescript

class User {
  public readonly id: string;
  public readonly name: string;

  constructor(name?: string) {
    this.name = name || 'unknown';
    this.id = Math.random(); // just an example;
  }
}

class Transaction {
  private target: string;

  public readonly date: number;
  public readonly origin: string;
  public readonly amount: number;

  constructor(origin: User, target: User, amount: number) {
    this.date = Date.now();
    this.origin = origin.id;
    this.target = target.id;
    this.amount = amount;
  }

  public changeTarget(user: User) {
    this.target = user;
  }
}

class TransactionManager {
  private static instance: TransactionManager;
  private transactions: Transaction[] = [];
  private users: { [id: string]: User } = {};

  public getInstance() {
    if (!TransactionManager.instance) {
        TransactionManager.instance = new TransactionManager();
    }
    return TransactionManager.instance;
  }

  public createUser(name) {
    let user = new User(name);
    this.users[user.id] = user;
    return user;
  }

  public lendMoney(from: User, to: User, amount: number) {
    let transaction = new Transaction(from, to, amount);
    this.transactions = this.transactions.concat(transaction);
    return transaction;
  }

  public getUserDept(user: User) {
    if(!this.users[user.id]) {
      throw new Error('user not found');
    }
    return this.transactions.reduce((dept: number, t: Transaction) => {
      return t.origin === user.id ? dept + t.amount : dept;
    }, 0);
  }
}</code>
Comment: Thank you for the suggestion. I will consider it and separate it from the user.


scrollable views in drupal 6 is needed

Question: I want to create a views with scrollable content. I've searched using google and found this : http://drupal.org/project/scrollable  but it is abandoned.
Is there anything similar to it ? I use Drupal 6.
Answer: You can download it from the "View all releases" link (near the bottom of the module's project page). That page contains a link to scrollable 6.x-1.x-dev.
Answer: Use the Scrollable Content module, select the style as Scrollable Content. Here is a quote about it (from the module's project page):

... provides a scrolling functionality for your content. Scrollable Content will give you a nice content slider preview of your site's nodes, and provides some display options.
The basic use is via blocks page, you'll find a block called "Scrollable Content" and if you want more control & you know how to use Views, you should use the Views style for Scrollable Content.

Hope it will match your requirement.

scrollable views in drupal 6 is needed


How to use tokens in a node?

Question: I added a new content type. How can I use tokens when editing a node of that content type?
For example, if I put "Hello [user:name]", the page shows the following:

As shown above, the "[user:name]" token in it is not replaced with the username.
Answer: You need a text filter to replace tokens in fields. You can configure them in admin/config/content/formats. In drupal 7 you can install the needed text filter with:
Token Filter
But this will not be ported to drupal 8 in the same way as in drupal 7:
Issue Token Filter in Drupal 8
As this is a very simple piece of code, there is an unofficial version for drupal 8:
token_filter-8.x
Comment: it works like to drupal7 or Drupal8 works differently?
Comment: With token_filter_8.x it works like in drupal 7. This is not an official drupal 8 port and I'm not sure, if this works 100 % for all kind of tokens. There may be some caching issues.
Answer: This is something one typically does with the Token Filter module. Some details from its project page:

Token Filter is a very simple module to make token values available as an input filter.
The module now supports native tokens (e.g. [site:name]) and all global tokens by default. It even allows some contextual tokens like node or user to be replaced, but currently does not encourage users to use them in the filter help text.

This module currently has a beta version for D8.
Comment: This is the definitive answer for Drupal 7

How to use tokens in a node?


Python list in list formatting the output

Question: I have a list in list as follows:
bounding_time = [['58'], ['68']]
v = [['-0.00162439495203'], ['-0.000178892778126'],]

and 58 in bounding_time correspond to first item in v and subsequently for 68. I trying to write to a file in such a way that I should get
58    -0.00162439495203
68    -0.000178892778126

However, with my code, which is:
for bt_new in bounding_time:
    bt = ''.join(map(str, bt_new))
    print bt
for v_new in v[0]:
    print v_new

I am getting
58
68
['-0.00162439495203']['-0.000178892778126']

Is there a way to format these lists to the desired output?
Comment: Could you review my answer, please, and please let me know if you have any questions.
Answer: First set up the data:
>>> bounding_time = [['58'], ['68']]
>>> v = [['-0.00162439495203'], ['-0.000178892778126'],]

Now, use zip to iterate over each sublist in each list, accessing the first item in each, and concatenating those strings with 4 empty spaces:
>>> for i, j in zip(bounding_time, v):
...     print i[0] + '    ' + j[0]
...
58    -0.00162439495203
68    -0.000178892778126

Or you can ensure you have the same width for the first column with str.ljust.
>>> for i, j in zip(bounding_time, v):
...         print i[0].ljust(6) + j[0]
...
58    -0.00162439495203
68    -0.000178892778126

Comment: @Deepak, thanks, and note that you now have enough reputation (15) that you can upvote answers that you find helpful.


Use generics with legacy code

Question: In my project, the external API we used is not genericfied, so there's a class called ItemList which is an implementation of java.util.List, it holds a list of Item objects. however in our new code we express this as List<Item>, I want to write a method that can takes both ItemList and List<Item>,
I tried this kind of signature:
public static void readList(List<?> list) {}

it works fine, but the problem is there is a cast from Object to Item inside this method, which is used when the argument is ItemList, and not necessary for List<Item>, is there a better way to do this?
Comment: @Blindy, sadly SO can't vote down for your junk comments.
Comment: Funny how you think Java's implementation of "generics" does anything to "modernize" your code, considering that they just get thrown out at the earliest convenience by the compiler... Ahh to be young and innocent again!
Comment: @Blindy:  Just try to write modern code to deal with a "legacy" API that doesn't do generics... then tear your eyes out at the sheer amount of crap you have to deal with.
Answer: If ItemList is an implementation of List, and if you know it contains Item instances, just cast it to List<Item>. You'll get a type safety warning, but it's not less safe than casting each element of the ItemList to Item.
Comment: When using raw types, you need casts. Generics were introduced to be able to avoid them. Since your legacy API still uses raw types, you still need casts. You may cast the whole list to a generic list, or cast every element to Item, it's up to you. But you won't be able to avoid casts.
Comment: Yes, but this may require users who use your API to do a casting to eliminate a warning.
Answer: Can you write your new API to handle List<Item> so it is clean moving forward, and then provide a static conversion method to act as an adapter for the legacy uses List<Item> asList(ItemList itemList)?  This way you isolate where the ugly unchecked conversion happens.
Answer: What about providing two methods - one for each parameter type.  At least you only have only one type safety warning in a known place that has been discussed and accepted:
public static void readList(List<Item> list) {
    // do something
}

@SuppressWarnings("unchecked")
public static void readItemList(List<?> list) {
    readList((List<Item>)list); // Type safety warning tucked away in here
}

Although you don't have type safety, the name of the method readItemList is at least a strong hint to coders of the list type they are expected to be passing in.
Answer: If I am reading the API correctly, java.lang.Class:getTypeParameters() looks promising.
Try:
if(list.getClass().getTypeParameters().length == 0) {
    // Code for non-generic
} else {
    // Genericized
}

Use generics with legacy code