Can't populate an array with data returned from mongoose

Question: I have the following code:
var array = [];
Collection.findOne({'name' : 'FirstItem'}, function(err, result) {
    if (err) throw err;
    array.push(result);
});

Now mongoose returns result as it should, but I can't add it to the array - it remains empty. What's the problem?
Comment: Where did you check the array? Is `Collection.findOne` not a `async` function?
Comment: does the `result`contain data?
Answer: If you write code like:
var array = [];
Collection.findOne({'name' : 'FirstItem'}, function(err, result) {
    if (err) throw err;
    array.push(result);
});
// Do something with the array.
console.log(array);

The array will be empty at there, because when you call Collection.findOne, it needs to connect to your database and retrieve the data, and this will cost time.
And for the reason not blocking your succeeding codes, it'll not just hang there and wait to receive the result, instead, it'll let other codes still run, and call the funtion you passed in when it got data, until then, your array will be empty
What you should do is move your logic that needs to use the array, in to that callback, like:
var array = [];
Collection.findOne({'name' : 'FirstItem'}, function(err, result) {
    if (err) throw err;
    array.push(result);
    // Do something with the array.
    console.log(array);
});

Comment: Thanks a lot, it now works. I am not a back-end expert and I don't have much experience with these things.


Does MongoDB duplicate subdocument with identical data?

Question: I'm completely new to MongoDB and looking at moving my base persistence code (for many projects) over to it using JDO as an agnostic layer.  So I'm asking this question from the perspective of a java developer who likes to the work with beans as the basic model unit.
My question is about subdocuments and whether they exists independently or are internally consolidated by MongoDB.  i.e. if I had a domain structure like this:
Household - collection of Persons
<code>Person
 - name
 - address

Address
 - street
 - postcode
</code>
If I had a document for a household it would have multiple Persons but each Person would have the same address.
Would each address be a distinct and separate entity within MongoDB (even though they are the same 'class' and have the same values.  Or does Mongo somehow identify that they are referring to the same entity and internally store a UID for each Address?
More importantly.  If I update the postcode for one address does that mean that every member of Household's address subdocument would reflect that change?
It seems if it does then it's straying into the relational sphere but without such referencing I can see horrible inefficiencies arising?
Answer: Mongo will not deduplicate those subdocuments for you, no.  If you want to normalize that data, you'll need to save those addresses in to a different collection (ideally) and store DBRefs to those documents when you save the enclosing documents.  Using something like morphia or spring-data can help manage those references for you.
Answer: If persisting data via JDO you have the choice of embedding the Person+Address into Household, or persisting as individual objects (just like you do with RDBMS). If storing as not-embedded then its up to you whether you have multiple copies of the same Person, or a single one referred to by multiple Households. If storing as embedded then they are embedded, so part of Household, hence info is dupd.


Override destroy and delete in Rails 3 and removing the callbacks

Question: I want to block destroy and delete in the User model only and I want to block the callback. In few words I want to block any possibility to delete a user record. I tried by overriding destroy and delete methods but they are not called and the user is alway deleted.
class User < ActiveRecord::Base
  def destroy
  end

  def delete
  end
end

I do not want to use any gem related to this, so do not cite any gem. I am not sure if overriding those methods is a good idea, probably I should just create a 'deactivate' method and leave the default delete and destroy method there, just in case I will need them in the Rails console
Comment: If you don't want to use any gem you want to re-invent the wheel ;)
Comment: If you decide to use a gem after all:  https://github.com/gregfitz23/deactivatable
Answer: Refer to Rails API Methods.
It's not necessarily a bad thing to override these methods provided you know what you're doing and the consequences. Sometimes it's the cleanest way to solve a problem.
My recommendation is looking at the following Rails API method documentation entries and ensuring you're not missing any important actions here.
#destroy
#destroy!
#delete
By creating those methods in your model, it will override anything in the inherited Rails API so it should work just fine.
Answer: I'm not sure that I understand your question fully.
One way to do this is to make the destroy and delete methods private.
You say that the methods never get called, but that the objects are being deleted anyway. How does this happen? Are you deleting them from a collection? You may need to override a class method of User rather than those two instance methods.
Comment: I presume he doesn't ever want them actually removed from the DB and instead wants them flagged as deleted.  Depending on the goals of the site and the importance of information preservation it's not an unreasonable choice to only remove such records via manual/offline DB maintenance.


Matlab - set like datatype?

Question: I need to work with Matlab again but it's long ago that I did so the last time. So I need your help (searching for "set" leads only to how to set colors of axis and so...). How can I achieve a set like behavior of an array (or any other similar datatype).
The thing is I have a initial set of vectors and want to add some new vectors to it but I don't want doubles.
Thank you in advance.
Comment: This question is about the *Matlab* computer programming language, not mathematics, and hence should be migrated.
Comment: Agree about the migration.  Meanwhile, you may want to look at the [Java collections](https://www.mathworks.com/help/matlab/matlab_external/bringing-java-classes-and-methods-into-matlab-workspace.html), which are available from within MATLAB.
Comment: sure let's migrate that (and my other matlab topics too). how?
Answer: Let Abe the $k\times n$ matrix containing your first vectors and v be the $1\times n$ vector you want to add in your "set" A. Then
B = unique([A;v],'rows') will either output you B = A if v already belongs to A or B = [A;v] if v is a new vector of the set of vectors A.

Matlab - set like datatype?


Random "words" game

Question: I was thinking about a problem and I did not know how to search for relevant theory behind it so hopefully someone can help me.
Suppose you are playing a game, where someone thinks of an object and he types its name and sends it to you so you can find out which object he is thinking of. However, even though the intention is for you to be able to guess the object correctly, the string that arrives to you has random errors. (eg He was thinking of "mathematics" and he sent "math'atics" or even "maths")
Suppose now you have been playing this game with someone for a while and you have collected a large pool of messages and classified them accordingly (with labels the name of the object they are trying to describe).
Now a new string with random errors arrives.
Can I somehow calculate the probability that I would observe this string given it is trying to describe a particular class?
So thinking of the string that arrives at you as a random variable that depends on the object it is trying to describe, can I approximate somehow its distribution?
For example, suppose the true word is "Mathematics". I collect and classify these strings: ["math", "mthmatcs","Mathemat;cs","matematsat"] = "Mathematics"
then "aPMthmtcs!" or "W?MAthemtics@" arrives. It doesn't belong in the set of previous observed words however it contains sequences of letters that seem to be very "probable" when you are in "Mathematics". Can this be made somehow rigorous?
I hope this is clear enough. Sorry for long post.
Answer: A simple-minded but possibly good-enough solution to this problem is to compare each new string to every string in your training data with Levenshtein distance, and return the class of the closest string. This can be thought of as a 1-nearest-neighbor classifier, and extended to $k$-nearest neighbors if you wish; a $k$ such as 3 or 5 might be more accurate than 1.
Comment: I thought about this but its not what I am trying to do. and I already tried it and can promise you it doesnt work well ( at least for my data)
Comment: @vounoo As you described it, the question was hypothetical rather than involving real data. Please edit your question to [provide context](http://arfer.net/w/statqgl) so you can get accurate answers.
Comment: Despite this, still as a hypothetical question this method doesnt do what I am trying to do exactly...
Comment: @vounoo In that case, I can't tell what you're trying to do.
Comment: Levenhstein distance does not capture the similarity I am trying to find. for example math and Mathematics are far away. But "math" contains subsequences of letters (mth, mat etc) that are very "probable" in the "Mathematics" class. I am looking for a way to describe this rigorously. I am sorry if you still don't understand I don't know how to explain this in a better way.
Comment: for example "asdgagghwMatheaefmatics" should go to mathematics. if no more suitable class exists. but with Levenhstein distance it probably wont
Comment: @vounoo Your best bet is to describe the real problem, rather than trying to explain the sort of solution you think would work.
Answer: I would consider approaching it from an information theoretic point of view. The twist wrt information theoretic approaches is that they are momentless and rooted in metrics such as Kullback-Lieber, mutual information criterion, minimum distance length, distance correlations, and more (take your pick).
There are several routines out there that would enable the compilation of a matrix of distance or similarity functions for non-numeric objects such as text strings. Then, based on that matrix use PCA or some related dimension reduction algorithm to create a set of component combinations. Once that's done, the final step would be to develop a "regression" model producing coefficients or weights that could be used to score new text objects and, based on their similarity to the original objects, make a probabilistic assignment(s).
The routines are out there. The one I'm most familiar with is Andreas Brandmaier's PDC (permutation distance clustering). In addition, Brandmaier has developed an R module for implementation. In his several papers, he goes into much greater theoretical depth than I am able to in this short note. This approach is worth a look and he has many ungated papers out there about it on his website at the Max Planck Institute in Germany.

Random "words" game


Intuition behind a first Chern class computation

Question: On a complex smooth algebraic surface $X$, say we have a vector bundle $F$ which fits in an exact sequence
$$0\to F\to O_X^{r+1} \to A\to 0$$
with $A$ a torsion sheaf supported on a smooth curve $C\subset X$.
Locally, on the points of $C$, the second map $O_X^{r+1} \to O_C$ is given by the natural map $O_X\to O_C$ on one factor, plus the zero map on the remaining $r$ factors. Then $F$ is the kernel of this map.
Now what I would like to understand is the fact that
$$c_1(F)=-[C]$$
The point is that I am able to compute this by applying  Whitney formula to the above sequence. What I would like to understand is an apparently much simpler/intuitive argument:
The vector bundle map $F\to O_X^{r+1}$ drops rank along $C$, hence $\det F = O_X(-C)$.
(this is at p.533 in this article)
I would very much appreciate some intuitive explanations on the behavior of Chern classes.
Answer: If you have a rank $n$ complex vector bundle $E$ on $X$, where $X$ is a compact topological manifold, and if $s_1$,...,$s_n$ are $n$ generic continuous sections of $E$, then the locus of points $x \in X$ at which the dimension of the complex span of $s_1(x)$,...,$s_n(x)$ drops (i.e. this dimension at $x$ is strictly less than $n$) forms a real cycle of codimension $2$ in $X$, whose Poincare dual is $c_1(E)$.
This can be reformulated as follows. If $\epsilon^n$ denotes the trivial complex vector bundle on $X$ of rank $n$, then given a bundle map $f: \epsilon^n \to E$ which is an isomorphism at a generic point of $X$, the locus of points $x \in X$ at which the rank of $f$ drops is the Poincare dual of $c_1(E)$. But the rank of $f$ is the same as the rank of $f^T: E^* \to (\epsilon^n)^*$, with of course $(\epsilon^n)^*$ isomorphic to $\epsilon^n$. This essentially explains the appearance of a minus sign in the formula $c_1(F) = -[C]$.
More precisely, if one has a bundle map $f$ from $E$ to $\epsilon^n$, where $E$ has rank $n$, which is an isomorphism at a generic point of $X$, and if $Z$ is the locus where the rank of $f$ drops, then $c_1(E)$ is minus the Poincare dual of the homology class of $[Z]$.
More generally, if $E$ has rank $n$ and $F$ has rank $N \geq n$ are complex vector bundles over $X$, and if $f$ is a bundle map from $E$ to $F$ which is generically injective, with $Z$ the locus of points of $X$ at which $f$ fails to be injective, then the Poincare dual of the homology class of $Z$ is $-c_1(E)+c_1(F)$.
What about the case where $X$ is a compact complex manifold, and $E$ and $F$ are holomorphic vector bundles of rank $n$ and $N \geq n$ respectively? Assume that there is a holomorphic bundle map from $E$ to $F$ which is generically injective. Can we say that the Poincare dual of the homology class of $Z$ is $-c_1(E)+c_1(F)$? In other words, is the degeneracy locus of a holomorphic bundle map $f$ which is generically injective, in the same homology class as the degeneracy locus of a continuous bundle map which is generically injective? I suspect that in general, the answer to that question is no (please check the literature though). However, if the sheaves of germs of holomorphic sections of $E$ and $F$ are locally generated by global holomorphic sections of $E$ and $F$ respectively, then I believe the same relationship holds between $Z$ and the first Chern classes of $E$ and $F$ (one place to look for a more careful statement and proof of the above would be the books on positivity in algebraic geometry by the same author, Prof. Lazarsfeld).
Comment: Dear Malkoun, thank you for your helpful answer
Comment: Dear Heitor Fontana, I have expanded my answer a little. Have a look at the books on positivity in algebraic geometry by Prof. Lazarsfeld for example. I suspect they might contain the statement you are looking for, with possibly the proof as well. My description is just a "sketch", so to speak.


How can I play my Venus Special without hurting my fingers?

Question: I have a Venus Special. It looks good but it is hard to play. My fingers hurt while playing the guitar.
What is the solution?
Comment: For how long have you been playing? If it's your first attempt at playing guitar it's normal that it hurts your fingertips until you get calouses developed.
Comment: It might help to get new strings or a lighter gauge.
Answer: Honestly, the only solution is to continue to play. Your fingers will develop calluses and stop hurting after a few weeks (for some people it may be a couple months, it varies). Just make sure that after you have developed your calluses, you continue to play, because after a few days of not playing they will deteriorate and go away, leaving you at square one again.
Edit: I was addressing the question asked, not the title of the question. I don't really see a correlation between the two.
Answer: You can try getting flat wound strings, which are much smoother than round wound strings. You should also try different gauges of string to see if you find one easier to play than another. Light gauge strings can be easier on your fingers since you don't have to press as hard.


What's the correct way to redirect the user when a Batch API job finishes?

Question: I've got a form that starts a batch job. What's the right way to redirect them after it finishes? Calling drupal_goto() in my finish function?
Answer: You can set 'redirect' in hook_batch_alter().
For example:
$batch['form_state']['redirect']['path'] = 'cart';

Comment: Do you have a sample for how that would work? It doesn't seem like the batch is a form.
Answer: drupal_goto('your/hookmenu/link', array('query' => array('destination', $_GET['destination'])));

Comment: Yeah, I know how `drupal_goto()` works I'm just curious if there's a better way, something like `$form_state['redirect']`
Comment: I don't know a better one, but an alternative is `header('Location: index.php?q=node");` But I will not use it personally. `$form_redirect['redirect']` will not work outside a form context. So drupal_goto is the only robust way to do it.
Answer: If you know the redirect path in the moment you start the batch, you can
batch_process('my/destination/path');

See https://api.drupal.org/api/drupal/includes!form.inc/function/batch_process/7
Comment: What if we have query string as well in the path. For example my/destination/path?destination=admin/content
Comment: For complex cases, it's better to use custom redirect callback.
Comment: Can you please elaborate how to do that?
Comment: Yes. 1) Read docs: https://api.drupal.org/api/drupal/includes!form.inc/function/batch_process/7 2) Pay attention to `$redirect_callback` ;)
Answer: i'm create link to form (created by form api) that runs the batch with get-parameter "?destination=myRedirectPath".
batch lanch on function form_submit() and take info about redirect after batch from url.
without "goto".


Let $A$, $B$ be subsets of $S^n, n≥2$. Show that if $A$ and $B$ are closed, disjoint, and neither separates $S^n$, then...

Question: Let $A,B$ be subset of $S^n$, $n\geq 2$. Show that if $A$ and $B$ are closed, disjoint, and neither separates $S^n$, then $A\cup B$ does not separate $S^n$.
I've thought to do it by contradiction and use the Mayer-Vietoris exact sequences, but really I have some doubts, so the appreciate any help, thanks.
Comment: Did you try to cover $S^n$ by the complements of $A$ and $B$, and write down the last portion of the Mayer-Vietoris long exact sequence? I think the solution along this way is pretty straightforward...
Comment: @Seirios: It means that its complement is not connected, which is detected by 0-th homology.
Comment: @AlexanderShamov: What it means that a subset separates $S^n$?
Answer: Let $U = S^n\setminus A$ and $V = S^n\setminus B$ then by hypothesis $U$ and $V$ cover $S^n$ so we can apply Mayer-Vietoris:
$$ H_1(S^n) \overset{\partial_*}\longrightarrow H_0(U\cap V) \overset{(i_*,j_*)}{\longrightarrow} H_0(U)\oplus H_0(V) \overset{g}{\longrightarrow} H_0(S^n) \longrightarrow 0 $$
If we assume that $n\geq 2$ then $H_1(S^n) = \{0\}$, because neither $A$ or $B$ separate $S^n$ we have that $H_0(U) = H_0(V) = \{0\}$ and the sequence is exact so we must have that $H_0(U\cap V) = \{0\}$ i.e.  $A\cup B$ does not separate $S^n$.
Comment: You probably should indicate you are using reduced homology.
Comment: I don´t think I'm using reduced homology in any part, the Mayer-Vietoris sequence is for the unreduced case.
Comment: $H_0$ of a connected space is $\mathbb Z$ not $0$.


I am trying to print some corresponding values to a character but condition always going to else

Question: I am trying to print some values specified in if condition but compiler throws errors that this variable is not declared in this scope.
```

#include <bits/stdc++.h>
using namespace std;

int main()
{
  char i, p, P, z, Z, e, E, d, D;
  cin>>i;

  if(i==p || i==P)
    cout<<"PrepBytes";

  else if(i==z || i==Z)
    cout<<"Zenith";

  else if(i==e || i==E)
    cout<<"Expert Coder";

  else if(i==d || i==D)
    cout<<"Data Structure";

  else
    cout<<"Wrong Input";

  return 0;
}

Output:-

PS E:\C++> .\a.exe
d
Wrong Input

Comment: @Amit Mittal These variables char i, p, P, z, Z, e, E, d, D; are not initialized and have indeterminate values. As result the program has undefined behavior.
Comment: Make up your mind: Is it a compiler error, or do you get the wrong output when running it?
Comment: Where is the compiler output?
Comment: it's not a compiler error it is showing the wrong output.
Comment: You should get lots of warnings about use of uninitialized variables. If you don't, make sure you turn on compiler warnings e.g. `-Wall` for GCC.
Answer: You're comparing your i with uninitialized values p, P, etc....
Did you want to compare the input character with the characters 'p', 'P'...?
#include <iostream>
using namespace std;
int main()
{
  char i;
  cin>>i;

  if(i=='p' || i=='P')
    cout<<"PrepBytes";

  else if(i=='z' || i=='Z')
    cout<<"Zenith";

  else if(i=='e' || i=='E')
    cout<<"Expert Coder";

  else if(i=='d' || i=='D')
    cout<<"Data Structure";

  else
    cout<<"Wrong Input";

  return 0;
}

Live example here.
Answer: If be honestly, it's not the "Wrong Input". In your program the "else" - condition says that the "i" doesn't equal to any variable (i, p, P etc.). You shall to initialize all of these variables. Or use such condition:
if (i == 'p' || i == 'P')

And so on.


Using OCI8 Module to See OracleDB

Question: I have an external oracle db I'd like to use to show data in views. Has anyone used the OCI8 module, if so, (sorry for my ignorance) how do we see the data? Do I need to create a custom module and hook into it? I cannot find any how to on this.
The readme says: 1) Build out OCI8OracleSelectQuery class which will mimic Drupal's SelectQuery. This would include writing an oci8_db_select() function to create these
Where do I do this? Thanks!
Comment: Are you familiar with the [Forena](https://www.drupal.org/project/forena) module, which also supports Oracle DBs?
Comment: I looked into that also...
Answer: That module provides a very basic API only; no UI, no methods to display/format data, and no integration with the Views module.
It currently provides developers with:

A database connection class for Oracle
A simple Oracle-specific version of db_query
A simple Oracle-specific version of db_query_range

and literally nothing else.
So yes, in order to see any data using this module, you're going to need to create your own module which uses the couple of query functions it provides, and displays the results in whatever way makes sense.
For something more automated, you could try the technique mentioned here to hook into Views and force it to use a different database for certain tables (which can theoretically be in an Oracle DB). I've never tried that so I can't comment on its effectiveness, or if it's genuinely even an option. Something tells me that you'd need a PDO connection to Oracle for that to work, but I might be wrong.
As an aside, the line you quoted from the readme looks like a TODO note; the maintainer is probably saying that the functionality hasn't been implemented yet, but that developers who want to make proper use of the module will probably find it beneficial to implement that per their requirements.

Using OCI8 Module to See OracleDB


Is hash always different for different strings?

Question: I try to hash path to the file with it filename by md5 algorithm, of course the filename always different in system. I'm interesting in is this hash always will be different for different files or hash can repeat?
Сan be such that I get same hash from different files? Are there any restrictions? Thanks
Comment: @Victor It's because both hash return strings that stars with "0e..." so PHP treat them as floating point numbers and they end up equal. Just use === for comparison and it will give correct results [3v4l.org/4jLl0](http://3v4l.org/4jLl0)
Comment: No, a "hash clash" or a "collision" is the term used when two different strings generate the same hash
Comment: Here's proof of clashing: http://3v4l.org/2vrMi
Comment: @JohnConde But when I print this two hash they are different, don't understand why?
Answer: It's very unlikely that you will get a hash collision on your file names, however it is possible so you may want to consider it as a potential source of bugs in your application (depending on how many strings you are going to be hashing).
You don't mention if there is any cryptographic reason for you hashing the filenames, if you do need the filenames to be securely encrypted you should use the php crypt() function instead (md5 hashing has not been considered secure for a long time http://www.kb.cert.org/vuls/id/836068)
Answer: Yes, you can potentially get hash collisions.  See wikipedia articles on the pigeonhole principle and birthday paradox to understand why.
Answer: Hash collision is a major issue today in cryptography and general computer science. While md5 is a widely known and used hash, collisions can be very prevalent in it. Collisions are unlikely to happen, but they can occur. They typically will not occur unless someone is attempting to create them.
I submit here the issue that there are 340282366920938463463374607431768211456 possible md5 hashes (since they're displayed hexadecimal style, 16 possibly characters raised to the power of the 32 character length), but there are an infinite amount of strings which can be hashed (that of course taking computational limits out of the equation).
But what is a developer to do if it's possible to have collisions?
I was recently in a meeting with a new friend of mine who runs a business that, among other things, involves cryptography. He said something that I had never thought of before. As I lack the memory to recall word-for-word, it was something along these lines: "Sure, you can fool my md5, but try to fool both my md5 and my sha256." What he was saying is that as a developer we have an enormous amount of programming options and that we should take advantage of them. We have the md5, gost, the sha-family and the list could go on. Hash your string with both a sha256 and an md5 and you'll find the chance of collisions to be lowered tremendously. In fact it will likely be lowered to the point where your chance of collision is practically nothing.
An implementation of this:
<?php
    $salt = "my_secret_salt";
    /* this should have numbers, spaces, letters, special characters, etc. */
    $stringToHash = $theUsersCookieValues;
    $time = time();
    $hash_1 = hash('md5', $time . $salt . $stringToHash);
    $hash_2 = hash('sha256', $time . $salt . $stringToHash);
    setcookie("time_created", $time);
    setcookie("user", $theUserCookieValues);
    setcookie("hash_1", $hash_1);
    setcookie("hash_2", $hash_2);
?>

While this deals with cookies, not filenames, it is still a great way to implement this principle, in my humble opinion.
Comment: Well, instead of using two hashes, you can use a larger hash with 512 bits or more.
Comment: Yes, but from purely a speed standpoint, the sha256 and the md5 take a little less time to calculate (I'm just making an assumption) than the sha512 for example. On top of this, a 512 bit hash is just 1 hash. 1 hash is still easier to fool than 2 hashes. While both ways are extremely unlikely and would take decades-upon-decades to likely find a collision for, I would still venture to guess that fooling both an md5 and a sha256 would be even less likely than fooling a single 512. That being said, one could do two 512's and 2 different salts, but that seems like overkill.
Comment: "1 hash is still easier to fool than 2 hashes." No, that's not the case as the likelihood of getting a collision on sha 512 bits is way less than the likelihood of a collision on a sha256 x likelihood of a md5 collision.
Comment: However, the collision you find for the md5 and the sha256 must be identical to each other.
Comment: As for speed of calculating a larger hash, it can be mitigated by going for a single hash with a number of bits equal to 256 + 128 bits.
Comment: " the collision you find for the md5 and the sha256 must be identical to each other." Not possible as the hashes have different size. However,  you may have two simultaneous collisions.
Comment: Consider this:
You find a collision for md5 and it's "abcd"
You find a collision for sha256 and it's "xyz"
"xyz" != "abcd" which means now you have to find another collision.
The user could come up with an exceptionally large amount of collisions, but the collisions, unless they're the actual values, will likely never be equal. If you want to be even more extreme, you could use more than 2 hashes and make finding the collision even closer to impossible.
Comment: "As for speed of calculating a larger hash, it can be mitigated by going for a single hash with a number of bits equal to 256 + 128 bits" Yes, but there are different implement the hashing functions in different ways. For example, there are faster versions of the md5 and there are slower versions even though they all produce the same results and do roughly the same thing. But yes, that's why I was guessing it was faster.
Comment: Given s1 we are looking for s2 such that md5(s1) = md5 (s2) and sha256(s1) = sha256(s2). On the other hand we are looking for the likelihood of sha512(s1) = sha512(s2). The first case gives 1/2^128 x 1/2^256. In case 2 it is 1/2^512.
Comment: "I was guessing it was faster". Indeed.


Identify the function represented by $\displaystyle \sum_{k=2}^\infty \frac{x^k}{k(k-1)}$

Question: So first I wrote it out in the terms, and I got
$\displaystyle \sum_{k=2}^\infty \frac{x^k}{k(k-1)} = \frac{x^2}{2}+\frac{x^3}{6}+\frac{x^4}{12}+\frac{x^5}{20}+...$
I know the power series for $\displaystyle ln(1+x) = x-\frac{x^2}{2}+\frac{x^3}{3}-\frac{x^4}{4}$ which is similar to the derivative of the power series from above, as
$\displaystyle \frac{d}{dx}(\frac{x^2}{2}+\frac{x^3}{6}+\frac{x^4}{12}+\frac{x^5}{20}+...)=x+\frac{x^2}{2}+\frac{x^3}{3}+\frac{x^4}{4}+...$
My question is, where do I go from here? How would I make it so the series is similar ln(1+x)? Or am I even going down the right route when it comes to solving this problem? Any help would be appreciated.
Answer: Hint A. You have $f'(x)=-\ln(1-x)$. Can you integrate this?
Hint B. Alternatively, use partial fraction decomposition on $\displaystyle\frac{1}{k(k-1)}$.
Comment: Thanks so much for the help
Answer: What you could have done is to differentiate twice to get
$$\left( \sum_{k=2}^\infty \frac{x^k}{k(k-1)}\right)''=\sum_{k=2}^\infty x^{k-2}=\frac 1 {1-x}$$making
$$\left( \sum_{k=2}^\infty \frac{x^k}{k(k-1)}\right)'=-\log(1-x)$$
$$ \sum_{k=2}^\infty \frac{x^k}{k(k-1)}=x+(1-x) \log (1-x)$$
Comment: I'll keep that in mind for future problems, thank you
Comment: It may be worth verifying each integration has the right integration constant.
Answer: You're very close.  Since $$\log (1 + x) = x - \frac{x^2}{2} + \frac{x^3}{3} - \frac{x^4}{4} + \cdots,$$ we have $$- \log (1-x) = x + \frac{x^2}{2} + \frac{x^3}{3} + \frac{x^4}{4} + \cdots.$$  Then integration term by term gives $$- \int \log(1-x) \, dx = \frac{x^2}{2} + \frac{x^3}{6} + \frac{x^4}{12} + \frac{x^5}{20} + \cdots.$$  So all you need to do is figure out how to perform the integration.  Do be careful, since the RHS should be zero when $x = 0$, so an antiderivative on the LHS should also be zero when $x = 0$.
Comment: Thank you so much for the help, I greatly appreciate it.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\sum_{k = 2}^{\infty}{x^{k} \over k\pars{k - 1}} & =
\sum_{k = 2}^{\infty}{x^{k} \over k - 1} -
\sum_{k = 2}^{\infty}{x^{k} \over k} =
\sum_{k = 1}^{\infty}{x^{k + 1} \over k} -
\pars{-x + \sum_{k = 1}^{\infty}{x^{k} \over k}}
\\[5mm] & =
\pars{1 - x}\pars{-\sum_{k = 1}^{\infty}{x^{k} \over k}} + x
\\[5mm] & =\
\bbox[10px,#ffd,border:1px groove navy]{\large\pars{1 - x}
\ln\pars{1 - x} + x} \\ &
\end{align}


How can I update ContentItem from a background task in Orchard?

Question: The ContentItem I'm updating has a bool variable and I only know ContentItem Id. How can I update this variable from controller? I'm planning to send ajax request to the controller and then update.
I have a checkbox and I want to change bool variable when the user clicks it.
I tried to update it with ContentManager.Query() but I failed. This is the part where I'm planning to send the request.
$("li").click(function () {
    if ($(this).hasClass('checked')) {
        $(this).removeClass('checked');
        //Make State False $(this).attr("id")
    } else {
        $(this).addClass('checked');
        //Make State True $(this).attr("id")
    }
});

Answer: In your controller, assuming you have injected a IContentManager instance named _contentManager, you should be able to do something like this (I'm assuming what you called a "bool variable" is a Boolean field named "State" under some part):
public ActionResult SetState(int contentItemId, bool state) {
    var contentItem = _contentManager.GetLatest(id);
    if (contentItem == null) return HttpNotFound();
    var field = contentItem
        .Parts
        .SelectMany(p => p.Fields)
        .FirstOrDefault(f => f.Name == "State") as BooleanField;
    if (field != null) {
        field.Value = state;
    }
    return RedirectToAction("SomeAction");
}


Get the Dimensions of the Theme Logo

Question: In Drupal 7 theme settings, you can upload a logo.
How do you print the width and height of this logo in your theme?

Background Research:
theme_get_setting('logo') lets you get the path of a logo uploaded in the theme settings.
image_get_info lets you get the height and width of an image.
However, image_get_info(theme_get_setting('logo')) does nothing.
Answer: You can use the following code. (Add error checking where necessary.)
  $image_url = parse_url(theme_get_setting('logo'));
  $image_path = str_replace(base_path(), realpath(DRUPAL_ROOT) . '/', $image_url['path']);
  $info = image_get_info($image_path);
  $height = $info['height'];
  $width = $info['width'];

As side note, theme_get_settings('logo_path') returns the path of the uploaded file used as logo. While theme_get_settings('logo') always return a value, whatever the logo is the default one, or one that has been uploaded, theme_get_settings('logo_path') returns a value when the logo has been uploaded.
The value returned for "logo_path" is similar to public://logo.png. To obtain the real path, you would use code similar to the following one.
  if ($image_uri = theme_get_settings('logo_path')) {
    if ($wrapper = file_stream_wrapper_get_instance_by_uri($image_uri)) {
      $image_path = $wrapper->realpath();
    }
    elseif (!empty($image_uri)) {
      $image_path = realpath($image_uri);
    }
  }

Comment: Correct me if I'm wrong. You can also use url() with absolute and aliased keys set to TRUE and path set to the front page.  It will give an absolute URL to the front page so you can str_replace.
Comment: If there aren't modules implementing `hook_outbound_alter()` that alter the URL for the front page, it can work too.
Comment: Thanks! I used to put it everywhere even for files. Thanks for the outbound alter tip. Even though it's not used everywhere that can beat my bad habit.
Answer: The call to theme_get_setting('logo') gives you the URL of the logo, not the path (which is what you need in order to use image_get_info).  The reason your call to image_get_info returns nothing (actually FALSE) is that you're feeding it garbage.  As the old saying goes: GIGO.
You need to do something like the following:
$filepath =  $_SERVER['DOCUMENT_ROOT'] . base_path() . path_to_theme() . '/logo.png';
$image_info = image_get_info($filepath);
$width  = $image_info['width'];
$height = $image_info['height'];

(My method for sniffing the $filepath is probably not optimal, as it assumes the logo file is named "logo.png", which is not always the case, but I hope you get the idea.)

Get the Dimensions of the Theme Logo


Sessão em Laravel não funciona em outra página

Question: Estou trabalhando em um projeto com laravel, nele criei uma variavel de sessão que pega um parâmetro da url da seguinte forma:
<code>if(!empty(Input::get('lang'))){
    $lang = Input::get('lang');
    Session::put('lang', $lang);

} else {
    $lang = "es";
    Session::put('lang', $lang);
}

if(Session::get('lang') == 'pt-br'){
    App::setLocale("pt-br");
}
</code>
Dessa forma a sessão só está funcionando nessa página, quando tento usar em outra página não consigo, alguém poderia me ajudar?
Comment: Veja na pasta config o arquivo session.php e veja sua lifetime.
Comment: Está com o valor padrão, 120. Mesmo que eu altere para um valor bem alto continua do mesmo jeito.
Comment: Ela vem vazia na outra página ?
Comment: O retorno é NULL.
Comment: Tem algum erro de lógica ai! verifique melhor o código, ou então coloque todo o código!
Comment: @LucianoAlexandre uma dica seria você criar um middleware para fazer esse tratamento do idioma, no middleware você pode pegar o parâmetro lang na URL e setar o idioma correto e caso não tenha o parâmetro você seta o idioma default.
Answer: A session() do Laravel trabalha de diversas maneiras, como podemos ver na documentação. Contudo, se está usando a forma padrão será necessário dar um reflash() ou um keep() em sua sessão para manter em uma próxima página:
<code>$request->session()->reflash();
</code>
ou
<code>$request->session()->keep('lang');
</code>
Utilizando o $request como a variável da requisição.
Espero ter ajudado!
Comment: Ajudou sim, mas poderia me esclarecer mais um detalhe, o que é uma variável de requisição? Como faço para usar?
Comment: Claro! Essa variável já vem automático em uma requisição quanto dá um *get* lá em seu routes.php. Vou postar um exemplo...
Comment: Aqui tem um exemplo... lá no seu arquivo de rotas há um *get* para um determinado controller, certo? com uma função, por exemplo *listar*. Na função dentro do controller a função *listar* deverá estar da forma que está aqui neste aquivo, com a variável *request*: https://gist.github.com/evertramos/860bba5f8a4c672c829d662af3fc3b13 veja esse modelo.
Comment: É possivel criar uma variável de sessão sem usar uma variável de requisição?
Comment: A variável de requisição é padrão do Laravel... não sei se tem como criar a variável de sessão fora da requisição, pois a sessão está gravada justamente na requisição de vai e volta do cliente.
Comment: Ao tentar usa-la estou recebendo o seguinte erro: Argument 1 passed to HomeController::updateIdioma() must be an instance of Illuminate\Http\Request, none given
Comment: Um detalhe que pode ser importante é que estou usando a versão 4.2 do laravel.
Comment: Tem de referenciar no Controller. Eu uso 5.2
Comment: O meu código está assim no controller:                                                                                public function updateIdioma(Request $resquest){
            if(!empty(Input::get('lang'))){
                    $lang = Input::get('lang');
                    $langAtual = $request->session()->get($lang);
                return   View::make('auth.registration');                                                                                }
        }
Comment: Tente fazer os modelos da documentação e a parir de lá parta para os exemplos antes de colocar em produção.
Comment: Acredito que essa estrutura não é compativel com a versão 4.2.
Comment: Não entendi o porque de usar `reflash`, sendo que o AP não usa `flash` em nenhuma parte do código.  Quando se usa `put`, a sessão deveria funcionar com  `get` normalmente.


Vetor por Parâmetro em C

Question: Estou precisando passa a posição de Vetor por parâmetro como segue código, minha função recebe o endereço e modifica diretamente a variável passada por parâmetro.
Porém o programa para de funcionar e fecha durante a compilação. Alguém pode me ajuda??
for(i=10;i>=0;i++)
    FPVazia(&Buckets[i]);

void FPVazia(TipoPilha *Pilha)

Comment: O laço nunca para. Começa em 10 e vai sempre somando um, nunca se aproximando da condição de parada
Comment: Sempre inclua o código, não uma imagem com ele. Editei a pergunta.
Answer: Quando se trabalha com vetores, não se deve colocar o & para passar o endereço de memória pois ele já recebe desta forma (somente com vetores).
Posta o restante do código, pois estás passando um elemento de vetor, mas na assinatura do método ele recebe uma estrutura de dados pilha.
Teu código pode ser assim:
for(i = 9; i >= 0; i--)
    FPVazia(Buckets[i]);

Ou assim:
for(i = 0; i < 10; i++)
    FPVazia(Buckets[i]);

Answer: Neste seu caso não é necessário colocar o & antes do vetor, vamos analisar o porque disso, sua função é a seguinte void FPVazia(TipoPilha *Pilha) note que o que você pede como parâmetro é um ponteiro para uma região da memória, este que será interpretado como um tipoPilha, e quando você o chama você está passando o seguinte, FPVazia(&Buckets[i]);, e porque isto está errado, aqui caímos na definição do que é vetor, um vetor é um ponteiro para uma região de memória, esta que seria a sua primeira região de memória do vetor, índice 0.
Então para facilitar o seu entendimento, para você entender melhor o que você fez, uma outra forma de escrever o que você fez é a seguinte  FPVazia(&(TipoPilha*)(Buckets + i));, logo você nota que o que você está passando para a sua função é o endereço de memória do seu ponteiro e não da posição do seu vetor, pois um vetor já é um ponteiro.
Para arrumar isto basta tirar este &, ficando da seguinte maneira  FPVazia(Buckets[i]); ou  FPVazia((TipoPilha*)(Buckets + i));, é importante ressaltar que estas duas maneiras são equivalentes, a unica diferença entre elas é que uma é omitido o ponteiro e a conta de posição, enquanto a outra não.
A segunda maneira é feita utilizando aritmética de ponteiro, um ponteiro * por si só sempre é interpretado como um inteiro em C, então para evitar que algum erro ocorra sempre quando estiver utilizando aritmética de ponteiros lembre-se de fazer o casting, para que o ponteiro seja interpretado de acordo com o tipo que você está utilizando, se a variável buckets fosse um vetor de inteiros você poderia deixar apenas FPVazia(*(Buckets + i));, mas como não é faça o casting. Outro fato importante é que como já dito anteriormente você fazer Buckets[i] ou (TipoPilha*)(Buckets + i) é a mesma coisa, eles são equivalentes, pois quando você faz Buckets[i] o que o computador interpreta e faz é (TipoPilha*)(Buckets + i).
Outro erro que está explicito é o do for, você inicia o seu i em 10, e depois incrementa ele, só que sua condição diz que para i >= 0 você vai fazer o que há dentro do for, mas está condição sempre será verdade logo o seu loop será infinito, para arrumar isto basta decrementar o seu i, ou você inicia o i em 0, na condição coloca i < 10, e dai incrementa o i.
Indo direto para a resposta, você pode fazer o seguinte:
for ( i = 10 ; i >= 0; i-- )
    FPVazia(Buckets[i]);

ou
for ( i = 10 ; i >= 0 ; i-- )
    FPVazia((TipoPilha*)(Buckets + i));

ou
for ( i = 0 ; i < 10; i++ )
    FPVazia(Buckets[i]);

ou
for ( i = 0 ; i < 10 ; i++ )
    FPVazia((TipoPilha*)(Buckets + i));

Vetor por Parâmetro em C


Pass props to the first child using this.props.children

Question: I know the way we pass props to children when using this.props.children the following way:
React.Children.map(this.props.children, (child: any, index: number) => {
    return React.cloneElement(child, {
                Visibility: this.state.visibility,
        });
});

To pass prop to only the first child I can use the index and wrap the cloneElement call in an if (index === 0), but this won't stop map from interating over all the children.
I'm wondering if there's a way I can break the loop right after index 0 is reached. Thanks!
Comment: If you only render the first child, what about the other children?
Answer:
I'm wondering if there's a way I can break the loop right after index 0 is reached. Thanks!

Don't use map at all, then, if you only want the first child.
const child = (Array.isArray(this.props.children) ? this.props.children[0] : this.props.children) || null;
return child && React.cloneElement(
    child,
    {Visibility: this.state.visibility }
);

That first bit:
const child = (Array.isArray(this.props.children) ? this.props.children[0] : this.props.children) || null;

...guards against the fact that this.props.children is only an array when there are multiple children (details); otherwise, it's the single child passed, or undefined if no children are passed (which we convert to null so we can directly return it from render).
Then the return child && guards aginst the possibility there were no children at all.
Example with all those situations:

class Example extends React.Component {
  constructor(...args) {
    super(...args);
    this.state = {
      visibility: true
    };
  }
  render() {
    const child = (Array.isArray(this.props.children) ? this.props.children[0] : this.props.children) || null;
    return child && React.cloneElement(
        child,
        {Visibility: String(this.state.visibility) }
    );
  }
}

const Child = props =>
Visibility: {props.Visibility}
;

ReactDOM.render(

    <Example />
    <Example><Child/></Example>
    <Example><Child/><Child/></Example>

,
  document.getElementById("root")
);

Comment: @ZeroDarkThirty - It's a "guard" against the possibility there are no children at all.
Comment: When there is only one child then `this.props.children` is an `object` instead of an `array`.  In that case `this.props.children[0]` will be undefined. It would be better to check that case in your code.
Comment: Can you explain what the `this.props.children[0] &&` is for?
Comment: @PrakashSharma - Heaven help us, really? (Goes off and verifies.) ***sigh*** What poor design. Thanks for letting me know, fixed.
Answer: Since you only need the the first item, there is no need to loop through them.
React.Children.toArray() will always give you an array, regardless if you have one or multiple children, which saves you some of the checks in T.J's answer.
So here is a slightly shorter (and imo cleaner) solution:
  const child = React.Children.toArray(children)[0];
  if (child) {
    return React.cloneElement(child, {Visibility: this.state.visibility});
  }
  return null;

React.Children.toArray(children)
Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.


Help on simple comparison of means

Question: I have two groups (control and experimental). I want to test whether increased irrigation will affect clutch size of lizards. In order to do this, I need to have separate plots within the irrigated areas and within the control areas, in order to fence off the lizards. I am hoping to do a power analysis and determine how large my sample size needs to be. For instance, I could fence off four individuals in five different irrigated areas and fence off four individual in five different control areas....
(4 individuals in 5 plots for irrigated and 4 individuals in 5 plots for control)=40 individuals
My first question is, what type of analysis would I carry out? ANOVA? Or is this a nested design? Can I compare the mean of all lizards in the irrigated vs control? And also compare within irrigated and within control?
My second question is, once I know which test, how do I determine sample size needed to see a true effect?
I'm probably over thinking this! :)
Answer:
This feels like an ANOVA to me. A single factor ANOVA. You could do
two-way ANOVA, but I'm not sure what your other factor is. Treatment
is a factor. But location could be the other? i.e. the 10 blocks you
are dividing up the area into. Then you would have to be able to
randomly assign treatment within the blocks that you divide.
You could just do 20 irrigated and 20 control, but not sure that's
what you want. If not this is like a randomized block design.
As of right now you do not have a nested design. If you imagine your
setup as just 20 irrigated and 20 control, and you took the other
factor (besides treatment) to be the individual lizards, then a
nested design would be if you then asked...Does clutch size increase
between male and female lizards consistently differ? Then you could
have, $$E[Y] = SEX + SEX/LIZARD + TREATMENT$$
Yes you can compare the individual means. Given the one-way ANOVA
setting, if we can reject $H_0$ then we know that at least one of the
factor level means is different. Ideally, we'd like to know which of
the factor level means is different and in what way they are
different. For this you can do pairwise comparisons with confidence
intervals.
In a two-way ANOVA setting you have factors A and B, and then you have the factor levels, a and b. So we have ab total treatments under study and if all of these are included in the study we have a complete factorial study where a two-way anova with 5 and 4 levels for the two factors gives 5*4 = 20 total levels and we need a minimum of 20 observations.

I may come back and edit this more but I'd like to hear from some other people too.
Comment: Upvoting in order to (hopefully) at least award half the bounty. I don't think some of the points are correct, but on the other hand there are some good comments in there.
Comment: @Glen_b Thanks. Feel free to comment on changes and I can edit. I'm no anova expert, but it just kind of felt right here.
Comment: For a full bounty I'd be looking for something with better justification than feelings. I wouldn't say I'm an expert either, but I think you'd need to consider than within-plot there'd be more similarity than across plot (e.g. consider this in the case of the controls), implying that it's not simply one-factor fixed effects anova; there should be some accounting for the "within plot" similarity (at the least some tendency to be higher or lower together ... implying at the least some form of intraclass correlation)
Comment: The reason this didn't get the auto-award of the half-bounty in the end was because mine was the only upvote; it requires at least two upvotes for it to go through.
Comment: @Glen_b No problem. I just wanted to share my thoughts and maybe hear from other people.

Help on simple comparison of means


Daylight savings Linux errors 1970-1980

Question: I get one hour time difference in the year 1970 when running the following python script on my Ubuntu machine and my Windows machine.
$ python3 -c "
> import time
> import datetime
> print(time.strftime('%x %X%z %Z'))
> print(datetime.datetime.fromtimestamp((87*24+2)*60*60).isoformat())"

Ubuntu 16.04 / Python 3.5.2 says:
04/03/17 15:37:07+0200 CEST
1970-03-29T03:00:00

Windows 10 / Python 3.5.1 says:
04/03/17 15:37:06+0200 Västeuropa, sommartid
1970-03-29T04:00:00

(The Swedish text under Windows means CEST.) So the clock is correct, and I think the timezone and DST are too. I think Windows gets the result correct, at least it's at that time DST should have happened. On Ubuntu DST is not showing up until ten years later at April 6, 1980 (one week after Windows' DST at March 30, 1980; which I also think is correct), but thereafter everything seems dandy.
Is this a software bug? Within Python? Ubuntu? Or are there further settings I need to do somehow? I suppose there is little chance this is a calendar quirk not properly special-cased by Python/Windows?
Comment: Is the time you are converting exactly on the DST boundary?  Do you have a link to a reference for the DST rules in your time zone?
Comment: ( one may enjoy a view on maintaining a TZ-aware datetime application >>> https://youtu.be/-5wpm-gesOY )
Comment: What are the actual Ubuntu, resp. W10 locale TimeZone setups?
Comment: @JohnZwinck: no 15:37:07 is never on any DST boundary ever - that would be lunacy. If you like you can look at Sweden in [wikipedia](https://en.wikipedia.org/wiki/Daylight_saving_time_by_country#Rules_as_of_2017). I don't know what "W10 locale" mean?
Comment: @user3666197: bawhawhaw! ;)
Comment: @JonasByström: you asked this question but a lot of time passed and perhaps you forgot what it was saying.  You now tell me that 15:37:07 was not the DST boundary, but if you re-read your own question you will see that was the "current" time when you asked the question, rather than the time that the question is about.
Comment: @JohnZwinck: I've written no such thing.
Answer: Three years in. Took me a couple of hours of digging to find out. The reason is there is no timezone transition data under Linux for that time:
$ zdump -v Europe/Stockholm -c1900,1981
Europe/Stockholm  Sun May 14 21:59:59 1916 UT = Sun May 14 22:59:59 1916 CET isdst=0 gmtoff=3600
Europe/Stockholm  Sun May 14 22:00:00 1916 UT = Mon May 15 00:00:00 1916 CEST isdst=1 gmtoff=7200
Europe/Stockholm  Sat Sep 30 22:59:59 1916 UT = Sun Oct  1 00:59:59 1916 CEST isdst=1 gmtoff=7200
Europe/Stockholm  Sat Sep 30 23:00:00 1916 UT = Sun Oct  1 00:00:00 1916 CET isdst=0 gmtoff=3600
Europe/Stockholm  Sun Apr  6 00:59:59 1980 UT = Sun Apr  6 01:59:59 1980 CET isdst=0 gmtoff=3600
Europe/Stockholm  Sun Apr  6 01:00:00 1980 UT = Sun Apr  6 03:00:00 1980 CEST isdst=1 gmtoff=7200
Europe/Stockholm  Sun Sep 28 00:59:59 1980 UT = Sun Sep 28 02:59:59 1980 CEST isdst=1 gmtoff=7200
Europe/Stockholm  Sun Sep 28 01:00:00 1980 UT = Sun Sep 28 02:00:00 1980 CET isdst=0 gmtoff=3600

Who needs the years between 1917 and 1979 anyway? Computing is the future, not the passed. :D

Daylight savings Linux errors 1970-1980


How do you make a button that adds a number

Question: Can someone explain some way for me to change this to actually add the numbers? I am new to coding and also using notepad so its not giving me errors in the syntax.
My JavaScript:
function street() {
    var x=Math.floor(Math.random()*2 + 1);
    var z=document.getElementById("test")
    if (x == 1) {
        alert('This should add 1');
        z.innerhtml = z + 1
    }
    else if (x == 2) {
        alert('This should add 2');
        z.innerhtml = z + 1;
    }
}

And my HTML:

Adding
`

0

<button type = "button" onclick "street()">Add

Comment: Welcome to Stack Overflow! Um, *please* go read the [editing help](http://stackoverflow.com/editing-help/) for how to format code (and other things) in your question (and also answer).
Comment: And define `onclick=` correctly, and don't use an Element as a number.
Comment: Put the script after your HTML, or use an `onload` function, it's also `innerHTML`, and you'll have to wrap that in `parseInt()` to convert that to a number.
Comment: Also, notice you're trying to close your button with a `` tag. Change that to ``.
Answer: z.innerHTML = parseInt(z.innerHTML) + 1; // or 2. And you missed the = after your onclick (along with many other syntactical oversights already pointed out).
Comment: Let me add some value to the answer so OP knows exactly what is going on. Even if the inner html of your variable `z` is a number, it's considered a string, text etc. You may ask "Well why doesn't it just auto parse it into a number, why can't it be smart?" Because `"1"+"10"` is a string concatenation which just gives you back a new string `110` in this case. In other words the `+` operator does different things based on the data type.
Answer: My own take would be:
function street() {
    var x = Math.floor(Math.random()*2 + 1),
        z = document.getElementById("test"),
        // parses the text of the element, turning it into a base-10 number:
        n = parseInt(z['textContent' || 'innerText'], 10);

    // sets the text of the element to be the sum of
    // the current number + generated number:
    z['textContent' || 'innerText'] = n + x;
}

JS Fiddle demo.
The reason to use parseInt() is because the + operator will either add two numbers together or concatenate two strings. If you mix strings and numbers the type of the number is coerced to be a string, and '1' + 2 > '12'.
Therefore:
1 + 2 // 3
'1' + '2' // '12'
'1' + 2 // '12'
1 + '2' // '12'

My use of ['textContent' || 'innerText'] (W3C approach or MS approach) is to avoid accidentally picking up any serialised HTML elements that might have been appended to the 'test' element.
Incidentally, this line:
var z=document.getElementById("test")

finds a DOM node, not a string; to find the string contained within the DOM node you need to use either textContent, innerText or innerHTML (the latter is the simplest, and most cross-browser compatible, but will fail if the numbers are wrapped in any child elements).
I'd also suggest moving away from obtrusive JavaScript, and binding the event-handler outside of your HTML (this makes future modification easier, since there's less hunting down of onclick event-handlers to modify function-calls); in the first instance this involves giving the button an id by which to select it:
// getting a reference to the DOM node:
var button = document.getElementById('button');

// binding the function to the event of the button being clicked:
button.onclick = street;

JS Fiddle demo.
Alternatively:
// get all the button elements:
var buttons = document.getElementsByTagName('button'),
    // select the first of those elements:
    button = buttons[0];

button.onclick = street;

JS Fiddle demo.
Preferable (under contemporary browsers that implement DOM level 2 and/or 3):
var buttons = document.getElementsByTagName('button'),
    button = buttons[0];

button.addEventListener('click', street);

JS Fiddle demo.
Answer: I remember when I was new to coding as well. There are a number of issues here.
First of all, your html has to exist before the JavaScript can use it. The browser will load page elements from top to bottom so, without any clever tricks, your JavaScript needs to be below your html.
Second, the onclick attribute is sort of a no-no in the JavaScript world because the way it works is really inefficient. You can actually handle it better through actually JavaScript.
Then there's the matter of the actual code mistakes. Here's how it should look:

Adding

0

<button id="mybutton" type="button">Add</button>

Then it's best to put your JavaScript into its own file, but if you have it on the page you'd do this:

EDIT:
As far as adding the numbers is concerned, when you pull out some innerHTML, it is always in the form of text. When you try to add text to text or a number to text, you always get text. So, for example, "4" + 2 equals "42" and "4" + "2" also equals "42". The purpose of the parseInt function is that it turns your text into an ACTUAL number that can be added to other numbers. When you drop your new number back in to the innerHTML, it is converted back to text again.
Comment: To be more clear, `parseInt` will turn your text into a number. You need that to do real math. Also, JavaScript is case sensitive so `innerhtml` won't work. It needs to be `innerHTML`. By assigning the `street` function to the button with JavaScript, the browser won't have to fire up the JavaScript compiler whenever you click the button. Just a little efficiency boost there.
Comment: All of the answers except for @JoshBjelovuk are missing the point that the OP doesn't understand the difference between a number as a string and a number as a float data type. Teach a man to fish, don't just give him one.
Comment: @LéMuffinMan: not to be unduly picky, but I think I definitely covered that point...
Comment: I think you answered as I was writing it, sorry. Unfortunately I can't go back and edit it.
Comment: No problem, I tend to do a lot of editing after posting the initial answer, with the hope of adding further value as I go. But I thought that was in my initial post (though I could, of course, be quite wrong; edits do tend to blur together).
Answer:

Adding

0

<button type="button" onclick="street()">Add</button>

this will increment the value each time you click the button


sou novo em java e esssa linha de código está dando erro

Question: import  javax.swing.JOptionPane;
public class teste {
    public static void main(String[] args) {
        JOptionPane.ShowMessageDialog(null,"sla");
        System.exit(0);
}

}
Answer: Você colocou: ShowMessageDialog, com o 's' maiúsculo:

Correto:

JOptionPane.showMessageDialog(null, "sla");

Veja a imagem do código:
Comment: Continua com o erro :(
Comment: Não foi possível localizar nem carregar a classe principal teste
Comment: O nome da classe deve ser igual ao do nome do seu arquivo.
Comment: Tira um print da tela do seu editor e mande-a aqui, por favor.
Comment: Refaça o projeto, mas com os nomes corretos, a saber: nome da classe, nomes dos métodos. Aparentemente, o eclipse está procurando uma classe chamada 'este'.
Comment: ok kkkk eu me atrapalhei aqui, vou fazer isso


Homestead Laravel 5.3.29 No input file specified

Question: Stack:

Ubuntu 16.04
Laravel 5.3.29
Vagrant 1.9.1
Homestead

I'm running: vagrant up from ~/Homestead/
This is my yaml from ~/.homestead/:
---
ip: "192.168.10.10"
memory: 2048
cpus: 1

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/Code
      to: /home/vagrant/code

sites:
    - map: homestead.app
      to: /home/vagrant/code/blog/public/

databases:
    - homestead

variables:
    - key: APP_ENV
      value: local

I've also edited /etc/hosts:
192.168.10.10  homestead.app
In my local folder "~/Code/blog/public" and in vagrant ssh "home/vagrant/code/blog/public" - exists.
When I go to http://homestead.app - it shows me this error: No input file specified.
Any help would be appreciated.
Comment: try by removing the trailing slash from `/home/vagrant/code/blog/public`. and the error means nginx document root is not correct for homestead.app.
Comment: @Ramer Is this the first time you edited `Homestead.yaml` or are you trying to update an already once configured `Homestead.yaml` file. If you're trying the latter one you need to do `Vagrant reload --provision`.
Answer: nginx cannot find your index.php because the path to your public folder has a trailing slash.
ip: "192.168.10.10"
memory: 2048
cpus: 1

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/Code
      to: /home/vagrant/code

sites:
    - map: homestead.app
      to: /home/vagrant/code/blog/public/ <-- remove this trailing slash

databases:
    - homestead

variables:
    - key: APP_ENV
      value: local


How to specify a non MLE prior for a naiveBayes model in R?

Question: I am just learning R, and am aware that the package e1071 has a naiveBayes method that takes in predictor and class membership, and estimates the class prior using the relative frequency (ML estimate).
I would like to see the impact of having a sample that is not balanced across classes (let's say male, female are represented in 3:7 ratio in the available data), when I know that for the population I am interested in, the prior of male, female would be much closer to 0.5:0.5 than 0.3:0.7. The skewed representation is due to practical problems in sampling/surveying.
I've tried doing a down-sampling of the female subset to make the training set reflect the 1:1 ratio. Is there a way of using naiveBayes with a pre-specified prior that is not reflected in the relative frequency in the data? I've looked through the documentation on e1071::naiveBayes and there does not seem to be any way of specifying my own prior.
Is there another package that does that?
Answer: If you are looking for an implementation of the naive Bayes algorithm allowing for the use of prior, you should probably take a look at the klaR package, and its NaiveBayes() function which has
prior: the prior probabilities of class membership. If unspecified,
       the class proportions for the training set are used. If
       present, the probabilities should be specified in the order
       of the factor levels.

Answer: This is an ugly, ugly solution, but if you're locked into e1071, you can pass the 'raw' option to predict, which will give you the probabilities of each class.
You could then "correct" these by dividing out the "empirical" prior (i.e. the one from your sample) and multiplying them by the true population prior.


I'm trying to use the likebox plugin on my website with the "iframe" option and it's not working

Question: I coped and pasted the code that is supplied, and the i frame is displaying with a "page cannot be found". Does anyone know if this is just a bug? Or if they're not maintaining the "iframe" option anymore?
Answer: Facebook is still using the iframe option. Did you put in the link to your Facebook page? You might try using the tool again. http://developers.facebook.com/docs/reference/plugins/like-box/


How to express a jQuery selector containing an XML namespace?

Question: I am trying to write my selector for jQuery. The attribute is xlink:href and the value is #_SAPGUI-icons_0_s_wfwire. I tried to construct it like this:
$('[xlink:href="#_SAPGUI-icons_0_s_wfwire"]')

I get a syntax error because of the expression [xlink:href="#_SAPGUI-icons_0_s_wfwire"].
Do you have any idea how to go about this?
Answer: The issue is because of the : in the selector. You need to escape it using \\, like this:

$('[xlink\\:href="#_SAPGUI-icons_0_s_wfwire"]').addClass('foo');
.foo { color: red; }

#_SAPGUI-icons_000

#_SAPGUI-icons_0_s_wfwire

#_SAPGUI-icons_111


Formula for difference in order statistics

Question: Is there a specific formula one can use to compute the differences in order statistics, say $x_i - x_{i-1}$ when the underlying distribution of $x$ is standard normal?
Also what is the asymptotic value of this difference?
Comment: You can calculate the difference by subtracting one from the other, as in your formula, without regard for the underlying distribution.  Order statistics are a feature of the sample, not the distribution.  I am not sure what you are really asking...
Comment: Are you perhaps inquiring about finding the distributions of successive differences of order statistics from a Normal sample?
Answer: Let $W_{i,j:n} = X_{j:n}-X_{i:n},\; 1\leq i<j\leq n$ be the difference between the $i$th and $j$th order statistics (aka the spacings). The pdf of $W_{i,j:n}$ is then given by:
$$
f_{W_{i,j:n}}(w) = \frac{n!}{(i-1)!(j-i-1)!(n-j)!}\times \int_{-\infty}^{\infty}\left\{F(x_{i})\right\}^{i-1}\left\{F(x_{i} + w) - F(x_{i})\right\}^{j-i-1}\times \left\{1-F(x_{i}+w)\right\}^{n-j}f(x_{i})f(x_{i} + w)\;\mathrm{d}x_{i}, \quad 0<w<\infty
$$
This formula is given in $[1]$. As far as I know, there is no simple formula for the standard normal.
References
$[1]$ Arnold BC, Balakrishnan N, Nagaraja HN (2008): A First Course in Order Statistics. Siam, Philadelphia.
Comment: @Tool $F$ denots the cdf and $f$ the pdf, yes. Regarding the notation: I've copied the expression without change from the cited reference. I don't know why the authors chose this kind of notation, sorry.
Comment: Could you clarify whether $F$ and $f$ are the CDF and PDF of the underlying distribution of $x$ ? Also, is there a specific reason you labeled the integration variable $x_i$ with $i$ ?


Why is the projection map proper?

Question: It might be a silly question. I got stuck there. For the context, see S.K.Donaldson's Riemann Surfaces, chapter 4, section 4.2.3.
Suppose $P(z,w)=a_0(z)+a_1(z)w+\dotsb+a_n(z)w^n\in\mathbb C[z,w]$ is an irreducible polynomial where $n>0$ and $a_n(z)\neq0$ for some $z\in\mathbb C$. Consider the zero set $X$ of $P$, and the projection map $\pi\colon X\to\mathbb C,(z,w)\mapsto z$. Let $S$ be the set of singular points of $X$, i.e. where $P=\partial P/\partial z=\partial P/\partial w=0$, and $F$ be the roots of $a_n(z)$. By implicit function theorem, $X\setminus S$ is a Riemann surface. Furthermore, set $S^+=\pi^{-1}(\pi(S)\cup F)$, we have $\pi(S)\cup F$ is finite therefore $S^+$ is finite. Now let $E=\pi(S)\cup F\cup\{\infty\}$, we obtain the projection map $\pi\colon X\setminus S^+\to S^2\setminus E$. It's a holomorphic map between Riemann surfaces.
It claims that $\pi$ is also a proper holomorphic map. I cannot see any good reason for this. I call for some help on the reasoning.
Any idea? Thanks.
EDIT1: I think the following generalization should be true:

Suppose $X,Y$ are two connected Riemann surfaces, and $F\colon X\to Y$ is a nonconst holomorphic map. If $F$ is onto and there's an integer $N$ such that the preimage $F^{-1}(y)$ is finite and the cardinality $\#F^{-1}(y)\le N$ for all $y\in Y$, then $F$ is proper.

It's wrong, as Daniel Fischer said.
EDIT2: If $X,Y$ are locally compact Hausdorff spaces and $p\colon X\to Y$ is a proper continuous map. Given $y\in Y$, and an open set $V\supseteq p^{-1}(y)$, there's an open set $W$ containing $y$ such that $p^{-1}(W)\subseteq V$. It follows from the fact that $p$ is closed, thus $W=Y\setminus p(X\setminus V)$ is open, and if $p(x)\in W$, then $p(x)\not\in p(X\setminus V)$ therefore $x\in V$. I don't know whether it's true in other ways, say when $p$ is holomorphic and the cardinalities of fibers are bounded.
EDIT3:
The following should be true:

Suppose $X,Y$ are two connected Riemann surfaces, and $F\colon X\to Y$ is a nonconst holomorphic map. If $F$ is onto and there's an integer $N$ such that the preimage $F^{-1}(y)$ is finite and sum of multiplicities of $F^{-1}(y)$ is exactly $N$ for all $y\in Y$, then $F$ is proper.

Note that $F$ is locally $z\mapsto z^m$ for some $m$ with appropriate charts and coordinates. That's the local behavior of a nonconst holomorphic map.
If $K$ is compact in $Y$ and there's an open covering $\mathcal C$ of $F^{-1}(K)$, then we only need to find a finite refinement $\mathcal C'$ of $\mathcal C$ (i.e., for each $\mathcal O'\in\mathcal C'$, there's an $\mathcal O\in\mathcal C$ such that $\mathcal O\supseteq\mathcal O'$), which is also a covering of $F^{-1}(K)$.
For each $y\in K$, let $F^{-1}(y)=\{x_1,\dotsc,x_n\}$ where $n\le N$. We choose a small neighborhood $V_y$ of $y$ and disjoint neighborhoods $W_1,\dotsc,W_n$ for $x_1,\dotsc,x_n$ such that $W_k$ is contained in some open set in $\mathcal C$, $F(W_k)=V_y$ and in local coordinates, $F$ acts as $z\mapsto z^{m_k}$. Moreover, for each $y'\in V_y\setminus\{y\}$, $\#(F^{-1}(y')\cap W_k)=m_k$. (We can choose them step by step. First, choose disjoint local charts and coordinates around $x_1,\dotsc,x_n$ and $y$ such that the map $F$ restricted to each local chart around $x_k$ is just $z\mapsto z^{m_k}$. WLOG, local charts are discs in the very local coordinates. Take the smallest radius $r$ of the images of discs, and let $V_y$ be the disc of radius $r$ centered at $y$, and the choice of $W_1,\dotsc,W_n$ is obvious). By assumption, $m_1+\dotsb+m_n=N$.
We claim that $F^{-1}(V_y)=\bigcup_{k=1}^n W_k$. It's a trick of counting. Note that
$$\#F^{-1}(y')\ge\#\left(\bigcup_{k=1}^n(F^{-1}(y')\cap W_k)\right)=\sum_{k=1}^n\#(F^{-1}(y')\cap W_k)\ge m_1+\dotsb+m_n=N$$
But by assumption, the sum of multiplicities should be $N$, therefore $F^{-1}(y')=\bigcup_{k=1}^n(F^{-1}(y')\cap W_k)$.
Now $\bigcup_{y\in K}V_y\supseteq K$ and we can choose a finite covering, then the $W_k$'s for different $y$'s in the finite covering should be a finite refinement of $\mathcal C$. Q.E.D.
Answer: Without looking at the structure of $X$, we can argue elementarily by noting that the roots of a polynomial $p(z) = c_n z^n + \dotsc + c_1 z + c_0$ with $c_n\neq 0$ all lie in the closed disk $\{ z : \lvert z\rvert \leqslant R\}$, where
$$R = \max \left\{ 1, \lvert c_n\rvert^{-1}\sum_{k=0}^{n-1}\lvert c_k\rvert \right\}.$$
For, if $\lvert z\rvert > R$, then
$$\lvert p(z)\rvert \geqslant \lvert c_n\rvert \left(\lvert z\rvert^n - \lvert c_n\rvert^{-1}\sum_{k=0}^{n-1}\lvert c_k\rvert\,\lvert z\rvert^k\right) > \lvert c_n\rvert \lvert z\rvert^{n-1}\left(\lvert z\rvert - \lvert c_n\rvert^{-1}\sum_{k=0}^{n-1} \lvert c_k\rvert\right) > 0.$$
Let $\tilde{\pi} \colon \mathbb{C}^2 \to\mathbb{C}$ be the projection to the first component, so $\pi$ is the restriction of $\tilde{\pi}$ to $X$.
If $K \subset \widehat{\mathbb{C}}\setminus E$ is compact, then $\pi^{-1}(K) = X \cap \tilde{\pi}^{-1}(K)$ is closed, since $X$ and $\tilde{\pi}^{-1}(K)$ are closed. Since $a_n(z) \neq 0$ on $K$, the continuous function
$$R(z) = \max \left\{ 1, \lvert a_n(z)\rvert^{-1}\sum_{k=0}^{n-1} \lvert a_k(z)\rvert\right\}$$ is bounded on $K$, and hence $X \cap \tilde{\pi}^{-1}(K)$ is bounded, thus $\pi^{-1}(K)$ is compact.

Alternatively, we can look at the geometry of $X$ to gain perhaps a little more insight:
Let $K \subset \widehat{\mathbb{C}}\setminus E$ be compact, and $L = \pi^{-1}(K)$. Since we're dealing with metrisable spaces, compactness coincides with sequential compactness. We show that $L$ is sequentially compact. So let $\bigl((z_k,w_k)\bigr)_{k\in\mathbb{N}}$ be a sequence in $L$. Since $K$ is compact, we can without loss of generality assume that $z_k \to z^\ast \in K$.
The hand-waved argument showing the reason that $\pi$ is proper goes:
$\pi$ is basically an $n$-sheeted (possibly branched) covering, so at least one sheet above a small neighbourhood of $z^\ast$ must contain infinitely many $(z_k,w_k)$, and thus we can extract a subsequence $\bigl((z_{k_m},w_{k_m})\bigr)_{m\in\mathbb{N}}$ in a single sheet, and that means that the $(z_{k_m},w_{k_m})$ converge to the point $(z^\ast,w^\ast)$ above $z^\ast$ in that sheet.
We must get rid of the hand-waving now:
If $P(z^\ast,\cdot)$ has only simple zeros, $\pi$ is unbranched above an open neighbourhood $U$ of $z^\ast$, and we have $n$ holomorphic functions $\varphi_j \colon U \to \mathbb{C}$ with disjoint ranges such that for every $z\in U$ we have
$$P(z,w) = 0 \iff \bigl(\exists j\in \{1,\dotsc,n\}\bigr)\bigl( w = \varphi_j(z)\bigr).$$
Namely, let $\zeta_1,\dotsc,\zeta_n$ be the $n$ distinct zeros of $P(z^\ast,\cdot)$. Pick a $\delta > 0$ such that $\lvert \zeta_j - \zeta_k\rvert > 2\delta$ for all $j \neq k$, and let
$$\varepsilon_j = \inf \left\{\lvert P(z^\ast, w)\rvert : \lvert w-\zeta_j\rvert = \delta\right\},$$
and $\varepsilon = \min \{ \varepsilon_1,\dotsc,\varepsilon_n\}$. Then $\varepsilon > 0$, and by continuity, there is an open neighbourhood $U$ of $z^\ast$ such that
$$\lvert P(z,w) - P(z^\ast,w)\rvert < \varepsilon$$
for $z\in U$ and $w \in \bigcup\limits_{j=1}^n \overline{B_\delta(\zeta_j)}$. By Rouché's theorem, $P(z,\cdot)$ has exactly one zero in $B_\delta(\zeta_j)$ for each $j$, and that zero is given by
$$\varphi_j(z) = \frac{1}{2\pi i} \int_{\lvert \zeta-\zeta_j\rvert = \delta} \zeta\cdot\frac{\frac{\partial P}{\partial w}(z,\zeta)}{P(z,\zeta)}\,d\zeta.$$
Since $z_k \to z^\ast$, by dropping some initial terms, we can assume that $z_k \in U$ for all $k$, and then we have $w_k = \varphi_{j_k}(z_k)$ for a uniquely determined $j_k \in \{1,\dotsc,n\}$. There must be at least one $j$ with $j = j_k$ for infinitely many $k$, and for such a subsequence we have $w_{k_m} = \varphi_j(z_{k_m}) \to \varphi_j(z^\ast) = \zeta_j$, and $(z^\ast,\zeta_j)\in L$.
If $P(z^\ast,\cdot)$ has zeros with multiplicity greater than $1$, the argument needs to be modified a little. Let the distinct zeros be $\zeta_1,\dotsc,\zeta_r$, with multiplicities $\mu_1,\dotsc,\mu_r$. With the same construction as above, for all small enough $\delta > 0$, we find an open neighbourhood $U(\delta)$ of $z^\ast$ such that $P(z,\cdot)$ has exactly $\mu_j$ zeros (counting multiplicity) in $B_\delta(\zeta_j)$, and hence no zeros outside $\bigcup\limits_{j=1}^r B_\delta(\zeta_j)$ (since $\sum\limits_{\rho=1}^r \mu_\rho = n$).
Thus we find a $j$ and a subsequence of $\bigl((z_k,w_k)\bigr)$ with $\lvert w_{k_m}-\zeta_j\rvert < \delta$ for all $m$, and repeating the argument for a sequence $\delta_\ell \downarrow 0$ shows that then $w_{k_m} \to \zeta_j$, so $(z_{k_m},w_{k_m}) \to (z^\ast,\zeta_j) \in L$.

It generalises to (non-constant) holomorphic maps between Riemann surfaces where all fibres have the same finite cardinality (counting multiplicities), with essentially the same argument. Since all fibres have the same cardinality, $f^{-1}(y)$ is contained in a small neighbourhood of $f^{-1}(x)$ when $y$ is close to $x$, and that ensures that every sequence $z_k$ with $f(z_k) \to x$ has one of the points in $f^{-1}(x)$ as an accumulation point.
If the fibres don't all have the same cardinality, the map need not be proper: consider the map $f\colon z \mapsto z^3$ from the upper half-plane to $\mathbb{C}\setminus\{0\}$, where for example $f^{-1}(\overline{B_{1/2}(1)})$ is not compact.

With regard to the third edit, the statement is correct, as mentioned above. Concerning your proof, it is not necessary to demand $F(W_k) = V_y$ for all, $k$, it suffices to have $V_y \subset F(W_k)$, that simplifies it a little, I think.
Comment: The proof seems quite involved. I got a plausible generalization and I hope you can help me to check it, and if fortunate, it could be used to simplify the proof and clarify the logic.
Comment: We can also argue in a more elementary way. I thought it would be nice to show a bit of the structure of $X\setminus S$. I'll add the low-tech proof.
Comment: You need that all fibres have the same cardinality counting multiplicities. Without that, $f$ need not be proper.
Comment: Thanks. When the degrees (the sum of multiplicities for each point) are the same, we can choose a neighborhood $W$ of $y_0$ such that the cardinality of $f^{-1}(y)$ is just the degree of $y_0$ for $y\in W\setminus\{y_0\}$, then my **EDIT1** should work since the local behavior of $f$ is just $z\mapsto z^n$, right? At a glance, I think you're using Rouché theorem just to show the very fact of the local behavior. I don't like go into sequential compactness even for metric spaces.
Comment: Yes, I use Rouché's theorem to have the conclusion that fibres above close points are close to each other, which is equivalent to $f$ being a closed map. If you have a closed holomorphic map with finite fibres, that is proper. But, as the example shows, not all holomorphic maps with finite fibres are closed. If $X$ is a compact (connected) Riemann surface, $f$ is closed (and all fibres have the same cardinality, counting multiplicity, but you can get that as a conclusion and don't need to assume it then). Here, I find sequential compactness more convenient, although using nets or filters ...
Comment: ... to prove the compactness via the characterisation that a space is quasicompact if and only if every filter/net has an accumulation point doesn't change much. If you feel comfortable with nets or filters, it is a trivial rewrite of the argument.
Comment: Okay, edited. I hope you can check it.

Why is the projection map proper?


Pre-Data processing categorical variables in decision tree in R (rpart)

Question: I am new to decision trees, there are several things confused me a lot.

The first thing is that should we convert all categorical variables (Such as: gender, department, number of years) to a numeric variables using unclass method?

At the first time, I run the decision tree model simple using rpart(Y~.) based on the raw data which contains lots of ord. Factors, Factors,int. I took a look at the cptable for this model.

After I convert all factor variables into numeric using unclass, and build a new model based on the dataframe. I don't know why it can produce a totally different cptable. What I have done is just convert all factors to numeric, that is. Will it influence the model result? Why ?

The last question is that if I am making a predictive model using regression trees, should I scale the data?
Answer:
You should convert any variables that should be numeric to numeric, e.g., number of years. It does not make sense to convert department to numeric. Any category that contains only two values (possibly gender, depending whether you work with two or more genders) can be left as is or changed to numeric, it does not make a difference to the tree, although it will be easier to interpret as categoric.
Of course changing variables between categoric and numeric will change everything. If you leave number of years as categoric, then a tree will split it by assigning some numbers to the left child node and some to the right one - and probably using a wild mixture of assignments (0, 1, 2 to the left, 3 to the right, 4 and 5 to the left, 6 to the right...). If this variable is numeric, the tree will choose a threshold and assign every value below that threshold to the left and every number above the threshold to the right child.
Scaling is possible, but not necessary. It will just change the threshold used in splitting. (If you have very large or small numbers, you may have numerical issues, but that is rare.)
Comment: And an overall note: the sample size required for this whole process to work is perhaps $n=100,000$.  I mean 'work' in the sense of the patterns found by recursive partitioning and the accuracy of predictions being good in a new dataset.
Comment: Thank you so much. It solved all my concerns, and may I ask are there any way to select the top split? From my perspective, it is impossible since the `rpart` will automatically arrange the splits from the top to the bottom.
Comment: Most tree fitting algorithms will indeed do this automatically in order to optimize the fit, and you can't intervene. For the *top* split, this is however easily done: simply split your data into two however you want, and grow a separate tree for each subset. (I don't quite know why you would want to do this.)
Comment: @StephanKolassa I tried to look into the `tree_model$variable.important` and found that `variable1` and `variable2` were the two most important variables since these two had the highest  value in `variable.important` output. So my next step is try to build a new tree model with `var1` and `var2`.


How to allow connection from specific AWS EKS pods to AWS RDS?

Question: Let's say I have an EKS cluster with multiple pods hosting different applications. I want to allow connections from a specific application to an RDS instance without allowing all the pods in the EKS cluster to connect to the RDS.
After some research, I found out that there's a networking approach to solve the issue, by creating security groups for pods. But I am trying to look for another approach.
I was expecting to have a simple setup where I can:

create IAM policy with read/write permissions to the DB
create an IAM role and attach that policy
create a service account (IAM and k8s service accounts) with that role
assign the service account to the pods I want to grant RDS access.

But it seems like the only way to have IAM authentication from pods to RDS, is by continuously generating a token each 15m. Is this the only way?
Answer: I would recommend this task to be divided into following parts:

making sure the security concept is sound
allowing network traffic from EC2 worker nodes to RDS
creating Egress network policy for the cluster to only allow RDS traffic for specific pods

making sure the security concept is sound
The question here is why would you want to select only specific pods to access RDS database? Is there a trust issue with parties deploying pods to the cluster or is it a matter of compliance (some departments can't access other department resources)? If it's trust, maybe the separation here is not enough, maybe you should not allow untrusted pods on your cluster (vulnerabilities with root gaining via docker)?
allowing network traffic from EC2 worker nodes to RDS
For this, the Security Group of worker EC2 nodes must be allowed on RDS side (Inbound rules), and just to be sure, SG of EKS cluster nodes should also allow connections to RDS. Without these generic rules, the traffic can't flow. You could be specific here - for example allow access on only specific RDS instances, not all. You can have more than one node group for your EKS cluster also (and run pods that require RDS access only on those nodes, with labels).
creating Egress network policy for the cluster
If you create a default deny-all Egress policy (which is highly recommended), than no pods can access RDS by default. You can then apply more granular Egress policies to access RDS database by namespace, label, pod name. More here:
https://www.cncf.io/blog/2020/02/10/guide-to-kubernetes-egress-network-policies/
Clarification: in this scenario you store secrets to access database in kubernetes secrets, mount them into pod and login normally. If you want to just get connection without auth, my answer won't help you.
Comment: Thank you for you thorough answer!
I think I got a bit confused between how to manage the network traffic between the 2 services (EKS and RDS) and between the log in mechanism.
As you have mentioned, it is required to add the SG of the EKS cluster to the inbound rules of the RDS in order to allow traffic from all the EKS pods.
So far, the only way I authenticate to the RDS from a pod, is using the master username and password, which is obviously a security issue.
I would like to know what other approaches are available. IAM authentication using tokens is one way, right?
Comment: If I want to use IAM authentication from the pods to RDS, how would that work?
- Create an IAM role with permissions to access the database.
- Create an IAM user and assign him the role
- Create a database user with the same name as the IAM user and grant role.
- Create a k8s service account with that role attached and assign the service account to the pods.
- Then on the pod I use that username and a generated token to log in?


Is sampling from data, getting a statistic and repeating this process to get a mean of the statistic a "Monte Carlo" method?

Question: Suppose we have some data (say around 10,000 cases) that sample a variable of interest; e.g., the concentration of metal in soil.  By generating a random series of indices we choose some of those samples and then compute some statistics, for instance the mean. We do this many times and finally get the mean of mean values.

Is this the Monte Carlo method?
If yes, how? If not, why not? What is needed to be a MC calculation?
Comment: The question is a little puzzling because this specific example is just a computationally inefficient way to get a familiar result: the mean of the means necessarily equals the mean of the original dataset.
Comment: @whuber: My hope is that the "mean of means" example is simply to hide the actual computation being done. On the other hand, perhaps being able to legitimately use a "Monte Carlo Method" -- "as confirmed by statisticians on stackexchange" -- will allow someone to fulfill a contract clause or something. Or perhaps it's the other way around: someone sold them a program based on "sophisticated Monte Carlo techniques" that simply calculates a mean inefficiently. What delicious mystery!
Comment: @wayne,@whuber - Mean in the question is just for example and to simplify the question. By the way how amazing guesses!
Answer: What you describe is "a" Monte Carlo method (but there is not just one MC method so it is not "the" MC method).
Monte Carlo methods refer to a large group of methods that involve repeted random sampling.  Exactly what you are doing depends on the sizes of your resamples and whether you are sampling with replacement or not.  If your resamples are the same size as the original sample and you sample with replacement then this is called "bootstrapping".  If your resamples are without replacement and smaller than the original sample then it is a variation on the "jacknife".  There are many other methods that qualify as Monte Carlo methods as well.
Comment: I replaced "the" with "a" in the question. Actually what you said is what I expected to hear. I mean I'm happy that my understanding was not wrong. To develop my question I would like to ask if the number of trials was only two then regardless the confidence of the overall result, is the method still a Monte Carlo method?
Answer: I'd say calling this a Monte Carlo method is a bit misleading.
I think that what you do is usually called Simple Random Sampling, see here:
http://en.wikipedia.org/wiki/Simple_random_sample
and is particularly used in survey analysis, polls, etc.
Monte Carlo methods usually refer to sampling methods used in integral approximations, where you choose the number N of draws, and the larger N, the more precise your results are. They are usually only justified asymptotically, when N goes to infinity (in which case they are expected to give the "right solution", usually to compute an integral of interest). In this respect your method seems different from classical MC methods, as introduced e.g. here:
http://books.google.com/books/about/Monte_Carlo_statistical_methods.html?id=HfhGAxn5GugC
Comment: Isn't Monte Carlo a random sampling method? Or isn't there relationship between them. I will check your link.
Answer: This sounds like a bootstrap or at least a variation on the bootstrap. If you are resampling from the full dataset you have access to, and importantly the resample size has the same n as the original, this would be a bootstrap. I would not label this a monte carlo. I think of monte carlo as when you are actually running simulations on fake data, often to test a particular method, to see if you get the answer you should expect given the parameters you specified in the fake data setup.


set theory proof of $A\cap B = A \setminus(A\setminus B)$

Question: Please proof that $A\cap B=A\setminus(A\setminus B)$ this really gave me sleepless night. I tried using the set intersection properties but I still got confused.
Answer: To show $A\cap B = A -(A-B)$, you show two subsets relations
$A\cap B \supseteq A -(A-B)$ and $A\cap B \subseteq A -(A-B)$.
To show $A\cap B \supseteq A -(A-B)$, let $x \in A-(A-B)$, then $x\in A$ and $x\notin A-B$. Here if $x\notin B$, then $x\in A-B$ and contradiction arises, so $x\in B$. so $x\in A$ and $x\in B$, i.e. $x\in A\cap B$. So we show $A\cap B \supseteq A -(A-B)$.
To show $A\cap B \subseteq A -(A-B)$, let $x\in A\cap B$, then $x\in A$. Here if $x\in A-B$, then $x\notin B$ and contradiction arises, so $x\notin A-B$. Together we have $x\in A$ and $x\notin A-B$, i.e. $x\in A-(A-B)$. So $A\cap B \subseteq A -(A-B)$. Hence this completes the proof.
Answer: Notice that
$$\begin{align}A \setminus (A \setminus B) & = A \cap (A \cap B^c)^c = A \cap (A^c \cup B) \\ & = (A \cap A^c) \cup (A \cap B) = \varnothing \cup (A \cap B) = A \cap B.\end{align}$$
I have used two properties here - the de Morgan's laws for sets and the distributivity of $\cup$ and $\cap$.
Answer: Any element of $A$ is either also an element of $B$, or it is not.
so, $A\cap B$ means $x$ is an element of BOTH $A$ and $B$.
$A\setminus B$ means that $x$ is an element of $A$ BUT NOT $B$
$A\setminus(A\setminus B)$ means that $x$ is an element of $A$ BUT NOT $A\setminus B$, and so  $x$ is an element of $A$ BUT NOT an element of $A$ BUT NOT $B$.
And the clever bit is that 'BUT NOT an element of $A$ BUT NOT $B$' means 'BOTH $A$ and $B$', which is $A\cap B$.
Answer: $$A, B \subseteq E$$
$$\begin{align} A \setminus (A \setminus B) = \{o\in E  \;|\; (o \in A)\;\land\;(o \in (A \setminus B)^c) \} = \{o\in E  \;|\; (o \in A)\;\land\;(\neg (o \in A \;\land\;o \in B^c )) \} =  \{o\in E  \;|\; (o \in A)\;\land\;(o \in A^c \;\lor\;o \in B ) \} = \{o\in E  \;|\; (o \in A \;\land\; o \in A^c )\lor(o \in A\;\land\;o \in B ) \} = \{o\in E  \;|\; \text{⊥ (false)}\lor(o \in A\;\land\;o \in B ) \} = \{o\in E  \;|\;(o \in A\;\land\;o \in B ) \} = A \cap B \end{align} $$


sklearn KernelDensity score_samples giving values greater than 0

Question: I am using sklearn KernelDensity function to estimate density and then evaluate pdf at some points using score_samples function but the values returned by the score_samples function are much greater than 0 which shouldn't be the case because as per documentation it returns log(density) [Documentation: The array of log(density) evaluations. These are normalized to be probability densities, so values will be low for high-dimensional data.]
from sklearn.neighbors.kde import KernelDensity
import numpy as np

data = np.random.normal(0, 1, [50, 10]) #50 data points, dimension=10
data_kde = KernelDensity(kernel="gaussian", bandwidth=0.2).fit(data)
output = data_kde.score_samples(data)

#print(output)
output = array([19.94484645, 19.94484645, 19.94484645, 19.94484645, 19.94484645,
       19.94484645, 19.94484645, 19.94484645, 19.94484645, 19.94484645,
       19.94484645, 19.94484645, 19.94484645, 19.94484645, 19.94484645,
       19.94484645, 19.94484645, 19.94484645, 19.94484645, 19.94484645,
       19.94484645, 19.94484645, 19.94484645, 19.94484645, 19.94484645,
       19.94484645, 19.94484645, 19.94484645, 19.94484645, 19.94484645,
       19.94484645, 19.94484645, 19.94484645, 19.94484645, 19.94484645,
       19.94484645, 19.94484645, 19.94484645, 19.94484645, 19.94484645,
       19.94484645, 19.94484645, 19.94484645, 19.94484645, 19.94484645,
       19.94484645, 19.94484645, 19.94484645, 19.94484645, 19.94484645])

Since density lies in [0, 1], log(density) should be between (-Inf, 0] unlike 19.9448 shown above.
Answer: probability densities don't have to be between [0,1]. They are densities and not an exact probability. The Wikipedia page gives a good overview of pdfs.

https://en.wikipedia.org/wiki/Probability_density_function


Statistical properties of parameters estimated by method of Lagrange multipliers in R

Question: I have time series data that can be fitted by a constrained non-linear function (non-linear in the parameters to be estimated).  I'd like to use the method of Lagrange Multipliers (link), specifically R's Rsolnp package (link), because the Lagrange Multiplier itself has economic meaning.  I would like the statistical properties (p values or confidence intervals) of the parameters estimated by solnp in Rsolnp.
If my problem didn't involve constraints, I could use R's nls class (link) and the summary.nls method (link) to retrieve the statistical properties of the fitted parameters.
Questions:

Is there an equivalent to summary.nls for solnp?
If not, how can I obtain the statistical properties of the parameters estimated by the method of Lagrange Multipliers? A reference to a paper or textbook here will be sufficient.

Here are some details of my function (a CES production function from economics) and constraints:
Function:
iGDP ~ ((1-zeta) * (exp(lambda_L*iYear) * iCapStk^(alpha) * iLabor^beta)^phi + zeta*(exp(lambda_E*iYear) * iQ)^phi)^(1/phi)

Constraints:
alpha + beta = 1

(Note that I don't want to substitute 1-beta for alpha, because the numerical value of the Lagrange Multiplier has a valuable economic interpretation. I want to use the both the constraint equation and the method of Lagrange Multipliers.)
Known data (on an annual basis):
iGDP, iYear, iLabor, iCapStk, iQ

Parameters to be estimated (these are the parameters for which I would like statistical properties: p values, confidence intervals, etc.):
zeta, lambda_E, lambda_L, alpha, beta, phi

Answer: I don't think there's much you can do with statistical interpretation of Lagrange multipliers with inequality constraints. Most of non-linear statistical inference (as you may have seen in Ron Gallant's book or Newy and McFadden's Handbook of Econometrics chapter), is mostly asymptotic. However, for large samples, you will have weird distributions of your Lagrange multipliers if their constraints are active in population (see Andrews' papers on estimation on the boundary of the parameter space).
With equality constraints, inference for Lagrange multipliers is doable. At least, I have seen this done for empirical likelihood (see e.g. Theorem 15.2.1 in Bruce Hansen's Econometrics Notes).


setting a value using ISNULL?

Question: I know this is simple but I really need to make sure what I understood is indeed correct.
Is the below code setting the value of A.FUTUREUSE09 to 'not available' if DS.[FUTUREUSE09] IS NULL?
UPDATE A
   SET
       A.[FUTUREUSE09] = ISNULL(DS.[FUTUREUSE09] , 'not available')
       ----------
       -----------
       -----------
       -----------
FROM PRODUCT A JOIN DS_PRODUCTS DS
ON A.ID = DS.ID
JOIN HIERARCHY H ON
                            CASE
                             WHEN DS.CODE = 'not available' THEN 'NA_PL3'
                             ELSE DS.CODE
                            END = H.CODE;

Answer: Yes. It will. ISNULL takes 2 parameters: First is a check_expression and second is replacement_value. It returns the first check_expression if it is not null else it returns replacement_value, in your case not available
Comment: okay,,, so if DS.[FUTUREUSE09] is not null then A.[FUTUREUSE09] will be set to DS.[FUTUREUSE09] ??
Comment: Cool. If this solved your issue, please accept the answers to avoid duplicate questions being asked by others later

setting a value using ISNULL?