Como desbloquear a porta 80 do Firewall do Windows 8?

Question: Estou usando WAMP para rodar um servidor local e as vezes quero mostrar os meus projetos para uns amigos, eu já configurei a porta 80 no roteador com o meu IPV4 e tudo mais. Quando faço o testes de porta em algum site diz que a porta tá aberta mas com bloqueio, e quando desativo o Firewall funciona normal, mas não vou deixar o Firewall desativado.
Uso Windows 8
Comment: Painel de Controle -> Ferramentas administrativas -> Firewall; Crie regras de entrada pra porta 80.
Answer: Abrir uma porta no Firewall do Windows
Nesse caso seria necessário abrir uma porta no firewall do windows:

Passe o dedo desde a borda direita da tela, toque em Pesquisar (ou,
se estiver usando um mouse, aponte para o canto superior direito da
tela, mova o ponteiro do mouse para baixo e clique em Pesquisar),
digite firewall na caixa de pesquisa e toque ou clique em Firewall
do Windows.
Toque ou clique em Configurações avançadas. É possível que você receba uma solicitação
para fornecer uma senha de administrador ou para confirmar sua
escolha.
Na caixa de diálogo Firewall do Windows com Segurança Avançada , no
painel esquerdo, toque ou clique em Regras de Entrada e, no painel
direito, toque ou clique em Nova Regra.
Siga as instruções na tela.

A regra nesse caso seria a liberação da porta 80, caso você tenha mantido o padrão do apache.
Fonte: http://windows.microsoft.com/pt-BR/windows-8/Windows-Firewall-from-start-to-finish
Comment: Valeu. Eu tava tentando em *Regras de Saída*.


Random numbers and percentages in Java

Question: I have some Java code. In my code, I have a collection of users. Each user has a percentage chance of "winning" the collection, as that the sum of the chance of each user in the collection is 100. To choose a winner, I sort the collection (which is an array) in ascending order. My problem is choosing the winner based off of that sorted array. This is what I have tried:
public Bet getWinner() {
    double random = Math.random() * 100;

    Bet[] copy = Arrays.copyOf(getBets(), bets.size());
    Arrays.sort(copy);

    for (Bet bet : copy) {
        if (random < getChance(bet)) {
            return bet;
        }
    }
    return null;
}

public float getChance(Bet bet) {
    return (bet.getAmount() / getJackpotTotal()) * 100;
}

public float getJackpotTotal() {
    float total = 0;

    for (Bet bet : getBets()) {
        total += bet.getAmount();
    }
    return total;
}

But is there are two users in the collection, one with 10% chance of winning and the other with 90%, if random is > 90, getWinner returns null. How else can I do this? Is there a way to create a random distribution based off of a percentage, or is there something simpler or different?
Thanks for your help.
EDIT
This is not a duplicate because it is not asking specifically about weighted random numbers. It is asking about choosing something (not a random number) from a random number.
Comment: For the `n`-th user, sum up all probabilities from user `0` to `n` (this is guaranteed to be between `0` and `1` by definition). If this sum is `<` or `<=` (your decision) than `random`, you have found your winner.
Comment: Possible duplicate of [Weighted randomness in Java](http://stackoverflow.com/questions/6737283/weighted-randomness-in-java)
Comment: @pjs: Not a duplicate because it's not asking specifically about weighted randomness, but choosing something based from a percentage
Comment: Perhaps you like this one better: http://stackoverflow.com/questions/14915899/pick-random-element-from-set-with-non-uniform-distribution  This is definitely a question that has been answered before.
Comment: Unlike that question, this is asking using a uniform distribution @pjs
Comment: @LAB No, 90%/10% is not a uniform distribution.  [The *definition* of a uniform distribution is that all outcomes are equally likely](https://en.wikipedia.org/wiki/Uniform_distribution_%28discrete%29).
Answer: You need to consider the summed up chances. If one player has chance 90 and one 10, then you first compare < 90 and then < 90 + 10.
Comment: Well, after realizing that was all I had to do, excuse me a moment, I'm dropping out of math. But thanks for your help.
Comment: You are welcome. Now that I am in industry, I do not have too much opportunity to show off with my PhD in maths ;-)
Answer: Add a variable that keeps a total of the odds you've gone through so far:
int total = 0;
for (Bet bet : copy) {

    if (random < total + getChance(bet)) {
        return bet;
    }
    total += getChance(bet);
}

Your naming conventions are a little ambiguous, so I hope you get the idea even if I may be a bit inaccurate with the proper names.
Comment: Yeah, I could definitely work on names. But your code makes enough sense, thanks for your answer!

Random numbers and percentages in Java


CSS not working in IE8

Question: I am writing signature on a canvas. (Flash canvas) - Using jquery jsSignature plugin.
http://willowsystems.github.io/jSignature/#/about/
Signature color is black. But the signature is not visible. Actually it is writing to canvas. Canvas background is red.
If I close the browser and reopen the closed browser it is showing the signature. But again if I refresh or go to next page and coming back, again signature does not appear on canvas.
I know question is not reasonable and more down-votes can appear, still I am looking for some suggestions.
It is working on IE6 and IE9.
Not understanding whether it is CSS issue or JavaScript issue. Please help.
I can only give below information. I know this is not enough. I am unable to reproduce this in jsfiddle. Because lack of time.
CSS
    #signatureparentAppSig {
        background-color: #red;
        color: black;
        padding : 0px;
    }

Javascript:-
$appSig.jSignature({'UndoButton':true, 'extraActionClass' : 'appSigActions', 'strokeManagingFieldId' : 'app_num_strok', 'background-color':'white', 'sizeRatio' : '4', 'lineWidth' : '2', 'width' : '550', 'height' : '157'})

Comment: You missed a minor detail, Include the relevant code so we can actually help you. And no don't link to your site, if you don't take the time to ask a decent question why should we bother to answer ?
Comment: con you replicate the issue on jsfiddle ?
Comment: I have added the codes. I can not add everything here. Because it is very huge coding.
Comment: Not understanding how it works when I close the tab and reopen again. But second refresh it will not work.
Answer: You can use modernizr and/or normalize to make it display properly (like a block) so it will fit in your design. However, the functionality of the canvas is not usable in a browser that doesnt support it.

CSS not working in IE8


How does the power of discrete-time maps propagate compared to the continuous-time system?

Question: In continuous-time differential equations, if I have:
$\quad \frac{d}{dt}x_1(t) = A_1\cdot x_1(t) + B_1$
$\quad \frac{d}{dt}x_2(t) = A_2\cdot x_2(t) + B_2$.
the square of $x_1(t)$ and $x_2(t)$ can propagate as:
$\quad \frac{d}{dt}\{x_1^2(t)\} = 2 x_1(t) \cdot \frac{d}{dt}{x}_1(t) = 2x_1(t) \cdot\{A_1\cdot x_1(t) + B_1\} = 2A_1 \cdot x_1^2(t) + 2B_1 \cdot x_1(t)$
$\quad \frac{d}{dt}\{x_2^2(t)\} = 2 x_2(t) \cdot \frac{d}{dt}{x}_2(t) = 2x_2(t) \cdot\{A_2\cdot x_2(t) + B_2\} = 2A_2 \cdot x_2^2(t) + 2B_2 \cdot x_2(t)$,
the squares of $x_1(t)$ and $x_2(t)$ are of squares and the original $x_1(t)$ and $x_2(t)$.
I am curious about the propagation of powers of discrete-time maps:
$\quad x_1(k+1) = a_1\cdot x_1(k) + b_1$
$\quad x_2(k+1) = a_2\cdot x_2(k) + b_2$,
where $k = 1, 2, 3, \dots \in \mathbb{N}$.
For example, I am interested in the trajectories of $x_{1}^2(k)$ and $x_{2}^2(k)$.
My guess would be to do the following:
$\quad x_{1}^2(k+1) = (x_1(k+1))^2 = (a_1\cdot x_1(k) + b_1)^2 = a_1^2 \cdot x_1^2(k) + 2a_1\cdot x_1(k)\cdot b_1 + b_1^2$
$\quad x_{2}^2(k+1) = (x_2(k+1))^2 = (a_2\cdot x_2(k) + b_2)^2 = a_2^2 \cdot x_2^2(k) + 2a_2\cdot x_2(k)\cdot b_2 + b_2^2$.
Is this correct?
Answer: That is correct. This solid green curve in this image shows $x_1x_2$ for a two-dimensional system calculated as the product of the two solutions. Directly below the solid curve is another curve that gives the simulated trajectory of $x_1x_2$. This is no proof, but rather empirical evidence that what you think is correct is what is seen in practice.


Where is my AJAX call going?

Question: I'm very new to Drupal so I hope you'll forgive the silly question: where is the server-side code for my AJAX call?
I've read the documentation on the Ajax Framework, but I can't find any instances of #ajax or callback in my code.
Capturing the /system/ajax request yields some interesting form variables:

form_build_id: form-cBW24WCJRFxgW5TMHSa-9hQ_tVenToYkx2ObzTgnQKM
form_id: commerce_checkout_form_ip_info
_triggering_element_name: ief-36484c27df589bd88b009b3e91d079f24f9559cc-add
_triggering_element_value: %2B+ADD+MEMBER

(There are lots of others, but those seem like the relevant ones.)  I gather that this is a form using the Commerce module, but that doesn't help me much.
Finally, here's the line of code setting up the value of the button that triggers the AJAX call:
$form['customer_profile_ip_info']['field_company_ip_customer_info']['und']['actions']['ief_add']['#value'] = "+ ADD MEMBER";

Hopefully this is enough information to determine what's happening here.
Answer: IEF = Inline Entity Form; you should find what you're looking for in that module. If you're new to Drupal the layers of abstraction might make it difficult to understand what's going on though. If there's something in particular you're looking to find out how to alter or understand just update the question.
If you install the Devel module and add
dpm($form['customer_profile_ip_info']['field_company_ip_customer_info']['und']['actions']['ief_add']);

to your alter hook you should find the #ajax property.

Where is my AJAX call going?


tempusdominus 4 multiselect population

Question: I'm trying to get initialized my DateTimepicker with multiple Dates. I can initalized with a specific date but not with the multiple option.
var selectedDates = ["12/1/2019","11/1/2019"];
    $(function () {
                $('#holidayPicker').datetimepicker({
                    format: 'L',
                    allowMultidate: true,
                    multidateSeparator: ' ',
                    minDate: "<?php echo $startDate->format('Y-m-d');?>",
                    maxDate: "<?php echo $endDate->format('Y-m-d');?>",
                   //   setDate: [new Date(2019, 0, 4),new Date(2019, 0, 5)]
                    useCurrent: false,
                    //date: new Date(2019, 0, 4),
                    setDate: selectedDates,
                });
            });

What i have already tried:

with setDate an a array of Dates and Strings
with date and multiple Strings or multiple Dates as Strings
directly over the value attribut of the input field

Does someone has an idea?
Comment: I dont think its supported, ive created a feature request https://github.com/tempusdominus/bootstrap-4/issues/226 . I am currently looking into the source code to see if I can find some sort of a hack
Answer: I have managed to find a function in the source code that allows you to set the date directly. You have to access the datetimepicker object directly in order to use it.
Code snippet:
var $el = ('#your-element');
// Initialize datepicker.
$el.datetimepicker({
    inline: true,
    format: 'DD-MM-YYYY',
    allowMultidate: true,
    useCurrent: false // Prevents selection of current date
});

// Get the object directly from the data attribute.
// @see https://learn.jquery.com/jquery-ui/widget-factory/widget-method-invocation/
var prefill = ['01-15-2019', '01-16-2019'];
var plugin = $el.data('datetimepicker');
for(let i = 0; i < prefill.length; i++) {
    // Set the dates as active. You can optionally pass your own moment object as the first argument.
    plugin.date(prefill[i], i);
}

Comment: It throws a "TypeError: oldDate is undefined" error when the Clear button is clicked.
Comment: You'll have to debug that further yourself. Possibly it is missing some other setting.

tempusdominus 4 multiselect population


Showing Forum Topic Count 0 because, content access module conflict with Advanced Forum

Question: In my project I am working with advanced forum. for this I installed module as below.

advanced forum
ACL
content_access
chain_menu_access

The issue is after adding Forum Topic into forum, the count of topics display zero (0).
Help for resolve this issue.
Comment: Add a question to your post! Then, try to disable the content access modules in reverse order one by one and see at which point the count is correct. Voilà, you found the module which causes the trouble and you can then debug further.
Comment: The "bcoz" actually had me close to reporting this as spam, before I read the title more closely. Might wanna work on that.
Answer: Finally, I find solution for my issue and post it on issue list of Advanced Forum. Also patch is created, and pushed in to future development.


Drawing a random sample using a random number table

Question:
One hundred Random Digits
    00-04 05-09 10-14 15-19
===========================
00  54463 22662 65905 70639
01  15389 85205 18850 39226
02  85941 40756 82414 02015
03  61149 69440 11286 88218
04  05219 81619 10651 67079

I just started reading up on random number tables, but Im not really sure how to read the above table/interpret the data. How would I go about to draw a random sample of size $n =10$ without replacement from a numbered population of size $N=100$? And also a random sample of size $n=15$ without replacement from a numbered population of size $N=123$?
Comment: Is this a homework exercise or are you actually trying to generate random numbers in this way? If it is homework, please add the `homework` tag; if it's not homework my advice would be to put away the table and use a computer
Answer: A random number table is designed to create uniformly distributed values; this use is straightforward.  The somewhat tricky part to do correctly and efficiently is to sample without replacement. I will describe this because it is a useful algorithm for any statistician to know: random permutations are very important (for resampling and bootstrapping, for instance) and, because they may be generated a huge number of times, efficiently generating them can be essential.
Selecting elements of a population
Usually, one designates a starting entry in the table and a rule for selecting sequences of digits.  For instance, for sampling from $100$ objects, first number them from $0$ through $99$ in any order you like.  Without referring to the table, you might stipulate that you will start in row 3, column 1 and pick every other digit, grouping them in pairs. This determines the sequence
89, 10, 58, 44, ...

Via your numbering system you will interpret this sequence as elements of the population.
When $N$ is not a power of $10$ you can proceed in several ways. Perhaps the most efficient is to partition the random digits into longish groups, interpret them as values in the interval $[0,1)$ by placing an implicit decimal point in front of them, multiplying those by $N$, and rounding down.  For example, with $N=123$ items numbered from $0$ through $122$ and again starting in row 3 column 1, this time grouping the digits in sixes, you would produce
123 * .859414 = 105, 123 * .075682 = 9, 123 * .414020 = 50, 123 * .156114 = 19, ...

This can be performed in the field without any tools at all (apart from pencil and paper if you need those for the multiplications).
Sampling without replacement
The most straightforward way to accomplish this is simply to remove duplicates as they are encountered in the sequence of indexes generated above.  Two tricks are frequently employed when doing this manually (in the field) or by computer with very large populations.
The first one is that when sampling more than half the population, instead identify the elements that are not needed (without replacement), then just keep the rest for the sample.
There is an elegant algorithm to avoid searching for duplicates. It generates a random permutation (an ordered subset of the population of specified size); the ordering is useful in its own right.  You begin by writing the identifiers of the population in any sequence you like.  As an example, if we were to sample from a population of $N=10$ of individuals named {a,b,c,d,e,f,g,h,i,j}, we would begin with, say, this array preceded by a set of the elements put into the sample so far (none of them):
    {}, a b c d e f g h i j

Generate a sequence of random numbers as before. For this example let's use the previous sequence .859414, .075682, .414020, ... .  Because the array currently has $10$ elements in it, we use the first random number from the table to compute the random index 10 * 0.859414 = i.  Interpret this as an index*into the array, remembering the array indexes must start at $0$.  Swap the marked element of the array with the element at this index, keep the new element at the first index for your sample, and then drop the first element from the array altogether, leaving this:
    (i), b c d e f g h a j

Repeat, bearing in mind the array now has only $N-1$ = $9$ elements.  So we use the second random value from the table to compute 9 * 0.075682 = 0.  That happens to designate the first element of the remainder of the array, which is swapped with itself and also put into the growing sample:
    (i, b), c d e f g h a j

Another repetition produces the index 8 * .414020 = 3, identifying the value f in the array, which is swapped with the initial c:
    (i, b, f), d e c g h a j

You can see that the only actual changes made to the array are the swaps: the random permutation--here (i, b, f)--automatically appears in the first $k$ entries of the array after $k$ swaps are performed in this manner.  In this fashion you can generate a random $k$-permutation by means of just $k$ (uniformly distributed) random numbers and $k$ swaps: a highly efficient procedure.  Moreover, in cases where the sample size is not fixed in advance, this procedure can be iterated with the remaining non-sampled elements.
BTW, to prove that all permutations are equally likely to occur in this algorithm, note that all elements of the population have equal chances of being the first chosen. The proof is finished by induction (because this is a recursive algorithm).
Answer: Michael Chernick's method will be exact for $N=100$, but will have slight imbalances and unequal probabilities of selection for $N=123$ due to small discretization error.
For $N=100$, I would go with just two digits in the table, so my sample of size $n=10$ would be comprised of units 54, 46, 32, 26, 62, 65, 90, 57, 6 and 39 (the 00 combination maps to 100).
For $N=123$, you'd have to observe that $123\times8 = 984$, so it would be handy to use the triples of numbers $\mod 123$, and discard some $16/1000=1.6$% of the combinations. So the sample of size 10 would consist of units $ 544 (\mod 123) = 52$, $632 (\mod 123) = 17$, $266 (\mod 123) = 20$, etc. 000, 123, 246 combinations map to the unit numbered 123.
If you encounter duplicates, while you want to sample without replacement, you can either omit the duplicates, or shift by one digit, or omit the whole sample.
Random digit tables, as well as $t$-tables and $F$-tables in the back of your statistics textbooks, are basically the Ptolemaic system in statistics. Yes, they do work with some accuracy. But since their invent, things have changed computationally, and better accuracy methods are available these days.
Comment: @whuber, that's a philosophical debate, I guess. I am a believer in the right tool for the problem, and for most applications, I would see the PRNG to do appropriate job. The tables are only as accurate as the method that produced them. And you can produce computer-readable truly random numbers from random.org or special physical devices, although they won't be reproducible. And of course you can laminate your random number table and take it under water (although I sorta doubt people really do that, frankly; I'd be curious to see myself mistaken though :) ).
Comment: You're right, Stas.  But every few years I do find occasion to use a random number table (and each time I think it's the last time I will ever do so...).
Comment: Random number tables still have several advantages over pseudorandom number generators. One is that they provide the clearest possible documentation of how a random number sequence will be (or was) produced. Another is that they need no technology to use, which to some people in the field can be very useful (they still work when your batteries run out; they are lightweight; they can work in rain, snow, sand, and under water, etc.).  And they are *completely* accurate.  If anything, the onus is on the pseudo-RNGs to demonstrate their "accuracy."
Answer: In general you start with N objects out of which you want to choose k at random.  Select a uniform random number. Interpret a number U such as 54463 as 0.54463. Since you have index numbers 1, 2, 3,.., N to choose from pick index 1 0 < U <=1/N , 2 if 1/N < U <=2/N,..., N if (N-1)/N < U <=1.  Now after doing that you have N-1 index numbers left to pick k-1 out from.  Reorder the indices from 1 to N-1 and pick index 1 if 0 < U <= 1/(N-1), 2 if 1/(N-1) < U <=2/(N-1),..., N-1 if (N-2)/(N-1) < U <=1.  Continue in this way until all k indices have been selected.


Noob question about bayes rule denominator estimation

Question: A known problem of Bayes rule is the intractability of the estimation of $p(D)$ given a multiparametric problem, since $p(D)$ is found by marginalizing the joint probability $p(D, \theta_{1..n})$ over the whole n-dimensions $\theta$ space.
But I was wondering, since $p(D)$, in theory, does not depend on the actual parameterization of the model (otherwise it would be conditional on $\theta$ and not marginal), wouldn't be sufficient to estimate in a way that doesn't use $\theta$ at all?
I wouldn't know how to do it with no parameters at all, but the first thing that comes to my mind would be to use a simplified model with just one parameter to integrate over and then use the $p(D)$ estimated this way as a denominator of the joint density of the complex model.
What am I missing? If one can compute $p(D)$ analytically (or numerically but fast) from a simpler model, couldn't she plug it into a complex model to avoid using MCMC to estimate the normalized posterior?
Answer: There is more than one possible model for the joint distribution. Let's index two of them by $A$ and $B$:
\begin{equation}
p(D,\theta|A) \quad\text{versus} \quad p(D,\theta|B) .
\end{equation}
It follows that there are two different marginal likelihoods for the data, one for each model:
\begin{equation}
p(D|A) = \int p(D,\theta|A)\,d\theta
\quad\text{versus}\quad
p(D|B) = \int p(D,\theta|B)\,d\theta.
\end{equation}
Is one of the models correct? Which one is better?
To strip things down to the bare essentials, consider two models for $D$, neither of which has any parameters:
\begin{equation}
p(D|A) = \textsf{N}(D|0,1)
\quad\text{and}\quad
p(D|B) = \textsf{N}(D|3,1) .
\end{equation}
Now suppose $D =1$. Which model is more consistent with the observation $D$? I.e., which model has the greater marginal likelihood of the fixed data?
Comment: @Bakaburg I've added a bit more to my answer. See what you think.
Comment: Now I'm even more confused! What are A and B in this case? different parametrizations? why the different parametrization should influence $p(D)$ which is just a probabilistic statement of the observed data, not the parameters? To make a stupid example, let's imagine that we want to investigate the probability of raining $p(R)$ with two competitive models, using either low pressure $p(Lp|R)$ or low temperature alone $p(Lt|R)$. Even if the numerator of the two models change: $p(R|Lp) \times p(Lp)$ vs $p(R|Lt) \times p(Lt)$ the numerator stays p(R) which is just the frequency of rain isn't it?
Comment: That is, why $p(D|A)$ and $p(D|B)$ should not be the same? The base probability of rain doesn't change.
Comment: @Bakaburg I should have referred to the two distributions as models. I have modified my answer.
Comment: Thank you. these days I made some small experiments with R and of course it turned out that the marginal probabilities of data from two different models (i.e. different data/ parameters joint probabilities) are different. So that solves my question. The problem is that I don't get why. Why a statement about the data (which, by Bayesian theory, is fixed) should change based on parameters, since it's unconditional on them? writing it as $p(D|Model)$ doesn't change the problem since the model is defined by its parameterization, isn't it?
Comment: So if the probability of the data is conditional on the model, and the model is defined by the parametrization, -> the probability of the data depends on the parametrization, i.e. $p(D|\theta)$ that is is a conditional likelihood, not a marginal probability. I'm even more confused.
Comment: many thanks for your patience with me @mef! When you wrote "marginal likelihood" that triggered something in me (I never considered p(D) as a likelihood) and I found https://en.wikipedia.org/wiki/Marginal_likelihood on wikipedia. So you want to tell me that even if written $p(D)$ in reality it should be $p(D|M)$ where $M$ is the model functional form, not the parameters' value? That is, the "evidence" probability is conditional on the on how $D = f(\theta)$ is defined, but not on the $\theta$ value?


Extracting specific fields from mongodb

Question: I want to retrieve the the place names in my table places in the database placedb.
my data in the database is in the following format
<code> **{ "_id" : ObjectId("514c23udhgfhdfge"), "placeList" : "chennai,coimbatore,madurai........", "state" : "tamilnadu" }**
</code>
below is the code which i had tried but it does not shows any output and i have no idea what went wrong
<code>     MongoClient client = new MongoClient("localhost",27017); //with default server and port adress

     DB db = client.getDB("placedb");

     DBCollection areaColl=db.getCollection("places");

     DBCursor find=areaColl.find();

     String places = "";
     while(find.hasNext())
     {
         places=find.next().get("placeList").toString();
     }
     System.out.println(places);
     String[] place=places.split(",");
     for(int i=0;i<place.length;i++)
     {
         System.out.println(place[i]);
     }
</code>
Answer: This is how your code should look like:
<code>MongoClient client = new MongoClient("localhost",27017); //with default server and port adress

     DB db = client.getDB("placedb");

     DBCollection areaColl=db.getCollection("places");

     BasicDBObject allQuery = new BasicDBObject();
     BasicDBObject fields = new BasicDBObject();
     fields.put("placeList", 1);
     DBCursor cursor = areaColl.find(allQuery, fields);

     String places = "";
     while(cursor.hasNext())
     {
         places=cursor.next().toString();
         System.out.println(places);
     }

     String[] place=places.split(",");
     for(int i=0;i<place.length;i++)
     {
         System.out.println(place[i]);
     }
</code>
Comment: is your db password protected?
Comment: it was made by some one else...i have to access their db...i don't think it will be a problem..... i think i have to specify only the i/p...i'm very new to mongodb
Comment: Check if you have specified the correct port, default port is 27017. If DB is password protected then you need to key in the user credentials as well.
Comment: sry vmr now it's working well...but i need only the "placelist" values it's giving entire o/p including "objectid"
Answer: Chk this............................................
<code>     MongoURI uri = new MongoURI("mongodb://ip of server");
    Mongo mongo = (new Mongo.Holder()).connect(uri);
    DB db = mongo.getDB("placeDB");
    DBCollection coll = db.getCollection("places");
    DBCursor cursor = coll.find();
    JSONArray placeList = new JSONArray();
    String places = "";
    while (cursor.hasNext()) {
        places = cursor.next().get("placeList").toString();

    }
    String[] place = places.split(",");
    for (int i = 0; i < place.length; i++) {
        placeList.add(place[i]);
    }

    System.out.println(placeList);
</code>
Comment: thanks Rose but i need some specific field not the entire o/p

Extracting specific fields from mongodb


Finding the 7th smallest element in Min heap

Question: In a min-heap with n elements with the smallest element at the root, the 7th smallest element can be found in time -
a) Θ(nlogn)
b) Θ(n)
c) Θ(logn)
d) Θ(1)

==========================================================================
I am so confused between option c and d. Do we need to do Extract Min 7 times or simply do comparisons as at root level - 0 comparison, at 1st level - 3 comparison between root and LC and RC and so on.
Comment: You need 6 extract operations to find 7th element. Extract operation in binary heap has `O(log(n))` complexity. Overall complexity is `O(6 * log(n))` = `O(log(n))`
Comment: How, please share your insight.
Comment: @JimMischel Please share your knowledge! :)
Comment: Possible duplicate of [O(klogk) time algorithm to find kth smallest element from a binary heap](https://stackoverflow.com/questions/7650917/oklogk-time-algorithm-to-find-kth-smallest-element-from-a-binary-heap)
Comment: @DAle can we apply Heapsort and if not, why?
Answer: I'd say the question is ambiguous.
If we have to use the heap interface, we can do no better than extract the minimum 6 times, and look at the 7-th minimum. Each time except the last, we can spend anywhere from 1 (best case) to log n (worst case) operations, so it's O(log n) but not Theta of anything. The 7-th operation is Theta(1).
If we can exploit the heap's internal structure, as Yves Daoust already pointed out, we can be sure that the heap contains its minimum element in its first 7 levels, which have at most 1+2+4+8+16+32+64=127 elements. Finding a minimum in the first 127 numbers of the array where the heap is stored is Theta(1) because, however large, 127 is still a constant and does not depend on n.
Seeing that option (c) is not really a correct answer in first case (It would be if O() was used instead of Theta()), I'd go with (d).
Comment: Interesting remark about the restriction to the heap interface.
Comment: The question is not explicit enough about that. You are right to say that there is no Θ class for the raw running time in the case of heap operations. But the *worst-case* running time is indeed Θ(Log n). [The raw running time is not a unequivocal function of n. The worst-case, best-case and average-case are.] When we limit ourselves to the first 7 levels, we of course have O(1)=Θ(1).
Comment: @YvesDaoust Hmm, I see, thanks! So option `(c)` would be a correct answer if the question was about worst-case performance, and it mentioned we have to stick to the interface. That looks like too much unmentioned defaults to me, so I'd stick with `(d)`.
Comment: @YvesDaoust What I say is `Theta()` does not make sense for the first part, only `O()` does. In the best case (sift-down exits after first iteration), extracting a minimum takes `1` operation. In the worst case (sift-down goes all the way to the bottom), it takes `log n` operations. So sift-down does not belong to any `Theta()` complexity class. The tight bound in `O()` is `O(log n)`. I understand that `O(log n)` is a subset of `O(n)` etc., but the same does not hold for `Theta()`. Right?..
Comment: @Gassa May be please explain this line in a simplified manner - because, however large, 127 is still a constant and does not depend on "n"
Comment: @MicroLegions Whether `n = 1` or `n = 1000` or `n = 10^{10^{10}}`, 127 remains just the constant 127, it does not depend on `n`. We are asked to find the complexity in terms of `n`. The complexity classes drop the constant, so `O (127 * n^0) = O (n^0) = O (1)`.
Comment: @gassa I'm so so sorry to bother, but why you took n^0 in O (127 * n^0). Can I say as n = 100 and O(127*100) = O(12700) which is nothing but a constant?
Comment: @MicroLegions That's how asymptotic notation works. The phrase "time is O(n^3)" means "there exists a constant C such that, as n tends to infinity, the time has an upper bound of C * n^3". So, the variable n is already bounded as "the thing which tends to infinity", it is incorrect to simultaneously declare it a constant. The "7th smallest element", on the other hand, is given as a constant in the problem statement. If the problem asked what would happen when we need the k-th smallest element, the 127 would turn into 2^k - 1.
Comment: @Gassa if the question is finding the K'th smallest element in min heap of n nodes? Then can we also say it's O(k) or O(1) as K is a constant?
Comment: @Geeklovenerds The explanation presented an O(2^k) way to do it. If k is a constant, yeah, we can say it's O(1). How meaningful it is in practice? Depends on the particular case.
Answer: In the worst of the situations, the 7th element will be found in the 7 first levels of the heap, which contain at most 127 elements. You can find it by sorting these elements, which takes O(1).
CAUTION: this is not meant to be an efficient procedure, it is a simple theoretical argument to prove that the problem can be solved in constant time.
A possibly better procedure is to perform the selection phase of heapsort on the 127 elements heap, which will take at worse like lg 127 + lg 126 + lg 125 + lg 124 + lg 123 + lg 122 + lg 121 operations (very gross estimate, but it doesn't matter, it is O(1)).
Comment: Updated after seeing a flaw in the estimates.
Comment: @MicroLegions: Gassa explained it. In a restricted version of the question, the answer could be Θ(Log N). With the normal interpetation and as unambiguously  said in my answer, Θ(1).
Comment: So, what's the final answer O(1) or O(logn)?
Comment: @Geeklovenerds O(1) is the correct answer.
Answer: In min heap elements are not stored like binary search tree (i.e. smaller than root on left side and larger on right). A smaller element can present at any children node therefore, we cannot search element like we do in binary search tree.
So, we need to first pop top 6 elements from heap and store them in array, now 7th element is on root so we pop it and store it. Now we push all 6 element that we pop earlier into heap.
Time Complexity:-  7 operation to pop and 6 operation to push therefore total 7 + 6 = 13 operation. And each operation cost logn amount of time.
So, time complexity becomes 13*logn or simply O(logn)
Comment: No, you have to search among a bounded number of elements, hence O(1), even with sorting.
Comment: Can we apply Heapsort? If not, why?
Comment: yes you can but it is very inefficient its time complexity is O(nlogn) while the current algorithm's time complexity is O(logn)
Comment: After popping each element, you will have to run the heapify function to regenerate a min-heap which would amount to O(logn) time complexity. So popping is the wrong approach here. Instead if you limit the search area to top 7 levels then finding the 7th smallest element is O(1).
Comment: https://gateoverflow.in/1110/Gate-cse-2003-question-23
Answer: The answer will be O(n).Everyone here is assuming that you will have a Constant range under which you can find the answer so O(1) will be the answer but they  miss a point that a min heap can have duplicates . Lets say that 6th smallest element has 1 million duplicates then how would you calculate the range when it is not even given the number of duplicates is and on top of that let say the last element is 7th smallest you will have to search the whole array. Hence the answer is n.


Basics of running multiple internal ruby/rails apps on an IIS server - is something like passenger required for this situation?

Question: I am going to be deploying  about a dozen rails apps on an IIS server. These apps are behind out firewall for internal use only. They will all be low usage but critical apps.
The current setup is

IIS running on server 2012
Rails 4 is running on iis installed via the webplatforminstaller.
We will be using MS sql server
Apps uploaded from the laptop to the server do run.
There will be about 15 apps running. We can add another server if necessary.
Nothing else will be running on that server
E.g. an app might be located in c:\inetpub\wwwroot\apps\sales  and another in \hr. etc.
What I've read about deploying multiple rails apps seems to be geared toward public facing sites. I don't see much about private sites using a server ip/folder setup

Question:
 - Can multiple apps be run without adding a tool such as passenger?
Comment: Um, Passenger is a Linux/Unix application which works with nginx or Apache and won't do you any good on IIS. If I had any choice whatsoever I would choose not to deploy on IIS/MsSQL. There are very few rails shops that do and the adapters etc are not in the ballpark of what is available for Unix/Postgres/outside the MS box. Lots of headaches - very few benefits.
Answer: It is possible using the IIS HttpPlatformHandler extension. Scott Hanselman did a good write up on it that explains how to use it.
Although, in that blog post it's suggested to use JRuby and Tomcat. I don't think that is necessary, however I would suggest using puma as your webserver.
Comment: Thanks- I got it running with a combo of Puma and Jruby.


How to pass extra parameters in HTTP DELETE request?

Question: I am writing a REST API, which supports POST/GET/DELETE method for the same url.
For the DELETE method, the API needs extra parameters (details of the deletion). But the library I am using doesn't support request body for DELETE method, how can I do it?
If I put the parameter in URL like:
DELETE /API/Resource/id/parameter

Then I break the RESTyness.
Or I need to use another method POST/PUT, which is not RESTy, either.
Comment: Use query parameters or introduce custom request header(s) or change  the library you are using ;)  You should be more specific on what is a purpose of the extra parameters.
Comment: A URI itself does not state whether it (or the endpoint/resource behind) adheres to REST constraints or not. After all, a URI remains a URI no matter what and is neither RESTful nor RESTless. Also, the HTTP operation used does not really give a clue on whether the interaction is RESTful or RESTless. REST occurs from the interaction client and server have and when a client is only using the information provided by the server (think of Web surfing for applications)
Answer: Why is POST / PUT not RESTy? Take a look at the twitter REST API: You can destroy a status by POSTing to /statuses/id/destroy. That request does accept parameters. You could do something similar to this:
POST /API/Resource/id/destroy

I think that is RESTy enough.
Comment: Destroy is an action, not a resource... Looks we have to live with the loose definition of REST.
Comment: @hfhc2, IMHO twitter API is the worse API I've ever used. Using it as an example is not a good idea.


How to generate report in pdf format using R

Question: I am trying to find out the R code which will give me the output of the statistical analysis(i.e. Regression, DOE, Gage RR) in pdf or html format by using R ( Not by using R-studio). I want to generate report of my statistical analysis. Is there any R code which we can run in to the R to make pdf or html file ??. I know it for graphs only,
pdf("output.pdf")
x=rnorm(100,40,3)
y=rnorm(100,100,5)
fit=lm(y~x)
summary(fit)
plot(y)
dev.off()

This code gives me graph in pdf but I want all the summary of fit (ANOVA) and all information that R generates. Thanks
Comment: I do not want to use R-studio, I want to do it by using R only.
Comment: `pdf` is a PDF graphics device, which you could print text to with a lot of work, but it's not worth it. RMarkdown is the obvious answer here, and it can be used without RStudio, though RStudio does make using RMarkdown simpler and more powerful, so I'm not sure why you'd want to avoid it.
Comment: Thanks @alistaire, In my organisation I am not allowed to use R-studio. That's why I want to prepare .exe files by using R scripts. As we know in R-studio after clicking on "knitr" option in rmarkdown,  code executes and we get nice output in pdf as well as in html format. I want code which can be used in R and which will work like "knitr" function of R-studio and give output in pdf or html format.
Comment: I believe the "Knit" button really just calls `rmarkdown::render` on the current file, so you can easily replicate that with a text editor that can handle RMarkdown and an R repl.
Answer: Yes, RMarkdown/knitr is the way to go.
See here for the documentation for creating a pdf document.
Your Rmd file might look something like the following:
---
title: "Report"
author: "XXX"
date: "January 7, 2017"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Output

```{r}
x <- rnorm(100, 40, 3)
x

y <- rnorm(100, 100, 5)
y

fit <- lm(y ~ x)
summary(fit)
```

## Plot

```{r plot, echo=FALSE}
plot(y)
```

For an html document, simply change to output: html_document.
Render the pdf or html document with rmarkdown::render('filepath/yourfile.Rmd')
Comment: Thanks @alistaire, for your help. Could you please recommend me any book, website for to understand how to use all this in R ( not in R-studio) step by step bcz I am new to R. So that I can write nice programme in R. And how to use "rmarkdown" as well as "knitr" package in R ( not in R-studio) to get pdf / html output. thanks again.
Comment: Thanks @Conrad-mac


Pass data from TodayExtension to app

Question: Is it possible to pass data from a today extension to an app? (Even when its not currently running). I wish to pass an array of objects to the main app and instantiate a viewController based on the objects passed from the today extension. I know how to open the app from the extension just not to too sure how to send data to the app.
var arrayToBePassed: [MyDataSource]

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        var url = ""
        if currentSort == .recent{
            url = "ext://recent"
        }else{
            url = "ext://popular"
        }
        //HOW DO I PASS arrayToBePassed to my app?
        let myAppUrl = NSURL(string: url)!
        extensionContext?.openURL(myAppUrl, completionHandler: { (success) in
            if (!success) {
            }else{

            }
        })
    }

Answer: There's a few routes you could go down:
• In your app, implement a URL scheme that can quite literally take that array of objects, formatted as some sort of URL parameter. e.g. myAwesomeApp://objectArray=[these, are, strings]. You'll have to parse that URL yourself which should be a bit of fun.
• Look into NSUserDefaults. You can initialise a 'shared' user defaults object that both your app and your today extension can use, see here for more info. You could then store your array in here, and access it from the app when opened.
It really depends on what you're trying to do, but from the impression I get, I feel like the first option may be the best answer. I haven't provided any code, just an outline of how I'd go about it - but hopefully that should be enough to get you off to a good start.
Comment: Thanks for your answer, I don't think the first option will for work me, the data being passed is not an array of `strings` just an example (I should probably update the question). I'll definitely look into shared user defaults though
Comment: @kye sure, whatever you're doing you'll probably want to convert your array of objects to NSData somehow (you might want to have a look as `NSCoding`). Depending on how much there is to your object array, turning this NSData into a string you can just pass to the URL might even be an option (don't quote me on that).
Answer: Sharing of data is achieved through a new concept called "App Groups". App Groups are allowed to share some data, including files, but it is worth noting that file access needs to be marshalled to avoid concurrent writes and so forth. This can be achieved through NSFileCoordination, but CoreData and NSUserDefaults handle this out of the box.
You can find the detial Steps here

Pass data from TodayExtension to app


How to dynamically add watermark to report in Stimulsoft

Question: I would like to dynamically add watermark to a report that is generated in Stimulsoft. The watermark can not be hard-coded and only appear if the report was generated in TEST environment.
I have a variable that checks if the report was created in test environment:
isTestEnv
Which means that if the watermark was added to the page the old fashioned way I would use:
if(isTestEnv == true) {
   Page1.Watermark.Enabled = true;
} else {
   Page1.Watermark.Enabled = false;
}

But this is not the case. I have to add the watermark when generating the report. Does anyone know how to?
The text is same on all pages it simply says "TEST". But how to push that into a report is the mystery.
Answer: you can use this code and set your water mark image in your report
Stimulsoft.Base.StiLicense.loadFromFile("../license.key");
var options = new Stimulsoft.Viewer.StiViewerOptions({showTooltips:false});
var viewer = new Stimulsoft.Viewer.StiViewer(options, "StiViewer", false);
var report = new Stimulsoft.Report.StiReport({isAsyncMode: true});

report.loadFile("Backgroundimg.mrt");
var page = report.pages.getByIndex(0);

page.watermark.image = Stimulsoft.System.Drawing.Image.fromFile('test.jpg');
page.watermark.aspectRatio = true;
page.watermark.imageStretch = true;
page.watermark.imageShowBehind= true;

report.renderAsync(function () {
    viewer.report = report;
    viewer.renderHtml("viewerContent");
});

Answer: You can set the report page watermark to some Report variable at design time and in your code set the value for the report variable.
Something like this:
StiReport report = new StiReport();
report.Load("REPORT_TEMPLATE_PATH");
//You can check if this variable exists or not using an if condition
report.Dictionary.Variables["WATERMARK_VARIABLE_NAME"] = "YOUR_TEXT";
report.Show();//or report.ShowWithWpf();


Store email that are used to log in and show as suggestion on the email input during next Login - Android Application

Question: I am trying to find a way to keep all the email used for login into the application in a device and show them as suggestion or autocomplete when ever a user tries to login in to the application.
I tried using shared preferences and store them into an ArrayList during the login. However each time I login, the email gets replaced with the latest login email instead of adding up.
Example: first i login with firstname.lastname@example.com and logout from the system. For next login the suggestion firstname.lastname@example.com shows up. However if now i login with email@example.com, the old stored email is replaced with the new one.
What I did to get this was first after login I stored the user email from the server response in a shared preference.
Next I put that data into an ArrayList
<code>    SharedPreferences getEmail = getSharedPreferences("userEmail", Context.MODE_PRIVATE);
    String input_email = getEmail.getString("emp_email", "");

    ArrayList<String> userList = new ArrayList<>();
    userList.add(input_email);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, userList);
    if (userList.size() > 0){
        userEmail.setAdapter(adapter);
    }
</code>
The above code in inside the onCreate method of the login activity. How can i do this.
I am guessing maybe this is not the correct way to remember email address for auto suggestion. If so then please point me to the right direction.
Thank you.
Update
Fetching response from the server in LoginActivity on successful login
<code>public void getDataForId() {

    SharedPreferences authToken = getSharedPreferences("authToken", Context.MODE_PRIVATE);
    String token = authToken.getString("token", "");

    apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
    Call<UserResponse> call = apiInterface.getData("Bearer " + token);
    call.enqueue(new Callback<UserResponse>() {
        @Override
        public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {

            if (response.isSuccessful()) {

                String emp_email = response.body().getUser().getEmail();

                ArrayList<String> listEmails = getFromPrefs(this);

                if(listEmails == null){
                   listEmails = new ArrayList<>();
                   listEmails.add(emp_email);
                }

                saveToPrefs(this, listEmails);

                /*Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());

                if(!listEmails.contains(emp_email)){
                   listEmails.add("email@example.com");
                }

                saveToPrefs(this, listEmails);

                Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());*/

            } else {
            }
        }

        @Override
        public void onFailure(Call<UserResponse> call, Throwable t) {
        }
    });
}
</code>
Note that in am getting the email in the variable **emp_email* (assume the other two functions given by you are in the file). What I assume is that the commented out part (after the first email is saved), will start in the onCreate methode for me as after logging out.
there i get the pref data see it the new email matched the pref data and then store it. This is when it is getting replaced.
Answer: Try this.
I have edited your code
gist.github.com/adrielAd/b1fbc4f8665183eb195871d21cd415eb
<code>// make listEmails global and also initialise this in onCreate so you get already saved emails when you come to this screen
ArrayList<String> listEmails;

public void getDataForId() {

    SharedPreferences authToken = getSharedPreferences("authToken", Context.MODE_PRIVATE);
    String token = authToken.getString("token", "");

    apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
    Call<UserResponse> call = apiInterface.getData("Bearer " + token);
    call.enqueue(new Callback<UserResponse>() {
        @Override
        public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {

            if (response.isSuccessful()) {

                String emp_email = response.body().getUser().getEmail();

                listEmails = getFromPrefs(this);

                if(listEmails == null){
                   listEmails = new ArrayList<>();
                   listEmails.add(emp_email);
                }else{
                  if(!listEmails.contains(emp_email)){
                     listEmails.add(emp_email);
                  }
                }

                saveToPrefs(this, listEmails);

                /*Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());

                if(!listEmails.contains(emp_email)){
                   listEmails.add("email@example.com");
                }

                saveToPrefs(this, listEmails);

                Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());*/

            } else {
            }
        }

        @Override
        public void onFailure(Call<UserResponse> call, Throwable t) {
        }
    });
}
</code>
Answer: You can do like below.
<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<String> listEmails = getFromPrefs(this);

    if(listEmails == null){
        listEmails = new ArrayList<>();
        listEmails.add("email@example.com");
    }

    saveToPrefs(this, listEmails);

    Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());

    if(!listEmails.contains("firstname.lastname@example.com")){
        listEmails.add("firstname.lastname@example.com");
    }

    saveToPrefs(this, listEmails);

    Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());

}

public static void saveToPrefs(Context context, ArrayList<String> listEmail) {
    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context.getApplicationContext());
    SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
    Gson gson = new Gson();
    String list = gson.toJson(listEmail);
    prefsEditor.putString("list", list);
    prefsEditor.commit();
}

public static ArrayList<String> getFromPrefs(Context context) {
    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context.getApplicationContext());
    Gson gson = new Gson();
    String list = appSharedPrefs.getString("list", "");
    ArrayList<String> listEmail = gson.fromJson(list, ArrayList.class);
    return listEmail;
}
</code>
Here is the screenshot for logs
Comment: try adding this in your code

if(listEmails == null){
            listEmails = new ArrayList<>();
            listEmails.add(emp_email);
        }else{
            if(!listEmails.contains(emp_email)){
                listEmails.add(emp_email);
            }
        }
Comment: try this. I have edited your code

https://gist.github.com/adrielAd/b1fbc4f8665183eb195871d21cd415eb
Comment: I have added a new answer, as old answer shows about saving list in shared preferences
Comment: Thank you very much for your advise. I have been busy all day with work so i could not check it. I will do asap and give a feedback for others to see.
Comment: what is did was

 `ArrayList userList = new ArrayList<>();`
at the start of the class. Then I added the server response of the email to the userList like
`String emp_email = response.body().getUser().getEmail();

                    if (!userList.contains(emp_email)){
                        userList.add(emp_email);
                    }`

then saved it to tinyBD like
`TinyDB tinydb = new TinyDB(LoginActivity.this);
                    tinydb.putListString("user_email_id", userList);`
Now, when i get this string, i still only get the last logged in user id like before.
Comment: Did you reinitialised the list with tinyDB list? And then added the new email id in that list?
Comment: Yes.
However I maybe found the reason, somewhere I read that an ArrayList gets destroyed as garbage collector once an app is closed. Hence I'm getting an empty list everytime.
Comment: But if you initialise arraylist with the list stored then it should give you all email ids that you ave stored
Comment: when im initializing the arrayList with list stored, i got something like `[email@example.com, firstname.lastname@example.com]`. Maybe my initialization was wrong. However, what i did was save the data to a text file and read it back when i needed it.
Comment: just edited my answer. Please check that out. For gson you can add

implementation "com.google.code.gson:gson:2.8.2"

in gradle
Comment: In your solution you have taken two static strings to append the user list. For my case, i have one string variable which stores an email address sent from the server as response. What I think is happening in my case is, when I am getting a response, my string variable is changing and hence when I'm trying to append the array list, its simply getting replaced.
Comment: In your case if you enter one email at one time and save that by appending the list then every time you come to login screen and fetch the stored list you will be getting 1 email that you stored? right? Now when after logout you enter new email you can append that too in existing list and store that list in shared pref. In this way you can relate this to my 2 static strings.
Comment: I very much appreciate the time and effort you are investing into this. I cannot thank you enough. I have updated my question with what i did. Please if you dont mind, can you look into that.
Comment: I dont know how can I thank you. It worked. I really cannot thank you enough for helping me with this. Can you please update your answer with this code so i can mark it correct. Thank you a thousand times.


Counting the frequency of a list of pairs in an RDD with pyspark

Question: I am trying to calculate the frequency of some pairs (stored in a list) in an RDD where each element is a list of strings. Teh RDD has this form:
<code>[['protectuаsky', 'stoprussia', 'ukraineunderattaсk'],
 ['russianinvasion',
  'standwithukraine',
  'ukraineunderattack',
  'ukrainewillwin',
  'putinisawarcriminal',
  'stopputin',
  'russianukrainianwar',
  'russiagohome',
  'россиясмотри',
  'нетвойне'],
 ['russianukrainianwar', 'china', 'taiwan'],
 ['anonymous', 'oprussia', 'ddosecrets'],
 ['nft', 'mint']
 ...
]
</code>
My goal is to compute, for example, the frequency of the pair ('stoprussia','nft')
Comment: do you mean that you want the frequency of the occurrence of the two terms at the same list in the global list or you want the frequency of each term 'stoprussia' then 'nft'?
Comment: I want to calculate the frequency of the pairs in the RDD. Let's make a better example: my rdd will be like [ ["A","B","C"],["A","D"],["C","B","D"],["C","E"]].         The frequency of the pair ("B","C") should be 2 (first and third elements in the RDD.
Comment: Rereading you comment, I need the first thing you said. Keep in mind that the one you called global list is an RDD and to perform this operation I have to use the map reduce paradigm in order to ha it scalable with data
Answer: <code> def frequency(content,element):
        fre = 0
        for i in content :
            if set(element).intersection(set(i)) == set(element) :
                fre += 1
        return fre
</code>


Calling a function inside a switch case

Question: I am trying to convert the following if, else if, else to a switch statement.
    if(zipValue === "") {
    setErrorFor(zip, 'Please enter a zip code');
} else if (!isZip(zipValue)) {
    setErrorFor(zip, 'Not a valid Aust zip code');
} else {
    setSuccessFor(zip);
}

So far I have tried:
switch (zipValue) {
case "":
setErrorFor(zip, 'Please enter a zip code');
break;
case !isZip(zipValue): //can't get this working
setErrorFor(zip, 'Not a valid Aust zip code');
break;
default:
setSuccessFor(zip);
break;

}
the function isZip checks against a regex as shown here:
function isZip(zip) {
 return /^[0-9]{4}$/.test(zip);
 }

The original if, else if, else is working I just want to learn more about using a switch statement and make my code cleaner. Thank you.
PS after posting this I now see the irony that the switch statement is using more lines of code.
Comment: Why are you trying to change this code? The code is already in a clear and readable form. You seem to be deliberately butchering it... why?
Comment: `switch` compares the value of the supplied expression against the case values using a strict comparison (===), here you are comparing against a string in the first case and a boolean in the second so one of them will never match depending on the type of the initial `zipValue`.
Comment: Yes, you can try ternary where you return a value instead of boolean for comparison with the zipValue from the switch. Then it'll work.
Comment: I could try something like ternary with conditional chains.
Comment: I found this about using daisy chained ternary:
https://stackoverflow.com/a/49762262/12822663

I have already used one ternary in my program as follows:

!terms.checked ? setErrorFor(terms, 'Please agree to the terms') : setSuccessFor(terms);
Comment: Sometimes to have to break something that is working in order to learn more.
Answer: The value in the case statement for !isZip(zipValue) is always going to return a boolean. I'm guessing that zipValue will always be a string. Therefore that case statement will never be run since you're comparing two values of two different data types. So if someone inputs a zip code let's say 12345, then when it gets to that case block it will return false. And 12345 does not equal false

Calling a function inside a switch case


Erro ao modificar coluna de uma View com cálculo

Question: Preciso inserir uma coluna de cálculo nessa view abaixo, mas aparece a mensagem

Msg 205, Level 16, State 1, Procedure ConsolidadoEstudoBaseSifix, Line
  4 [Batch Start Line 9] All queries combined using a UNION, INTERSECT
  or EXCEPT operator must have an equal number of expressions in their
  target lists.

Sei que o erro está no UNION ALL, mas no caso não queria inserir mais colunas no "percentual."
Como posso resolver essa questão?
Segue código:
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER VIEW [dbo].[ConsolidadoBaseSifis] AS

with contabilidade as (

SELECT iUnidade,
COUNT(iUnidade) AS iQuantidade,
COUNT(vSimNao)  AS iSimNaoRespondido,
COUNT(vResp)  AS iJustificRespondidas
FROM  [dbo].[BaseSifis]
GROUP BY iUnidade
),

percentual as(

SELECT
(((iSimNaoRespondido+iJustificRespondidas)/iUnidade)*100) as iPorc
from contabilidade

)

select * FROM contabilidade

Union ALL

select * FROM percentual

Em resumo, ela está assim:

E gostaria que ficasse assim:

O script original é este:
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[ConsolidadoBaseSifis] AS
    with contabilidade as (

    SELECT iUnidade,
    COUNT(iUnidade) AS iQuantidade,
    COUNT(vSimNao)  AS iSimNaoRespondido,
    COUNT(vResp)  AS iJustificRespondidas
    FROM  [dbo].[EstudoBaseSifis]
    GROUP BY iUnidade
    )

    select * FROM contabilidade
GO

Comment: No `UNION` tem de haver correspondência entre as colunas de cada tabela. O que pretende juntar nas duas tabelas? A coluna `iPorc` corresponde a que coluna da tabela `contabilidade`?
Comment: No caso, eu quero criar uma coluna iPorc que é = (((iSimNaoRespondido+iJustificRespondidas)/iUnidade)*100) ... tentei criar esta iPorc dentro de contabilidad, porém ele faz referência a colunas que estão sendo criadas por ela...
Comment: Edite a sua questão e coloque lá o código, senão é difícil de perceber.
Comment: Ok, inseri duas imagens para ficar mais fácil visualizar
Comment: E coloquei o script original
Answer: Experimente dessa forma:
ALTER VIEW ConsolidadoBaseSifis
AS
    WITH contabilidade  AS
    (
        SELECT      iUnidade
                ,   COUNT(iUnidade) AS iQuantidade
                ,   COUNT(vSimNao)  AS iSimNaoRespondido
                ,   COUNT(vResp)    AS iJustificRespondidas
        FROM        BaseSifis
        GROUP BY    iUnidade
    ),  percentual      AS
    (
        SELECT  iUnidade
            ,   iQuantidade
            ,   iSimNaoRespondido
            ,   iJustificRespondidas
            ,   (((iSimNaoRespondido + iJustificRespondidas) / iUnidade) * 100) AS iPorc
        FROM    contabilidade
    )
    SELECT  *
    FROM    percentual
GO

Se não quiser mesmo colocar mais colunas, para além do iPorc e claro, a iUnidade (caso contrário não conseguirá ligar as duas tabelas), poderá fazer assim:
ALTER VIEW ConsolidadoBaseSifis
AS
    WITH contabilidade  AS
    (
        SELECT      iUnidade
                ,   COUNT(iUnidade) AS iQuantidade
                ,   COUNT(vSimNao)  AS iSimNaoRespondido
                ,   COUNT(vResp)    AS iJustificRespondidas
        FROM        BaseSifis
        GROUP BY    iUnidade
    ),  percentual      AS
    (
        SELECT  iUnidade
            ,   (((iSimNaoRespondido + iJustificRespondidas) / iUnidade) * 100) AS iPorc
        FROM    contabilidade
    )
    SELECT      iUnidade
            ,   iQuantidade             = SUM(iQuantidade)
            ,   iSimNaoRespondido       = SUM(iSimNaoRespondido)
            ,   iJustificRespondidas    = SUM(iJustificRespondidas)
            ,   iPorc                   = SUM(iPorc)
    FROM        (
                    SELECT  iUnidade
                        ,   iQuantidade
                        ,   iSimNaoRespondido
                        ,   iJustificRespondidas
                        ,   iPorc = 0
                    FROM    contabilidade
                    UNION ALL
                    SELECT  iUnidade
                        ,   iQuantidade             = 0
                        ,   iSimNaoRespondido       = 0
                        ,   iJustificRespondidas    = 0
                        ,   iPorc
                    FROM    percentual
                ) X
    GROUP BY    iUnidade
GO

Mas parece-me algo demasiado trabalhoso e pouco performante quando o que queremos é, basicamente, o resultado da tabela percentual.
Comment: Excelente!!
A primeira opção deu certo!! Obrigado!!
Comment: De nada! Marque a resposta como válida e dê um UP :)


CakePHP - Recuperar valor do option

Question: Olá! Estou consertando um website que peguei pronto e nele tem uma parte que o usuário seleciona um bairro em um <option>, porém, este <option> não está enviando a informação para o banco de dados.
Selecionando a cidade, aparece os bairros desta determinada cidade. Aqui está o arquivo view:
echo $this->Form->input('cidade', array('label' => 'Cidade', 'empty' => 'Selecione uma cidade', 'options' => $Cidades));
echo $this->Form->input('bairro', array('label' => 'Bairro', 'empty' => 'Selecione o Bairro', 'options' => array()));

No controller, a função para add:
public function add () {
    if (empty($this->request->data)); else {
        $data = $this->request->data;
        if ($data['Imovel']['opcoes']) $data['Imovel']['opcoes'] = implode(';', $data['Imovel']['opcoes']);
        $data['Imovel']['ativo'] = $data['Imovel']['ativoPeloAdm'] = 1;
        $data['Imovel']['creator'] = $data['Imovel']['modifier'] = $this->Session->read('Auth.User.Imobiliaria.id');
        if ($data['Imovel']['bairro']) {
            $bairro = $this->Cep->find('first', array('conditions' => array('id' => $data['Imovel']['bairro'])));
            $data['Imovel']['bairroNome'] = $bairro['Cep']['bairro'];
        }

        if ($data['Imovel']['cidade']) {
            $cidade = $this->Cidade->find('first', array('conditions' => array('id' => $data['Imovel']['cidade'])));
            $data['Imovel']['cidadeNome'] = $cidade['Cidade']['nome'];
        }

        $data['Imovel']['especificacao'] = $data['Imovel']['imovel'];
        if ($this->Imovel->save($data)) $this->redirect(array('action' => 'index'));
    }
}

Alguém pode me ajudar?
Ajax :
    $('#ImovelCidade').change(function(e) {
    $('#ImovelBairro').html($('<option />').val('').text('Carregando...'));
    $.getJSON(
        "<?php echo Router::url(array('controller' => 'pages', 'action' => 'pegarBairros')) ?>",
        { "cidade" : $(this).val() },
        function (data) {
            $('#ImovelBairro').html($('<option />').val('').text('Selecione'));
            $.each(data, function (chave, valor) {
                $('#ImovelBairro').append($('<option />').val(chave).text(valor));
            } );
        }
    );
});

Função pegarbairros no controller:
public function pegarBairros ($cidade = null) {
    $this->layout = 'json';
    $result = array();

    if (in_array($_REQUEST['cidade'], array_keys($this->cidade))) {
        $bairros = $this->Cep->find('list', array('fields' => array('id','bairro'), 'conditions' => array('cidade' => $this->cidade[$_REQUEST['cidade']]),'group' => 'bairro'));
        sort($bairros);

        foreach ($bairros as $id => $bairro) {
            if (!empty($bairro))
                $result[$id] = $bairro;
            else
                $result[] = 'error';
            $this->set('data', $result);
        }
    }
}

estou tentando inserir um bairro, mas está retornando um Array
Comment: Parece estar faltando alguma coisa, normalmente nesse caso a consulta pelos bairros da cidade seria feita utilizando ajax. Tem certeza que está tudo aí? Não tem nenhum [tag:javascript] faltando?
Comment: Você ligou o nível 2 de debug no `core.php`?
Comment: @ErlonCharles , vou postar o js !
Answer: Lendo seu código me parece que é um erro na formatação dos dados. Você precisa que seu ajax retorne um json assim você vai ter mais facilidade para manipular o retorno por javascript e gerar um html válido.
O que eu sugiro:
public function pegarBairros ($cidade = null) {
    $this->layout = 'json';
    $result = array();

    if (in_array($_REQUEST['cidade'], array_keys($this->cidade))) {
        $bairros = $this->Cep->find('list', array('fields' => array('id','bairro'), 'conditions' => array('cidade' => $this->cidade[$_REQUEST['cidade']]),'group' => 'bairro'));
        sort($bairros);

        foreach ($bairros as $id => $bairro) {
            if (!empty($bairro)) {
                $result[$id] = $bairro;
            } else {
                $result[] = 'error';
            }
            $result = json_encode($result);
            $this->set('data', $result);
        }
    }
}

Comment: eu troquei por este codigo e nao aparece nada, apenas carregando....
Comment: me mostre um exemplo do json que está sendo retornado
Comment: o json está retornando a posicao do item na lista...

CakePHP - Recuperar valor do option


Prove or disprove that the sum of two irrational numbers is irrational

Question: Prove or disprove that the sum of two irrational numbers is irrational. How do i answer this? Thanks.
Comment: Well understanding the definitions is really the beginning of how to work with these questions, and questions such as this are asked to help you to think through what the definitions imply. So you need to make sure you do know the definition.
Comment: Have you any thoughts of your own on this problem?
Comment: I don't know how to define an irrational number, root a doesn't work and i can't think of another way
Comment: Perhaps you meant to ask: Given $a, b \in \mathbb R \setminus \mathbb Q, a \ne -b$, does $a + b \in \mathbb R \setminus \mathbb Q $ ?
Comment: This is a duplicate of many, many questions, but I can't find them. Oh well, it's also missing context, so I will close it as that.
Answer: Since $-\sqrt{2} + \sqrt{2} = 0$, so the sum of two irrationals may be rational.
Comment: What do you think "irrational" means, @Heelloppp ?
Comment: How is that the sum though, isn't that the difference? Isn't it the same as saying root 2 - root 2?
Comment: a sum takes the form $a_{1}+a_{2} + \cdots$...
Comment: So does that prove or disprove the question? It says the sum of two irrational numbers is irrational, but can't it be both rational and irrational?
Comment: It disproves the proposition.
Comment: It's like asking if a woman can both be pregnant and not pregnant…
Comment: @Heelloppp: A real number that is not rational is called irrational. Very simple, please be noted.
Comment: @Heelloppp $\sqrt 2+(-\sqrt 2)=0$ and you will admit that $-\sqrt 2$ is irrational, I think.
Answer: ($2+\sqrt3$)+($2- \sqrt3$) $=$ $4$  which  is  rational. So , the  statement " sum of two irrationals is irrational"  is  disproved since  counter example  is  found.
When  a  statement  like  that  is  given  to   prove  or  disprove, " sum of two irrationals is irrational" , it  is  proved  if  it  is found  to  be  always true  and  disproved  if  at  least  one   counter  example  can  be  given.
In  fact,  sum  of  two  irrationals  can  be  either  rational  or  irrational. Not  necessarily  irrational  all  the  time.


Assing multiple values to one variable - shell

Question: I have a code running at the moment that pulls data from a txt file . But  I decided not to take all the values from a separate list,i want to implement these values direct into the code
<code>$SERVERS = gc "C:\Users\listofSERVERS.TXT "
</code>
Rather have all values in the code
<code>$SERVERS =( echo "Server1, Server2, Server3 ..." )
</code>
But the code is returning an empty file. Not sure if I am assigning $SERVERS variable correctly.
Answer: The doublequotes make it a single string.  It could be as simple as:
<code>$SERVERS = echo Server1 Server2 Server3
</code>
Answer: If you want an array of servers you can use something like the below. Note that it will only print out the current server to the console :)
<code>$servers = @("Server1","Server2","Server3")
Foreach($server in $servers){
    Write-Host $server
}
</code>


crontab: using ${USER}

Question: I am writing some scripts that uses ${USER} to point to subsequent scripts. But when I run it from crontab, it errors out and the files are not found. I understand why.
I intend to share this with my colleagues and each time the colleague has to manually change the first line to his own username. How can I minimize this issue (not have a manual way to change that one line)?
Comment: Does this answer your question? [Why is my crontab not working, and how can I troubleshoot it?](https://serverfault.com/questions/449651/why-is-my-crontab-not-working-and-how-can-i-troubleshoot-it)
Comment: @GeraldSchneider No, it doesn't cover this situation.
Answer: It's a typo. You should use $USER, not ${USER}.
Cron parses these lines itself and does only simple variable substitution; it is not a shell.

crontab: using ${USER}


Trouble Understanding an Example of a Double Category that is Not a 2-Category

Question: From Categories for the Working Mathematician:

By a double category (Ehresmann) is meant a set which (like the set of all natural transformations) is the set of arrows for two different compositions which together satisfy [the interchange law]. A 2-category (short for two-dimensional category) is a double category in which every identity arrow for the first composition is also an identity for the second composition. For example, the category of all commutative squares in $\mathbf{Set}$ is a double category (under the evident horizontal and vertical compositions) but not a 2-category.

Question: Why is the category of all commutative squares a double category but not a 2-category?
It is unclear to me from the author's description precisely what the "category of all commutative squares in $\mathbf{Set}$" is (in particular: what are the horizontal and vertical notions of composition? Isn't it just function composition?).
Answer: An object in this category is a pair of sets and a map between them. Write $(A \to B)$ for example.
Usually a morphism $f$ in a category has only one range $Dom(f)$ and codomain $Cod(f)$ assigned to it. In a double category there are two flavours of each for every morphism. A morphism in this category is a commutative square like this. . . .
$A \ \to \  B$
$\downarrow  \ \ \ \ \ \ \ \ \downarrow$
$C \ \to \  D$
The 'vertical' domain and codomain are $Dom_{|} = (A \to B)$ and $Cod_| = (C \to D)$
The 'horizontal' domain and codomain are $Dom_-=(A \to C)$ and $Cod_- =(B \to D)$
There are two 'vertical' and 'horizontal' notions of composition , call them $\circ_|$ and $\circ_-$. But we can only compose two morphisms using $\circ_|$ for example if the corresponding vertical domains match up. What this means is the bottom row of the first matches the top row of the second.
We compose  vertically by putting the first on top of the second to get a tall rectangle. The corners of the rectangle form a new square. That square is the vertical composition.
Likewise two squares can only be composed horizontally if the right column of the first matches the left column of the second. We compose  horizontally by putting the first left of the second to get a long rectangle. The corners of the rectangle form a new square. That square is the horizontal composition.
It can occur that two morphisms may be composable horizontally but not vertically or vice versa.
So why is this not a $2$-category? Well what exactly is an identity morphism with respect to $\circ_-$? It is a morphism $e$ such that $Dom_-(e) = Cod_-(e)$ and $f \circ_- e = e \circ_- f = f$ for every morphism $f$ where all parts are defined.
By experimenting you can show these morphisms are exactly the squares of the form. . .
$A \ \to \  A$
$\downarrow  \ \ \ \ \ \ \ \ \downarrow$
$C \ \to \  C$
. . . where the horizontal arrows are the identity map and the vertical arrows match. Meanwhile the vertical identity morphisms are of the form. . . .
$A \ \to \  B$
$\downarrow  \ \ \ \ \ \ \ \ \downarrow$
$A \ \to \  B$
. . . where the vertical arrows are the identity map and the horizontal arrows match.
But clearly a square may be of one type but not the other.
Comment: The category of commutative squares has as objects the commutative squares, presumably!
Comment: Under normal circumstances I would presume the same. However the definition given in the question names the category after the set of morphisms: "By a double category is meant a set which is the set of arrows for two different compositions. . . " So the double category of commutative squares should be the double category for which double squares form the arrows, rather than the objects.
Comment: Not to say the class of commutative squares cannot be given a double (triple?) category structure of course!
Answer: As Mariano pointed out, the authors probably meant a category with objects commutative squares. The nlab shows one, where horizontal composition is adjoining two commutitative squares horizontally, and vertical composition is adjoining them vertically. I think this was the original intention.


reset values of not selected fields of dropdown

Question: I have a dropbox that when selected it displays its respective fields
in first image you can see there is A person without an ID so when selected it displays
something like:

if you see I added 12
Now if i change my mind and select the other option (person with ID) one field is displayed like:

I added 9999
That is ok, but now if I change my mind again and return to other selected option the values are still there like:

I would like to clean them... How can I accomplish that?
It does not matter to fill all respective fields again, I want to reset values in that case if select
person without ID, delete the 9999, on the other hand, if i select person with Id, i want to reset the vakue 12
please take a look at my fiddle
some of the jquery code is:
<code>//function available
function validate(id, msg) {
    var obj = $('#' + id);
    if(obj.val() == '0' || obj.val() == ''){
        $("#" + id + "_field_box .form-error").html(msg)
        return true;
    }
    return false;
}

$(function () {
    $('#has_id').show();
    $('#select_person').change(function () {
        $('.persons').hide();
        if ($('#select_person').val() == 'typeA') {
            $("#has_id").html('');
            $("<option/>").val('0').text('--Choose Type A--').appendTo("#has_id");
            $("<option/>").val('person-A-withID').text('person-A-withID').appendTo("#has_id");
            $("<option/>").val('person-A-withoutID').text('person-A-withoutID').appendTo("#has_id");
        }

        if ($('#select_person').val() == 'typeB') {
            $("#has_id").html('');
            $("<option/>").val('0').text('--Choose Type B--').appendTo("#has_id");
            $("<option/>").val('person-B-withID').text('person-B-withID').appendTo("#has_id");
            $("<option/>").val('person-B-withoutID').text('person-B-withoutID').appendTo("#has_id");
        }

    });

    $('#has_id').change(function () {
        $('.persons').hide();
        $('#' + $(this).val()).show();
    });

});

var validation = function(){
            var err = 0;
            err += validate('select_person', "select person.");
            err += validate('has_id', "Select whether it has an ID or not.");

            if(err == 0){
               alert('continue');
            }else{
                alert('error');
            }

        };
</code>
Comment: It seems like it already does what you're saying it should do
Comment: yeah, if ypu play with that you see the value is not reseted, it is stored, so I want to reset the corresponding values of dropdown that is not selected
Comment: You mean like this? http://jsfiddle.net/LEfbX/132/
Answer: Simply make this change:
<code>$('#has_id').change(function () {
    $('.persons input').val('');
    $('.persons').hide();
    $('#' + $(this).val()).show();
});
</code>
New fiddle: http://jsfiddle.net/6m27M/
This simply clears out all the values any time a change is made to the #has_id dropdown.


Difference in means

Question: For a df that looks something like the following
group     signedup
A                  1
B                  1
A                  1
B                  1
B                  0
B                  0
A                  0

I need to  calculate the difference in means between group A and B for the 'signedup' attribute . Not sure if my solution is correct. Any insights will be appreciated!
Some background information:
'group' indicates whether the user is assigned to the control group (A) or the treatment group (B). signedup' indicates whether the user signed up for the premium service or not with a 1 or 0, respectively
from scipy import stats as scs
df=pd.read_csv(filename)
df_A=df.loc[df['group'] == 'A', ['signedup']]
df_B=df.loc[df['group'] == 'B', ['signedup']]
t,p= scs.ttest_ind(df_A,df_B)
if p < 0.05:
  print('Difference in means is statistically significant')

Comment: Welcome to Cross Validated! Is this a statistics question disguised as a coding question? If you just want to know about your Python code, 1) at a glance, it looks right and 2) pure coding questions are off-topic here, so a thorough debug or code review is not for Cross Validated. // For reasons discussed [here](https://stats.stackexchange.com/questions/535683/p-values-from-t-test-and-prop-test-differ-considerably/535685#535685), the t-test is not ideal here. I am a fan of the G-test, though I do not know a canned Python function. The chi-squared test (similar) probably is in scipy.
Comment: Unrelated, is it common to import stats as scs like importing numpy as no and pandas as pd? I have not done that, though most of my statistics work is in R, while I use Python for my data wrangling.
Comment: Hi Dave, I was asking if the use of a T test is correct for difference in means.
Comment: and yes it is totally acceptable to import stats the way I have done
Comment: My linked answer addresses the issue of t-testing binary variables like you have. In summary, you can do better than the t-test.
Answer: Here are three tests that are commonly used to compare binomial proportions, in appropriate circumstances.
Consider fictitious data sampled in R, based on sample sizes $n = 300$ and actual
success rates $p_a = 0.6, p_b = 0.7.$ All three tests detect a
difference with P-values about $0.001.$
set.seed(731)
n = 300
x.a = rbinom(n, 1, .60)
x.b = rbinom(n, 1, .70)

table(x.a)
x.a
  0   1
124 176
table(x.b)
x.b
  0   1
 85 215

Welch t test: Appropriate for large $n.$
t.test(x.a, x.b)

        Welch Two Sample t-test

data:  x.a and x.b
t = -3.3677, df = 593.35, p-value = 0.0008071
alternative hypothesis:
  true difference in means is not equal to 0
 95 percent confidence interval:
  -0.20581319 -0.05418681
sample estimates:
 mean of x mean of y
 0.5866667 0.7166667

A test of binomial proportions using a normal approximation, similar to a chi-squared test on a $2 \times 2$ table. [The continuity correction is slightly conservative and may not be needed for $n$ as large as $300.]$
yes = c(sum(x.a),sum(x.b));  yes
[1] 176 215
prop.test(yes, c(n,n))

        2-sample test for equality of proportions
        with continuity correction

data:  yes out of c(n, n)
X-squared = 10.602, df = 1, p-value = 0.00113
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.20886568 -0.05113432
sample estimates:
   prop 1    prop 2
0.5866667 0.7166667

Fisher's Exact Test, which uses a hypergeometric distribution based
on row and column totals of a $2 \times 2$ table under the null hypothesis
that the two groups have equal success probabilities: [It is especially useful if $n$ is small.]
TBL = cbind(yes, n-yes);  TBL
     yes
[1,] 176 124
[2,] 215  85
fisher.test(TBL)

        Fisher's Exact Test for Count Data

data:  TBL
p-value = 0.001105
alternative hypothesis:
 true odds ratio is not equal to 1
95 percent confidence interval:
 0.3932415 0.7998073
sample estimates:
odds ratio
 0.5616766

A brief simulation in R shows that the Welch t test has power about 99% of detecting a difference
between $p.a = 0.6$ and $p.b = 0.7$ with sample sizes $n=300.$
Similar simulations can find the power of the other two tests for
appropriate sample sizes.
set.seed(2021)
n = 300; p.a = 0.5; p.b = 0.7
pv = replicate(10^5,
               t.test(rbinom(n,1,p.a),rbinom(n,1,p.b))$p.val)
mean(pv <= 0.05)
[1] 0.99898  # approximate power

For $n = 150$ and the same proportions, the power is about 95%.
Note: Python must have equivalent procedures for such tests.

Difference in means


Why do I get "Type does not correspond to an entity on this site" when POSTing to REST api behind an Apache Reverse proxy?

Question: I have the REST api configured to allow POSTing new users to /entity/user. On my local machine, it works just fine. Once I push up to my remote host, it stops working.
The key difference is that on my local machine, my site is running in a docker container bound to port 6050, so all rest calls go to localhost:6050.
On my remote host, I have docker configured behind an Apache 2.4 reverse proxy. So the docker container is still bound to 127.0.0.1:6050, but all requests should go to https://sub.example.tld/.
To summarize, posting a new user to http://localhost:6050/entity/user?_format=hal_json, with the appropriate X-CSRF-Token and Content-Type headers set, works. It returns 200.
Posting to https://sub.example.tld/entity/user?_format=hal_json, with the appropriate X-CSRF-Token and Content-Type headers set, does not. It returns 422 Unprocessable Entity.
{"message":"Type https:\/\/sub.example.tld\/rest\/type\/user\/user?_format=hal_json does not correspond to an entity on this site."}

In the recent log messages, I see:
Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException: Type http://sub.example.tld/rest/type/user/user?_format=hal_json does not correspond to an entity on this site. in Drupal\rest\RequestHandler->deserialize() (line 201 of /var/www/html/web/core/modules/rest/src/RequestHandler.php).

I do manually set the user's "_links" array:
"_links": {
        "type": {
          "href": "https://sub.example.tld/rest/type/user/user?_format=hal_json"
        }
      },

I know that authentication isn't the issue. My code is successfully accessing views that require authentication.
Since I think it might be something to do with these settings, I do have the following set:

$settings['trusted_host_patterns'] = ["$sub\.example\.tld$"]
$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = ["internal network ip","172.18.0.1","127.0.0.1"];

I'm running Drupal 8.7.3.
My docker image is based on php:7.1-apache.
Any ideas what I'm doing wrong?
Comment: after importing new configs, you need to delete the caches, *drush cr* for Drupal 8.
Answer: The solution is to remember set the base url of any _links href values to use http if Drupal expects it, and https if Drupal, instead, expects that.
In my case, I was using https, but the https connection was terminated at the Apache reverse proxy, so Drupal wanted http.
Using a REST extension to test with let me manually change the links array to reflect that, and the user was created just fine.
Also, the "type" href should not have the _format=hal_json on it.


How to resolve hibernate table creation while its says unsuccessful creating table

Question: I have a domain class name DataList
@Entity
@Table(name = "list_data")
public class ListData {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "sys_id")
private String sysId;
@Column(name = "name")
private String name;
@Column(name = "detail")
private String detail;
@Column(name = "values")
private String values;

   //getters and setters
  }

I have some others domain class..
I'm using hibernate 3.6 everything alright.
but somehow Im unsuccessful while creating this table.

2012-02-25 03:31:52,166 ERROR SchemaExport:274 Unsuccessful: create table list_data (id >integer not null auto_increment, detail varchar(255), name varchar(255), sys_id varchar(255), >values varchar(255), primary key (id))
  2012-02-25 03:31:52,167 ERROR SchemaExport:275 You have an error in your SQL syntax; check the >manual that corresponds to your MySQL server version for the right syntax to use near 'values >varchar(255), primary key (id))' at line 1

I know my hibernate configuration is fine, I have some other domain class, they are working just fine.
Answer: I think that you cannot use values as a column name since it is a MySQL keyword (INSERT INTO ... VALUES() ).
Comment: That would be my guess as well. In general when I use hibernate I label columns with f_ and tables with t_ to avoid reserved names issues.


How many Digits are there in $2020^{2020}$

Question: How many digits are there in $2020 ^{2020} $ ?
In solution, I first factorized the given number to be $202^{2020}\times10^{2020}$
This made it sufficient to calculate the total digit number of $202^{2020}$ and then add $2020$ digits (for the zeroes in $10^{2020}$ ) to find the answer
Now I found out all powers of $202$ up to $7th$ power, by hand-multiplication. What I figured out is:
For every $202^{1+3n}$  no. of digits in the answer is $ 3 + 7n $
This way the answer of this question should lead to $6734$ digits where, $202^{2020}$ has  $4714$ digits, and $2020$ more digits for $10^{2020}$
My question is, whether the formula I mentioned in bold letter, is always applicable up to any natural number value of $n$ ?
Comment: Hint:  the number of digits in $N$ is $\lceil \log_{10} N\rceil$  (where $\lceil x\rceil$ denotes the least integer which is not less than $x$).
Comment: An exact answer?  Probably, but nothing leaps to mind.  To do it roughly, I'd approximate with $2^{2020}\times 10^{6060}$ and since $2^{10}\approx 10^3$ we'd then get around $10^{606}\times 10^{6060}=10^{6666}$ which would mean $6665$.  That's not terrible!  the correct answer (barring error) is $6677$.
Comment: @lulu To deal correctly with powers of $10$ e.g. $10$ has two digits you need the floor of the log plus one, rather than the ceiling. The functions are the same except at powers of $10$, so it makes no difference to he answer to the question.
Comment: To your numerical question:  No.  with $n=4$ we have that $202^{13}$ has $30$ digits but $3+7n=31$ and the gap continues to widen for larger $n$.
Comment: @lulu, can we use a method to solve this problem without calculator?
Comment: @MarkBennet  Thanks for the correction!  You are, of course, absolutely correct.
Answer: Let me use $\log x$ for the logarithm in base $10$ of $x$ and $\ln x$ for the natural logarithm.
You can do the computation by hand if you know $\log2=0.301030$ (which I had to memorize in school), $\ln10=2.302586$ (which I was supposed to memorize but never did) and the approximation $\ln(1+x)\approx x-x^2/2$ for $x$ close to $0$.
$$
\log202=\log200+\log\Bigl(1+\frac1{100}\Bigr)\approx2+\log2+\frac{1}{\ln10}\Bigl(\frac{1}{100}-\frac12\frac{1}{100^2}\Bigr).
$$
Answer: Your finding
$$202^{1+3n}\to3+7n\text{ digits}$$
is only approximate.
Actually, using logarithms,
$$\log_{10}202^{1+3n}=(1+3n)\log_{10}202=2.3053513694\cdots+6.9160541083\cdots n.$$
Taking the ceiling, the two formulas give
$$0 \to 3 , 3 \\
1 \to 10 , 10 \\
2 \to 17 , 17 \\
3 \to 24 , 24 \\
4 \to 31 , 30 \\
5 \to 38 , 37 \\
6 \to 45 , 44 \\
7 \to 52 , 51 \\
8 \to 59 , 58 \\
9 \to 66 , 65 \\\cdots$$

The correct answer is
$$\lceil2020\log_{10}2020\rceil=6677.$$


SQL2008R2Std Maximum RAM per instance

Question: In this page : http://msdn.microsoft.com/en-us/library/ms143685%28v=sql.105%29.aspx
It's written that SQL 2008R2 Standard supports 64GB of RAM, but is it per instance?
For SQL2012 (here : http://msdn.microsoft.com/fr-fr/library/cc645993.aspx )  it's written that it's "For a single instance", but not for 2008R2.
This question has already been asked (SQL Server 2008 R2 memory limit per instance or server?) but the answer comes from a test (and not with 64GB), so i'm not sure it will work for me :-)
The goal for me is to get a server with 128GB RAM, with two SQLSERVER2008R2STD, each with 64BG RAM (minus the OS-requiered).
Thanks!
Answer: Yes, it's per instance.
From the Server Memory Options page on TechNet:

Use max server memory to control memory usage. Establish maximum
  settings for each instance, being careful that the total allowance is
  not more than the total physical memory on your machine.

1st bullet under the Running Multiple Instances of SQL Server section toward the bottom.
Comment: Thanks for your answer! Yes I'll be careful and will keep a safety amount of RAM.
Answer: As every instance of SQL Server is a separate process, it's more logical that the limit is per instance.
Coordinating memory usage between different processes is something very complex. What if one process gets greedy and consumes the memory 'pooled' between several processes? What if the other processes don't want to give up memory? You'll easily end up with a race condition, bringing everything to a halt.
Comment: Thanks for your answer. The SQL Server's memory will be strictly regulated by max and min's server memory settings.

SQL2008R2Std Maximum RAM per instance