What is the limit $\lim_ {n\to\infty} \frac {3^n} {n^n}$?

Question: I know intuitively that it should be zero since n^n grows faster than 3^n but I get infinity.
Here is my work.
$\ln(y)=\lim_{n\to\infty} \ln(\frac{3^n}{n^n})$
$\ln(y) = \lim_{n\to\infty} n \ln(\frac{3}{n}) $
$\ln(y) = \lim_{n\to\infty} n [\ln(3) - \ln(n)] $
$\ln(y) = \lim_{n\to\infty}  [\ln(3) - \ln(n)]/n^{-1} $
using L'Hopitals Rule, I have
$\ln(y) = \lim_{n\to\infty} \frac{-1/n}{-n^{-2}} $
$\ln(y) = \lim_{n\to\infty} n = \infty$
$y = e^{\infty} = \infty $
where is my mistake?
Comment: You used Lhopital's rule, but $\ln 3 - \ln n\to -\infty$ and $n^{-1}\to 0$ as $n\to\infty$.
Comment: Not worth more than a comment, but what is your need for complicated theorems like L'Hopital in the first place? (That's an actual question, not a snide remark.) Note that for $n \geq 4$, you have $0 \leq \frac{3^n}{n^n} \leq \left(\frac{3}{4}\right)^n$: the Squeeze theorem is enough.
Comment: Why not simply observe that $(3/n)^n<3/n$ for $n>3$?
Comment: isn' $$\lim_{n\to\infty}3^n = \infty$$ and $$\lim_{n\to\infty}n^n = \infty$$, the use of L'Hopitals Rule valid?
Comment: You're also trying to take $\log(0)$ in your very first line, which I would be wary of.
Comment: @017 After taking the logarithm, you have $\ln(3/n)$ in the numerator and $1/n$ in the denominator. The former goes to $-\infty$, the latter to $0$.
Answer: You wrongly used Lhopital's rule, because $\ln 3 - \ln n\to -\infty$ and $n^{-1}\to 0$ as $n\to\infty$.
Not using L'Hopital's rule,
$$0\le \lim_{n\to\infty} \frac{3^n}{n^n} \le\lim_{n\to\infty}\frac{3^n}{4^{n-1}}=0$$
by squeeze theorem.
Answer: let $y = \left(\frac 3 n\right)^n.$ then $$\ln y = n (\ln(3) - \ln(n))\to -\infty \text{ as } n \to \infty.  $$ that is $\lim_{n \to \infty} y = e^{ln y} = e^{-\infty} = 0. $
Comment: ah!  I see.  So my mistake was in applying L'Hopitals Rule to a determinate form, right?  This would explain why I got the wrong answer.
Answer: Apply the root test to the series $\sum \dfrac {3^n} {n^n}$:
$$
\lim_ {n\to\infty} \left(\frac {3^n} {n^n}\right)^{1/n}
=
\lim_ {n\to\infty}  \frac {3} {n}\
= 0
$$
Therefore, the series converges and so
$$
\lim_ {n\to\infty} \frac {3^n} {n^n} = 0
$$
Comment: Isn't that a bit overkill? ( I mean, most people do consider sequences before introducing series...)
Answer: One with subsequences. Call $u_n = \left(\frac{3}{n}\right)^n$. Then $$\frac{u_{n+1}}{u_n} = 3 \frac{n^n}{{(n+1)}^{n+1}} \le  3 \frac{n^n}{(n+1)n^n} $$
so at least after $n=3$ the sequence is decreasing. It is lower bounded by $0$, so converging, and it suffices to choose a nice subsequence to find the limit. To make things simple, try $n=3k$. Then
$$u_{3k} = k^{-3k}\,.$$
By taking the $\log$, you easily get that $-3k \log k \to -\infty $ as $k \to \infty$, hence the limit of the subsequence is $0$.
Answer: You can rewrite it as
$$
\lim_{n\to\infty} e^{n \ln\left(\frac{3}{n}\right)}
$$
$$
n \ln \left(\frac{3}{n}\right) \to -\infty
$$
So
$$
\lim_{n\to\infty} e^{n \ln \left(\frac{3}{n}\right)} = 0
$$


Does connected components of a group scheme form a group scheme?

Question: Let $G$ be a group scheme locally finite type and smooth over a base scheme $S$, and assume $S$ is normal and integral.
Then does the set of (geometrical) connected components of a group scheme form a group? or even point of a group scheme over $S$?
If $S=Spec k $ where $k$ is a field, then this is true and we have a theory of $\pi_0(G)$ using etale algebras over a field. I wonder what will happen for the generic case.
Comment: If $S$ is spectrum of a field and $G$ is a finite group, the connected components are not group schemes (at least not in a natural way, except the identity component).
Comment: @Mohan Milne has a section "The group of connected components of an algebraic group" at https://www.jmilne.org/math/CourseNotes/iAG200.pdf, and I think that works well over a field.
Comment: I don't think it does. You have a group homomorphism $G\to \pi_0(G)$ and the fiber over $e$ is a normal subgroup. The fiber over other points of $\pi_0(G)$ are not subgroups.
Answer: To make the answer self-consistent, I recall some notions. The direct answer is the bold part.

When $S=\mathrm{Spec} k$ for a field $k$ and $G$ is just an $S$-group scheme, by [SGA3 I$_{\text{new}}$, VI$_{\text{A}}$, 2.6.5], there is a unique subgroup scheme $G^0\subset G$ whose underlying space is the irreducible component of $G$ containing the neutral section.

When $S$ is local Artinian and $G$ is locally of finite type over $S$, then $G^0$ also exists ([SGA3 I$_{\text{new}}$, VI$_{\text{A}}$, 2.3]) as a subgroup scheme. If $G$ is further assumed to be $S$-flat, then the fpqc sheaf quotient $G/G^0$ is an $S$-etale group scheme; if $S$ is further assumed to be an algebraically closed field, then the set $\mathcal{C}$ of connected components is a $G/G^0$-torsor, namely $\mathcal{C}\simeq G/G^0$, so we obtain the desired identification.

However, when $k$ is not separably closed, then by the above case, $\mathcal{C}$ will correspond to the set of $\mathrm{Gal}(k^{\mathrm{sep}}/k)$-orbits of $(G/G^0)(k^{\mathrm{sep}})$. For instance, $\mu_{3,\mathbf{Q}}=\mathbf{Q}[X]/(X^3-1)$ is a finite etale $\mathbf{Q}$-group scheme, but it has only two connected components: the neutral component $c_1$ and the other $c_2$ obtained by gluing $\zeta_3$ and $\zeta_3^{-1}$ together via the Galois action. The point is that there is no group structure on $\{c_1,c_2\}$ compatible with the group structure of $\mu_{3,\mathbf{Q}}$. (You can always endow a finite set with a group structure, but it will make the question meaningless: the compatibility is very important)

The following recollection is not directly relevant to the question, but I write here just for someone's convenience, especially who concerns about the existence of $G^0$.

For a scheme $S$ and an $S$-group scheme $G$, denote by $\underline{G^0}$ the subset of $G$ as the union of $G^0_s$ for all $s\in S$, where $G^0_s$ is the connected component of $G_s$ containing the neutral section. By [SGA3 I$_{\text{new}}$, VI$_{\text{B}}$, 3.4], if $\underline{G^0}\subset G$ is an open subset, then the subfunctor
$$G^0\colon S^\prime/S\mapsto \{u\in G(S^\prime)|u(S^\prime)\subset \underline{G^0}\}$$
is representable by an $S$-subgroup scheme whose underlying space is $\underline{G^0}$.

Indeed, when $G$ is an $S$-flat finitely presented group scheme, then [EGAIV$_3$, 15.6.5] implies that $\underline{G^0}$ is open in $G$. In particular, $G^0$ is an open $S$-group scheme of $G$.

When $S$ is Noetherian of finite Krull dimension and $G$ is commutative smooth of finite type over $S$, then $G^0$ exists as an $S$-smooth finite type group and $G/G^0$ is an etale group algebraic space, see the paper of Giuseppe Ancona, Annette Huber and Simon Pepin Lehalleur, On the relative motive of a commutative group scheme.
Answer: I think that you should first ask whether $G^\circ$ even makes sense for a group over a relative base. What is it supposed to mean? Perhaps we should assume that $S$ is connected in which case we have that $G^\circ$ should be the connected component of $G$ containing the image of $e:S\to G$? This is not a very well-behaved notion--it doesn't even respect base change. For example, if you take $G=\mu_p$ over $\mathrm{Spec}(\mathbb{Z}_p)$ then then $G=G^\circ$, $G_{\mathbb{F}_p}=G_{\mathbb{F}_p}^\circ$ but $G_{\mathbb{Q}_p}^\circ$ is trivial!


Maximum Likelihood Estimation IID Samples

Question: According to these notes from Penn State on MLE and notes from Stanford CS229 on logistic regression, training data is assumed to be IID.
The Penn State notes say "...which implies by definition that the X are independent." and the Stanford notes state that "Assuming that the m training examples were generated independently, we can then write down the likelihood of the parameters as..." However, according to this Cross Validated answer the observations do not need to be IID.
Isn't X a random variable and in order to take the product for the joint probability, don't the observations need to be independent? Also is there a difference in saying that the labels (y's) are independent versus the observations (x's) are independent?
Could someone explain? What am I misunderstanding?
Comment: Look at the examples of the joint likelihood functions for dependent data in the answers to the linked CV post. They're not the product of identical likelihood functions for individual observations.
Comment: They may be referring to autocorrelation, where $y_i$ values could be dependent on previous values, like $y_{i-1}$, such that $y_i = f(y_{i-1}) + \alpha + \beta x_i + \epsilon$.
Answer: You are misunderstanding the documents linked to. They probably makes an iid assumption for their examples, so that they exclude other cases, they do not make an universal assumption. To use likelihood methods you need to be able to write down a joint density function (or joint probability mass function), and that is simple in the independent case. But it can be done in many cases for models with non-independent observations.
Some examples, time series model with serial correlation, an example Beginner learning resources : Pdf and likelihood function for non-Gaussian time series model. Spatial models, I do not find really good examples on site, but here is one:  Maximum likelihood fitting of truncated, mixed, two population systems  or mixed models, for instance:  http://www2.stat.duke.edu/~sayan/Sta613/2017/lec/LMM.pdf


Groups aggregate functions using rxcpp?

Question: I'm trying to get a gist of RxCpp, the native cpp implementation of reactive extensions from Microsoft, to see if I could use it in a project, but I'm having trouble wrapping my head around the concepts.
If I had an observable templated with the following structure:
struct Person
{
    std::string name;
    std::string sex;
    int age;
}

How would I create another observable which contained, grouped by sex, the count of people, min age, max age and average age of all the events?
I've looked at examples, and I can't see how to get more than one aggregate at a time.
Answer: Use group_by to partition by gender and then combine the min/max/average reducers to produce the desired output per gender.

Updated with count, output and additional comments

This works for me:
#include "rxcpp/rx.hpp"
using namespace rxcpp;
using namespace rxcpp::sources;
using namespace rxcpp::subjects;
using namespace rxcpp::util;

using namespace std;

struct Person
{
    string name;
    string gender;
    int age;
};

int main()
{
    subject<Person> person$;

    // group ages by gender
    auto agebygender$ = person$.
        get_observable().
        group_by(
            [](Person& p) { return p.gender;},
            [](Person& p) { return p.age;});

    // combine min max and average reductions.
    auto result$ = agebygender$.
        map([](grouped_observable<string, int> gp$){
            // the function passed to combine_latest
            // will be called once all the source streams
            // (count, min, max, average) have produced a
            // value. in this case, all the streams are reducers
            // that produce only one value when gp$ completes.
            // thus the function is only called once per gender
            // with the final value of each stat.
            return gp$.
                count().
                combine_latest(
                    [=](int count, int min, int max, double average){
                        return make_tuple(gp$.get_key(), count, min, max, average);
                    },
                    gp$.min(),
                    gp$.max(),
                    gp$.map([](int age) -> double { return age;}).average());
        }).
        // this map() returns observable<observable<tuple<string, int, int, int, double>>>
        // the merge() returns observable<tuple<string, int, int, int, double>>
        // a grouped observable is 'hot' if it is not subscribed to immiediatly (in this case by merge)
        // then the values sent to it are lost.
        merge();

    // display results
    result$.
        subscribe(apply_to([](string gender, int count, int min, int max, double avg){
            cout << gender << ": count = " << count << ", range = [" << min << "-" << max << "], avg = " << avg << endl;
        }));

    //provide input data
    observable<>::from(
        Person{"Tom", "Male", 32},
        Person{"Tim", "Male", 12},
        Person{"Stel", "Other", 42},
        Person{"Flor", "Female", 24},
        Person{"Fran", "Female", 97}).
        subscribe(person$.get_subscriber());

    return 0;
}

with the resulting output
Female: count = 2, range = [24-97], avg = 60.5
Male: count = 2, range = [12-32], avg = 22
Other: count = 1, range = [42-42], avg = 42

Comment: the [=] capture and mutable were artifacts of a previous example, I have removed them and added more comments. The majority of the concepts needed to use rxcpp are common to the other Rx implementations. This is great since the other resources can be reused. This page is how I exposed my self to these shared concepts: http://reactivex.io/learnrx/. I am happy to discuss rxcpp specific questions. other resources are: docs - http://reactive-extensions.github.io/RxCpp/ and chat - https://gitter.im/Reactive-Extensions/RxCpp
Comment: Thanks, that looks great. A couple of questions:
Why do you have to use [=] and mutable in the first argument to group_by?
Can you add some additional comments in the section that combines min max and average? I don't quite understand what's going on there.
Finally, obviously you know rxxcpp very well since you worked on the library, any tips on learning how to use it effectively?

Groups aggregate functions using rxcpp?


SMS from a website

Question: I've been looking into how to code a website (through php or javascript) to send an SMS message to some friends' and my phones. The idea is that we'd like to get daily reminders with a message saying "posture" at some point during the day while we're awake to remind us to sit up straight, not slouch, etc.
So far, I've only found answers that seem to show how to send an email to the website owner (http://php.about.com/od/advancedphp/ss/mail.htm) using forms or that use other API's and/or services.
I know that each phone has its own unique "email address" provided through the phone company so that would be an easy matter to figure out. The problem I'm having is how to send an email from the site itself. Is there a way to do this through php or javascript, and automatically so I don't have to manually send the message every day? Thanks!
Answer: "I know that each phone has its own unique "email address" provided through the phone company so that would be an easy matter to figure out." NO.
"The problem I'm having is how to send an email from the site itself. Is there a way to do this through php or javascript, and automatically so I don't have to manually send the message every day?"
Are you just talking about automating a message on a daily basis? Check out http://www.phpjobscheduler.co.uk/ - really all i did was google php and scheduled interval.  I'm certainly not going to say how to have php email somebody, as there's got to be 1,000 other posts on the topic.
if you want to actually setup SMS via a real cell network, there are paid API's + servers that tie into the network that hook you up. Search for them. There's a ton, and each one provides slightly different services at different rates. Look em up.

SMS from a website


dynamic javascript using jquery

Question:
some text

I want the q= to be dynamic using the text in the previous paragraph. I can get the text into a variable
var str = $("#text").text();

but am struggling to output this dynamically.

EDIT:
It's much simpler than I thought, figured out the solution from Darin's answer:

Testing text to speech

Just needed to know how to append a variable. Thanks
Comment: what the heck do you want that `onclick` to do?
Comment: I'm creating a text to speech application for disabled students where a request (i.e. the contents of div#text) is sent to google translate using onclick using this method http://goo.gl/Iwqa0 - Thanks for all the responses so far!
Comment: Its funny there are 4 answers already but it can only be assumed that we know what OP wants as his question is not clear enough.  Are we really helping him by spamming him with our assumptions? Or should we possibly wait for him to clarify his question and better explain what he is trying to do?
Comment: @JohnHartsock it seems more fun this way ^_^
Answer: Start of what I think you want to do:
$('img').click(function(){
    var str = $("#text").text();
    alert('http://url.com?q=' + str);
});

Or maayyyyybe:
$('img').click(function(){
    var str = $("#text").text();
    window.location = 'http://url.com?q=' + encodeURIComponent(str);
});

Or even:
$('img').click(function(){
    var str = $("#text").text();
    this.src = 'http://url.com?q=' + encodeURIComponent(str);
});

Fiddle: http://jsfiddle.net/maniator/UrDRX/
(works in HTML5 browsers, edit the color code)
And on and on....
Answer: Lemme shoot in the dark:

or if you want to assign this src dynamically:

and then:
$(function() {
    $('#foo').click(function() {
        window.location.href = 'http://url.com?q=' + encodeURIComponent($("#text").text());
    });
});

Answer: Separation of concerns.  In this case you want to keep behavior (javascript) separate from the content (html) and style (css). - http://en.wikipedia.org/wiki/Separation_of_concerns
So... onclick="x();" is not preferred.  Rather:
$(document).ready(function(
 $("#buttonId").click(function() {
    var val = $("#text").text();
    var url = 'http://url.com?q=' + encodeURIComponent(val);

    alert(url); // or window.location or whatever you want to accomplish
 });
));

Answer: Perhaps, if you want to use the entire text-content of the paragraph:
var str = encodeURIComponent($('#text').text());

$('#linkId').attr('href','http://url.com?q=' + str);

JS Fiddle demo.

dynamic javascript using jquery


I can't access to data in JSON.server from react-native with use of Fetch's method

Question: I have created a simple JSON.server project with the following code:
npm install JSON-server -g
I run this server with the following code:
JSON-server --watch db.json -p 3001 -d 2000
when I run this server in my browser, it works but when I fetch data from this server in react native, this doesn't work.
my react-native's codes for fetch data from JSON.server:
return fetch(baseUrl + "data")
  .then(
    response => {
      if (response.ok) {
        return response;
      } else {
        //error
      }
    },
    error => {
      var errmess = new Error(error.message);
      throw errmess;
    }
  )
  .then(response => response.json())
  .then(dishes => dispatch(fetchData(data)))
  .catch(error => dispatch(dataFailed(error.message)));

fetchData method:
export const fetchData = data => ({
  data: data
});

update 1:
this is baseUrl:
export const baseUrl = "http://192.168.1.8:3001/";

please help me what is the problem.
I have tried this question but my problem has not fixed.
Comment: What's the error you're getting?
Comment: Shouldn't your endpoint be `fetch(baseUrl + "db.json")` since you are watching that file instead of `dishes`? Is there a `GET /dishes` route available on your server in `db.json`? Might help if you can share error message and routes defined in `db.json`.
Comment: You also set a custom port `3001` instead of default 3000. This needs to be added in `baseUrl` Ex: `http://localhost:3001/`
Comment: I have updated my question. please look at it again.
Comment: I haven't any error. I don't receive any data from JSON.serever. @Clarity
Answer: You would use localtunnel to get a server working on both devices:
Install localtunnel globally on your dev machine
yarn global add localtunnel

Then you use json-server to setup and run a mock server. The following command sets up the mock server on localhost and port 8000
json-server --port 8000 ./db.json --watch

Next to expose the mock server to the web use localtunnel
lt --port 8000 --subdomain application-mock-server

The above command will return a URL accessible across Internet of the form
 https://application-mock-server.localtunnel.me.

Then you plug this URL inside your React Native code base and will be accessible from the application running inside Expo on the mobile.
* Check full article here.
Answer: my issue was  because of my ip4 address.
as I told before, I have tried this question but my problem has not fixed.
I did  find a way to fetch data from the server.
For those who are facing similar problem.
Steps:
1) Go https://ngrok.com/ and create account
2) Login
3) Go to setup & installation, follow 1, 2 steps.
4)Place the ngrok.exe in a folder of your choosing. Make sure the folder is in your PATH environment variable.
5) Follow step 3 of setup & installation.
6) Open your command prompt and type ngrok http (eg: 3005) and enter. You will get a ngrok url (eg: forwarding http://977ab183.ngrok.io)
7) Make this url (eg: http://977ab183.ngrok.io/) your app baseUrl
8) Open another command prompt pointing to your app directory and run your json server: json-server --watch db.json -p 3005 -d 2000


Probability density function for Riemann-zeta zeros

Question: Curious about the expected probability distribution for the spacing between Riemann zeta zeros, of the form $s_n=\sigma+it_n$, where $\sigma=0.5$ and $t_n$ is the imaginary part of the $n$-th zero.
The mean spacing between zeros decreases slowly as the height $t_n$ goes up, somewhat confounding the issue, but taking a narrow slice of 100,000 zeros starting at the billionth zero ($t_{1000000000}$) should make that variation negligible. Here's a histogram of the spacings in that region:

The longer upper tail precludes a normal distribution. The red curve is a best fit gamma distribution, which doesn't quite do it either. The mean spacing at the beginning of the range covered is $0.351087$ compared to $0.351073$ at the end, so that variation is small.
What is the closest distribution to model the spacing?
Comment: The zeros conjectured to have the same distribution as the eigenvalues of a random Hermitian matrix, see https://en.wikipedia.org/wiki/Montgomery%27s_pair_correlation_conjecture. That implies a lot about the spacing between zeros (in particular the fact that the distribution peaks away from zero is related to the tendency for eigenvalues to repel one another). I don't know enough about the topic to post an answer, but this and this (http://empslocal.ex.ac.uk/people/staff/mrwatkin/zeta/random.htm) should be a good starting point to learn more.
Answer: I've done five million spacings starting from billionth (1e9) zero, and find that from the distribution I had in use Nakagami had highest log-likelihood.
However, when studying spacings $\Gamma(i+n)-\Gamma(i)$ with n=2,3,4...etc. Johnson distribution is superior. This is because skewness and kurtosis of the distributions change and Johnson (SB or SU) is very flexible distribution.
Answer: Just looking at other distributions, the three-parameter Burr type XII distribution fits pretty well. Here's the result as above around $t_{1e9}$:

The Burr type XII pdf is:
$f(x|\alpha,c,k)={{kc\over \alpha}({x\over \alpha})^{c-1}\over{(1+({x\over a})^c)^{k+1}}}$
For the above fit,
$\alpha = 0.837947, c=2.76292$ and $k=8.68889 $
However, the best fit parameters change at other heights, e.g. at $t_{10e9}$:

$\alpha = 0.776292, c=2.73405$ and $k=9.38153 $
Note the mean has shifted down slightly. The mean is given by:
$\mu = \alpha k\Gamma(k-1/c)\Gamma(1+1/c)/\Gamma(k+1)$
The Burr type XII distribution is used most often to study mortality, survival, failure rates and the like. I guess the interval between a zeta zero and the next could be thought of as its lifespan.
Comment: Try setting c to exp(1) and fitting the other parameters


$G=(I_{k}|A)$ is a generator matrix of $\mathcal{C}$ iff $H=(-A^{T}|I_{n-k})$ is a control matrix of $\mathcal{C}$

Question: I am trying to prove that, ''given a $\mathcal{C}$ $[n,k,d]$-linear code, $G=(I_{k}|A)$ is a generator matrix of $\mathcal{C}$ iff $H=(-A^{T}|I_{n-k})$ is a control matrix of $\mathcal{C}$''.
Firstly, I have supposed that $G=(I_{k}|A)$ is a generator matrix of $\mathcal{C}$; we name the columns of $A$ as $a_{1},a_{2},..,a_{n-k}$; if $x=(x_{1},...,x_{k})\in\mathbb{F}_{q}^{k}$, I can codify this into a word of the code by taking the generator matrix and multiplying it this way: $xG=(x_{1},...,x_{k},x\cdot a_{1},...,x\cdot a_{n-k})\in\mathcal{C}$, where $\cdot$ is the dot product of two vectors. I also know the following result:

$H$ is a control matrix of $\mathcal{C}$ if the following holds: $x\in\mathcal{C}$ $\Leftrightarrow$ $Hx^{T}=(0,...,0)^{T}$

So, If I show $H(x_{1},...,x_{k},x\cdot a_{1},...,x\cdot a_{n-k})^{T}=(0,...,0)^{T}$, I would have show that $x\in\mathcal{C}$ $\Rightarrow$ $Hx^{T}=(0,...,0)^{T}$; this is very easy to show taking on account how $H$ is constructed.
For the other direction, I would have to show that $Hx^{T}=(0,..,0)^{T}$ has, as a system of equations, as solutions all the words of the code... Here I get stucked.
Secondly, I would have to prove that, assuming $H=(-A^{T}|I_{n-k})$ is a control matrix of $\mathcal{C}$, $G=(I_{k}|A)$ is a generator matrix of $\mathcal{C}$. For this I suppose I would have to solve the system $Hx^{T}=(0,...,0)^{T}$ (which, by hipothesis I know has as solutions the words of the code), and then show that each of that words can be generated by $G$, i.e., that, given a code word, I can find a vector in $\mathbb{F}_{q}^{k}$ such that the product of that vector by $G$ is the code word firstly given. Nevertheless I am not sure this is the best approach...
Any help, guidance, or anything will be very helpful. Thanks!
Answer: You're almost there. What you wish to show is that the codes defined by $G$ and $H$ are the same, i.e.,
$$ \{ c \in \mathbb{F}_q^n: c=uG, u \in \mathbb{F}_q^k \} = \{ c \in \mathbb{F}_q^n: cH^\mathrm{T}=0\}. $$
Denote the left set by $\mathcal{G}$ and the right one by $\mathcal{H}$.
You have already proven that $\mathcal{G} \subseteq \mathcal{H}$. Since $c\in\mathcal{G}$, it follows that $c = uG$ for some $u\in \mathbb{F}_q^k$ and thus $cH^\mathrm{T}= uGH^\mathrm{T}= u(A-A)= 0$ by definition of the matrices $G$ and $H$.
For the other direction $\mathcal{H} \subseteq \mathcal{G}$, we split the codeword into two parts, $c=(d,e)$, $d \in \mathbb{F}_q^k$, $e \in \mathbb{F}_q^{n-k}$. Observe that with this notation, $cH^\mathrm{T}=0 \Leftrightarrow -dA+e=0 \Leftrightarrow dA = e$. Thus, if we set $u=d$, we obtain
$$ uG = (d,dA) = (d,e), $$
which proves that we can find a vector $u$ that generates $c$ and thus $\mathcal{H} \subseteq \mathcal{G}$.
Comment: Ok! Got it, thanks a lot!


How to filter substring from string in python?

Question: I try to fitler some text from a string of text.
So I have this string of text:
It was the best of\ntimes, it was the worst\nof times, it was the age\nof wisdom, it was the\nage of foolishness...\n\x0c'

and then I just want this part extracted from it:
It was the best of

So I try it like this:
import io
from PIL import Image
import pytesseract
from wand.image import Image as wi

pdfFile = wi(
    filename="C:\\Users\\engel\\Documents\\python\\docs\\text.png", resolution=300)
image = pdfFile.convert('jpeg')

imageBlobs = []

for img in image.sequence:
    imgPage = wi(image=img)
    imageBlobs.append(imgPage.make_blob('jpeg'))

extract = []
flag = False
string_to_check = ['It was the best of']

for imgBlob in imageBlobs:
    image = Image.open(io.BytesIO(imgBlob))
    text = pytesseract.image_to_string(image, lang='eng')
    extract.append(text)
for char in string_to_check:
    if char in extract:
        print("Char \"" + char + "\" detected!")

But the output is empty.
So my question is: how can I improve this?
Thank you
oke, this is the complete code fragment:
import io
from PIL import Image
import pytesseract
from wand.image import Image as wi
import re

pdfFile = wi(
    filename="C:\\Users\\engel\\Documents\\python\\docs\\fixedPDF.pdf", resolution=300)
image = pdfFile.convert('jpeg')

imageBlobs = []

for img in image.sequence:
    imgPage = wi(image=img)
    imageBlobs.append(imgPage.make_blob('jpeg'))

extract = []
flag = False
string_to_check = ['']
substring = 'Peen Waspeen 14x1lkg'

for imgBlob in imageBlobs:
    image = Image.open(io.BytesIO(imgBlob))
    text = pytesseract.image_to_string(image, lang='eng')
    extract.append(text)
    allSubstring = re.findall(r'{}'.format(substring),text)
    print(allSubstring[0])

But then I also get this error:
Peen Waspeen 14x1lkg
Traceback (most recent call last):
  File "c:\Users\engel\Documents\python\code\textFromImages.py", line 29, in <module>
    print(allSubstring[0])
IndexError: list index out of range

Comment: Not sure if I understand. Whenever you want to find a substring in a string, use regex. Then, if you want to specifically find this substring, use `re.findall(r'It was the best of',s)`if you want to find all substrings between `\n`then `re.split(r'\n',s)`. Does this answer your question or am I missing something?
Comment: But do you have example? So what I mean is. You have this string: It was the best of\ntimes, it was the worst\nof times, it was the age\nof wisdom, it was the\nage of foolishness...\n\x0c' and then I just want to print the substring:  It was the best of out of the string
Answer: Use regex for substring filtering.
If you want to find a particular substring within a string, you can simply use this:
import re

s = 'It was the best of\ntimes, it was the worst\nof times, it was the age\nof wisdom, it was the\nage of foolishness...\n\x0c'
substring = 'It was the best of'

allSubstrings = re.findall(r'{}'.format(substring), s)
print(allSubstrings[0])

If you want to find the first substring of substrings that are separated by \n, then you can split your string with:
import re

s = 'It was the best of\ntimes, it was the worst\nof times, it was the age\nof wisdom, it was the\nage of foolishness...\n\x0c'

allSubstrings = re.split(r'\n', s)
print(allSubstrings[0])

Both answers print the substring you are looking for, output:
It was the best of


My horizontalscrollview is stretching my imagebuttons when I use scale:fitxy

Question: My xml works just fine on the android studios nexus 7 and nexus 10 emulators and the xml looks fine running on my nexus 4. But when I run it on a 7 inch tablet it stretches my image in the y direction only (in landscape activity) and doesn't keep the aspect ratio. I've tried 2 different 7 inch tablets with the same result.I think I've tried changing layoutwidth and layoutheight to just about every possible combination. I also have the same scaling issue if I try it with a imageview instead of an imagebutton. I googled and googled and tried everything but haven't found a solution that works for me. Please help me...
Here is my xml:
<code><?xml version="1.0" encoding="utf-8"?>

<HorizontalScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/horizontalScrollView"
android:scrollbars="none"
android:fillViewport="true">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:measureWithLargestChild="false">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/imageButton2"
        android:src="@drawable/mainmenu1"
        android:background="@android:color/transparent"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        android:onClick="goToLab101" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/imageButton3"
        android:src="@drawable/mainmenu2"
        android:background="@android:color/transparent"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"
        android:onClick="goToPeriodicTable" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/imageButton4"
        android:src="@drawable/mainmenu3"
        android:adjustViewBounds="true"
        android:background="@android:color/transparent"
        android:scaleType="fitXY"
        android:onClick="goToLab102"/>

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/imageButton5"
        android:src="@drawable/fountainselector"
        android:background="@android:color/transparent"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"/>

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/imageButton6"
        android:src="@drawable/mainmenu5comingsoon"
        android:background="@android:color/transparent"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        android:onClick="goToLab103"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/imageButton7"
        android:src="@drawable/mainmenu6"
        android:background="@android:color/transparent"
        android:adjustViewBounds="true"
        android:scaleType="fitXY" />
</LinearLayout>
</HorizontalScrollView>
</code>
Comment: try flipping these values android:layout_width="wrap_content"
        android:layout_height="match_parent" to android:layout_width="match_parent"
        android:layout_height="wrap_content"
Answer: Add your same image drawables in drawable-large-xhdpi for 7 inch tablet support
Comment: Yes, I had tried adding larger image files to the xhdpi folder but this didn't 'seem' to fix my problem. My issue was my source image wasn't big enough to keep the aspect ratio when scaled to fit XY. The reason that adding a bigger image didn't fix my issue at first was that I needed to 'clean' my project for it to start using the bigger image when running on my device. Unfortunately I didn't clean my project until after I spent hours trying to fix the issue.


How to evaluate 2 dimensional Mellin-Barnes integral?

Question: Recently I need to evaluate an integral looks like
$I=\int _0^1 dx \int_0^1 dy \frac{1}{(1-x)^{\frac{1}{2}}\left(y(1-xy)t+1\right)}$
where $1>t>0$.
I don't know how to do it, and I'm told to try Mellin-Barnes representation, which lead me to
$I=\frac{1}{(2\pi i)}\int _0^1 dx \int_0^1 dy\int _{-i\infty}^{i\infty}dz_1(1-x)^{-\frac{1}{2}} \Gamma (1+z_1)\Gamma (-z_1)\frac{(-xy^2t)^{z_1}}{(1+yt)^{1+z_1}}\\
=\frac{1}{(2\pi i)^2}\int _0^1 dx \int_0^1 dy\int _{-i\infty}^{i\infty}dz_1\int _{-i\infty}^{i\infty}dz_2 (1-x)^{-\frac{1}{2}}\\
\times \Gamma (1+z_1+z_2)\Gamma (-z_1)\Gamma (-z_2)(-xy^2t)^{z_1}(yt)^{z_2}\\
=\frac{\Gamma (\frac{1}{2})}{(2\pi i)^2}\int _0^1 dx \int_0^1 dy\int _{-i\infty}^{i\infty}dz_1\int _{-i\infty}^{i\infty}dz_2 (-1)^{z_1}t^{z_1+z_2}\\ \times \Gamma (1+z_1+z_2)\Gamma (-z_1)\Gamma (-z_2)\frac{\Gamma (2z_1+z_2+1)}{\Gamma (2z_1+z_2+2)}\frac{\Gamma (z_1+1)}{\Gamma (z_1+\frac{3}{2})}$
I think I can close the contour to the right and thus have (I'm not sure)
$I=\Gamma (\frac{1}{2})\sum _{n_1=0}^{\infty}\sum _{n_2=0}^{\infty}\frac{(-1)^{n_1}(-t)^{n_1+n_2}}{n_1!n_2!}\Gamma (1+n_1+n_2)\frac{\Gamma (2n_1+n_2+1)}{\Gamma (2n_1+n_2+2)}\frac{\Gamma (n_1+1)}{\Gamma (n_1+\frac{3}{2})}$
However, it seems that, because of $\frac{\Gamma (1+n_1+n_2)}{n_1!n_2!}$, the sum dose not converge. I also tried to throw it to Mathematica, but failed to obtain a result.
I hope my understanding of the Mellin-Barnes representation is correct. I need help.
By the way, if there is another way to evaluate the original integral, it is also interesting!
Answer: After a long time this is not answered. However I'm able to deal with this using another method.
First substitude $x\to 1-x$, the integral is
$$\int _0^1dx\int _0^1dy\frac{1}{\sqrt{x}(1+ty-ty^2+txy^2)}$$
Then $x\to x^2$ it is
$$2\int _0^1dx\int _0^1dy\frac{1}{(1+ty-ty^2+tx^2y^2)}$$
Then $x\to \frac{x}{y}$ it is
$$2\int _0^ydx\int _0^1dy\frac{1}{y(1+ty-ty^2+tx^2)}$$
Then $x\to x+y$ it is
$$2\int _{-y}^0dx\int _0^1dy\frac{1}{y(1+ty+tx^2+2xyt)}$$
Then $x\to -x$
$$-2\int _0^ydx\int _0^1dy\frac{1}{y(1+ty+tx^2-2xyt)}$$
Now, change the order of the integral, it is
$$-2\int _0^1dx\int _x^1dy\frac{1}{y(1+ty+tx^2-2xyt)}$$
Now I am able to throw it to Mathematica, and the result can be obtained.


how to make translucent buttons over a image in react-native using native-base?

Question: I was trying to make buttons as shown in the screenshot.but can't figure out how can i make them look translucent.
import React, { Component } from 'react';
import {Image} from 'react-native';
import {Button, Content} from 'native-base';

export default class AppBody extends Component {
    render() {
        return (
            <Content>

                <Image source={require('./img/bg3.jpg')} style={{ width: 360, height: 509 }}>

                </Image>
            </Content>
        );
    }
};

Comment: try this: https://stackoverflow.com/questions/31336569/how-to-set-background-color-of-view-transparent
Comment: Possible duplicate of [How to set background color of view transparent in React Native](https://stackoverflow.com/questions/31336569/how-to-set-background-color-of-view-transparent-in-react-native)
Answer: Use rgba value for the backgroundColoras follows:
backgroundColor: 'rgba(52, 52, 52, 0.8)'

This sets it to a grey color with 80% opacity, which is derived from the opacity decimal, 0.8. This value can be anything from 0.0 to 1.0.
Copied from this answer.


Date conversion to Postgresql

Question: I need in PostgreSQL.
TO_CHAR(SYSDATE+(TO_NUMBER(puttim)/86400),'MM/DD/YYYY HH24:MI:SS');

I've tried the below code but that's not giving desired output. Value must be with the current_timestamp with extra 2 seconds.
to_char(current_timestamp + (puttim::integer) * INTERVAL '2 second', 'MM/DD/YYYY HH:MM:SS');

Comment: So what does this code do? And why are you storing numbers in a varchar column?
Comment: The difference between `00:00:00` and `00:00:02` is two **seconds** not two milliseconds. But it's still unclear to me what that oracle code is supposed to do. What unit does `settime` represent? Seconds? Milliseconds. And if it's number then why need the cast?
Answer: From here Data formatting

to_number ( text, text ) → numeric

Converts string to numeric according to the given format. to_number('12,454.8-', '99G999D9S') → -12454.8.

You need to provide a number format. See the rest of the link for what those are.
If settime is actually all number characters you can skip the formatting and do:
select '1234'::integer, '1.25'::numeric;
 int4 | numeric
------+---------
 1234 |    1.25

So something like:
settime::integer/86400
Comment: Why do you need my email? If this answer helps will you up vote  and/or accept it?
Comment: Your best option is to join the [pgsql-general](https://www.postgresql.org/list/) mailing list. The link has instructions on how to sign up.
Comment: That information is at the [Data formatting](https://www.postgresql.org/docs/14/functions-formatting.html) link in Table 9.26. Template Patterns for Date/Time Formatting
Answer: That should be simple with date arithmetic:
to_char(clock_timestamp() + settime * INTERVAL '1 second', 'MM/DD/YYYY HH24:MI:SS')

Date conversion to Postgresql


Firebase public Task  addOnCompleteListener() method

Question: I am confused with the differences between
public Task  addOnCompleteListener(OnCompleteListener listener)
and
public Task  addOnCompleteListener(Executor executor, OnCompleteListener listener)
in Android.
Attached here with the image of explanation from Firebase documentation.
From the explanation inside the documentation, the only difference between this two method is highlighted in the image. So what is the shared thread pool?
Thank you.
Answer: The difference is, in addOnCompleteListener(OnCompleteListener listener) the listener will be called on main thread and in addOnCompleteListener(Executor executor, OnCompleteListener listener), the Executor determines the thread that will be used to invoke the listener.
For more info, take a look at this great blog post.


Java string producing error when converting to an int

Question: I am trying to use Integer.parseInt() to convert a string representing a phonenumber into an int I can use.
This is the error I'm getting:
Enter a 10-digit telephone number with optional space or dash after the first and the second block of three digits >
5558759142
Processing encrypted number "5558759142"
Exception in thread "main" java.lang.NumberFormatException: For input string: "5558759142"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at java.lang.Integer.parseInt(Integer.java:615)
    at TelephoneNumberValidator.main(TelephoneNumberValidator.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 1

This is my code:
import java.util.*;
import java.lang.Integer;

public class TelephoneNumberValidator {
    public static void main(String[] args) {
        final String VALID_PHONE_PATTERN = "[0-9]{3}[-| ]?[0-9]{3}[-| ]?[0-9]{4}";
        final int NUMBERS_FOLLOWING_AREA_CODE = 7;
        final int DECRYPTED_AREA_CODE = 212;
        Scanner scanKeyboard = new Scanner(System.in);
        String userInput;

        do {
            System.out.println( "Enter a 10-digit telephone number with optional space or dash after the first and the second block of three digits >" );
            userInput = scanKeyboard.nextLine();
            //check to see if the phone number is correct
            if ( !userInput.matches(VALID_PHONE_PATTERN) )
            {
                System.out.println("The given input \" " + userInput + " \" is not valid");
            }
        }while ( !userInput.matches(VALID_PHONE_PATTERN) );

        //extract int from string
        String phoneJustNumbers = userInput;
        phoneJustNumbers = phoneJustNumbers.replaceAll("-",""); // replaces hyphens
        phoneJustNumbers = phoneJustNumbers.replaceAll(" ", "");

        System.out.println( "Processing encrypted number \"" + phoneJustNumbers + "\"" );
        //check the first 3 digits (aka area code) to see if it matches 212
        int areaCode =  Integer.parseInt(phoneJustNumbers);//gets area code
        int placeholderForAreaCode = 111; //set 111 so that each number in area code can be accounted for
        int placeholderForEntirePhoneNum = 1111111111; //set each digit to 1 so we can shift later
        for (int j = 0; j <= 9; j++)
        {
            if ( (areaCode + ( placeholderForAreaCode * j ) == DECRYPTED_AREA_CODE ) ) // we are shifting each digit by one
                                                                                // to see if it matches the decrypted area code
            {
                System.out.println("The telephone number is \"" + ( Integer.parseInt(phoneJustNumbers) * placeholderForEntirePhoneNum * j )
                        + "\" with a shift value of " + j);
            }
            else
            {
                System.out.println("The telephone number \"" + userInput + "\" cannot be decrypted area code." );
            }
        }

    }
}

So when I try to just substitute a hardcoded string it works using Integer.parseInt(). This leads me to believe the way I am generating cleaning up my string somehow stops this from working.
I am new to java so I don't know why that would be or what I have done wrong.
Answer: Out of range. The largest number you can fit into int simple does not fit that 5 billion value your number represents.
Try long instead.
Or, better: use a specific class to represent phone numbers, for example by using an array only containing the digits of that number,but also keeping the complete initial string you got from the user for example.
Thing is : the fact that phone numbers contain numbers doesn't imply that a phone number should be stored as real number!
Comment: Yes this was the issue. Thank you very much!
Comment: Then just go forward and accept the answer you consider being helpful for you.
Answer: The largest value int can be is 2,147,483,647. (See Integer.MAX_VALUE.) Your example phone number is much larger than that. Try using Long.parseLong() instead, as the largest value for a long is 9,223,372,036,854,775,807.
Comment: Yes this was the issue. Thank you very much!
Answer: The input is exceeding the maximum that an Integer can accommodate (store). Change the datatype to long to get over this.
Seems too much of Integer Operations - maybe create a Telephone class, have the prefix etc., as separate fields/attributes and then act on them. Maybe usage of String would be better unless you need to do some mathematical operations,  converting is not advisable


display message on page after validation

Question: I have following entry in my html file. basically the use of this entry is to show a message on page when user will hover the mouse on input field. now i want to show the same message, so i decided to put the same validation in javascript. then I am not able to display the message box please help.
.field:hover .hint {
    position: absolute;
    display: block;
    margin: -30px 0 0 455px;
    color: #000000;
    padding: 7px 10px;
    background: #FFFC17;

    -moz-border-radius: 7px;
    -webkit-border-radius: 7px;
    border-radius: 7px;
    }

    <bean:message key="addEmail"/>

<bean:message key="addEmailMsg"/>

we can see the entry of div tag. and hint class. please help me
basically I am java programmer and have not implemented too much javascript and css. Thanks
Comment: It's likely there is a bug in your javascript code. You should post the relevant sections here as well.
Answer: instead of css, you can make js function and put it in mouseover event
function show_hint(){
var hint = document.getElementById('hint');
hint.style.display = "block";
}

and make hint like

<bean:message key="addEmailMsg"/>

and make event

or just use jquery with making 'hint' hidden
html

<bean:message key="addEmailMsg"/>

js
 jQuery(document).ready(function($) {
        $(".field").hover(
          function () {
            $('.hint').show();

        }); });


Right type of exception for access of array index which doesn't exist in memory?

Question: I'm new to C++ exceptions, and i can't find the right type of exception for a bad memory access attempt.
Let's assume i allocated memory for 10 integers with this code:
int* intArray = new int[10];

for(int i = 0;i < 10;i++){
    intArray[i] = i+1;
}

And while trying to read it i made some logical mistake which will cause the program to access a memory i didn't allocate, for example:
for(int i = 0;i < 15;i++){
    cout << intArray[i] << endl;
}

What is the right type of exception to catch?
Thanks!
Comment: If you use a vector instead of an array, you can get the exact same effect but have it throw an exception as you describe. Do you want me to post an answer that describes how to do that, or does it have to be an array? Note that in modern C++, you'd be generally advised to avoid using arrays and new directly.
Comment: @NirFriedman about the first part i've solved it, but i do want to know about the second part, what do you mean by saying "using arrays and new directly" ?
Comment: Unless you are writing your own container, or in a handful of other cases, you shouldn't generally use new or arrays. Instead of an array, you should use a std::vector.
Answer: This code
int* intArray = new int[10];
...
for(int i = 0;i < 15;i++){
    cout << intArray[i] << endl;
}

does not throw an exception. This will lead to undefined behavior. Most likely, you just get the output of random data. When you create an array with new operator you get a sequence of elements with contiguous addresses. C++ does not have mechanisms to check the length of such arrays in runtime.
Comment: More precisely that should be undefined behaviour (UB). May be random data or a segmentation fault


Why is this conductor holding a toothpick?

Question: I was watching a performance of Ravel's Bolero, conducted by Gergiev:

And I noticed that instead of a  baton he was holding a toothpick:

Why is he holding it instead of a baton? Is there anything implied towards the orchestra?
Comment: The first time I saw that recording, I thought that he would switch over to larger and larger batons as the Bolero continued xD
Answer: See here.

The rumour is that Gergiev started using a toothpick to conduct because his movements whilst conducting were so violent that he was in the habit of losing his grip on the baton and it would go flying into the audience or the orchestra.
Comment: The story of a conductor loosing grip like that is probably from Daniel Turk of the Hallé Orchestra in the 1800s.
Answer: According to someone claiming to be an assistant conductor for Gergiev one year, "I'd guess that he prefers to have nothing or nearly nothing in his hands but wants something there to hold onto and give some focus to the shape of his right hand."
Whether or not Gergiev lost grip of batons in his early career is something I couldn't verify in a brief search, but it's believable.  There are several stories told of other conductors losing batons, or injuring themselves with batons, at SlippedDisc which includes an answer to the question "Didn't Solti once stab himself in the head with his baton while conducting Figaro?"   (Ouch!)
Comment: Slightly related:  Notice how Klaus Tennstedt's entire podium came crashing down (during Siegfried's Funeral March, no less) at 5:52.  But, he didn't lose his baton! :-D https://youtu.be/Us3NFFJhFPg?t=5m45s
Comment: Somewhat related: in 1687, [Jean-Baptiste Lully](https://en.wikipedia.org/wiki/Jean-Baptiste_Lully) died of gangrene after stabbing himself in the foot with his conducting baton, which of course was *dangerously* longer back then.
Comment: Also: I read not too long ago that Gustav Mahler misplaced (or forgot to bring) his baton, so he conducted with a spoon.  Can't find the specific link at the moment, but I believe it was during rehearsals for his 8th Symphony (Sept. 1910).
Comment: @StephanKolassa It was in fact a *staff*, not a baton, i.e. it was *designed* to be tapped on the floor. Stabbing your own foot with a baton would be quite an accident!
Comment: @KilianFoth in French, a staff of the sort one might bang on the ground is called a *bâton.*


Use powershell to build VPC's

Question: Our developers use VPC's to develop systems. When a developer joins a team he needs a VPC for that project. The developers have also a tendency to "break" the VPC.
Building a VPC and installing the required software is time consuming.
We were wondering if we could use Power Shell to do the following:

Install Windows
Run windows update
Install SQL Server
Install SharePoint Services
Install Visual Studio

Thanks
Shiraz
Comment: Perhaps a broader question is "how to automate deployment of developer virtual machines?" or something - as the technology used should be of little concern? ^^
Answer: VMware vCenter Lab Manager is a product that gives the ability to any (authorized) user to 'order' one or more virtual machines of his choice. In your situation the developer will order a 'default development vpc' and he will get the preconfigured vm with sql server, sharepoint etc.
Comment: +1 not only mentioning a good solution, but adding in the self-serving part for IT operations striving for more than a basic operational level (where basic in my opinion is automating stuff and mostly being proactive, but not delegating control).
Answer: As mke points out VMware's vCenter Lab Manager is the benchmark but it isn't cheap (~$2k per CPU on the ESX Hosts in the cluster that runs it) and you need to have vSphere cluster capacity for the VM's too, again not cheap if you don't already have it in your budget. If you have an environment where provisioning any significant number of developer VM's is a regular task though it is worth the cost IMO.
For an entry level solution you can prepare templates\clones with all of the components pre-installed, nicely patched and up to date too. Deploying from such a template will typically be an order of magnitude faster (if not more) and more reliable than scripting a full install followed by app installations, especially of the type you require. In a VMware vCenter environment this is pretty easy as vCenter handles all of the customization\sysprep parts for you but in any virtual environment you should be able to sysprep a baseline VM and save a copy. Provisioning your new VM is then simply a case of making a copy and importing the new VM instance, both are trivial to do for both VMware Infrastructure VM's (Using the PowerCLI) and Hyper-V VM's (using the PowerShell Management Library for Hyper-V) using Powershell but may be harder for other Hypervisors. One possible fly in the ointment is the way SQL Server's identity is handled - you may need to script some additional steps to clean up the cloned SQL instance as outlined in this SQLmag article.
As far as developers breaking test systems is concerned, that should be expected and ideally it should be something that they have no worries about. You want them to be able to break lab systems as much as they need to after all. VM Snapshots are one way to deal with this especially if you have an environment where you can give the Developers the rights to directly manage snapshots of their VM's.

Use powershell to build VPC's


Changing Twig template of form items through the theme

Question: I have a block, which renders out a form using code that looks like this:
{{ attribute(form.facets, 'filter_' ~ filter.name) }}

I'd like to amend the markup and CSS classes for the various elements that are output, including fieldset, input, label etc. I appreciate that I can override the template files for fieldset for example, by creating a fieldset.html.twig file in my theme, but I don't want to change the markup for every fieldset element. I only want to apply my custom templates to form elements which are rendered out from a specific block.
I know that I can use a 'suggestion' (mytheme_theme_suggestions_alter) to alter the template for any element, but I can't see a way of determining if an 'input' for example, is an input within my block, or some other block on the site. Does anyone know how I'd identify this?
Comment: Did you already come across https://drupal.stackexchange.com/a/211992/57183 and http://kevinquillen.com/drupal/2017/01/28/adding-twig-template-suggestions-for-form-elements?
Comment: I'd seen the second link, which I'd successfully used on another part of the site, but I hadn't seen that first link. I'm going to have a play with that now and see if I can get it working.
Answer: You can use drupal_static() together with the following two hooks in your module or your theme to add template suggestions for input elements based on the block ID where the input element is used in (same would work with fieldsets or any other form/render element):
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_block(&$variables) {

  $bid = &drupal_static('block_id', TRUE);
  $bid = $variables['elements']['#id'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME/MYMODULE_theme_suggestions_input_alter(array &$suggestions, array $variables) {

  $bid = &drupal_static('block_id', FALSE);

  if ($bid) {
    $suggestions[] = 'input__block__' . $bid;
    $suggestions[] = $variables['theme_hook_original'] . '__block__' . $bid;
  };
}

For example the search form textfield:

For example the password textfield:

Comment: Not sure about this @laymannx. It does do the trick, but using the global context to transfer information between functions is risky, think of a call to `drupal_static_reset()`. Additionally, calls to `drupal_static`, should be 'namespaced' by using the `__FUNCTION__` magic constant to use the function's name inside of which `drupal_static` is called, i.e. `drupal_static(__FUNCTION__)`, in that way making them specific to the function that needs them multiple times in the same request.
Comment: @StefanosPetrakis - Thanks a lot for your comment. I definitely have to dive deeper into `drupal_static` I learned of only yesterday. I will look how core or other contrib modules use it. Do you know of any other alternative to pass variables between hooks?
Comment: This didn't work for me unfortunately. Instead of `MYTHEME/MYMODULE_preprocess_block`, I was using `MYTHEME/MYMODULE_preprocess_form` and then trying to catch the `bid` in say `MYTHEME/MYMODULE_theme_suggestions_input_alter`. The problem was that the suggestion appears to run before the preprocess.
Comment: @laymannx - No worries, I think another option would be using session variables, but I would still go the way suggested in my first comment in the OP
Comment: @JamesThomson – `bid` means block ID. You probably won't get that in the form.
Comment: I changed it to grab the form ID. I could see the static var being populated in the preprocess, but only after the suggestion functions had already executed.
Comment: @JamesThomson – Indeed, I tried it myself. It doesn't seem to work for all forms at the same time on the page. For some I got the suggestion. For some I didn't got them. I guess then the solution in the comments under your question should be the way to go. Maybe you get it running and then can provide an answer yourself.


OSMDroid world map not showing up

Question: I'm following the OSMDroid tutorial present in here:
But I'm running in to some trouble, I've done everything as is in the tutorial, however, when I run the App, it should show the World Map, however I only see a grid and the zoom buttons.
Here's my code for the Layout and MainActivity:
Layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <org.osmdroid.views.MapView android:id="@+id/map"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

    </LinearLayout>

    <org.osmdroid.views.MapView
        android:id="@+id/mapview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tilesource="Mapnik" />

</android.support.design.widget.CoordinatorLayout>

Activity:
import android.content.Context;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;

public class MainActivity extends AppCompatActivity{
    MapView map = null;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Context ctx = getApplicationContext();
        Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));

        map = (MapView) findViewById(R.id.map);
        map.setTileSource(TileSourceFactory.MAPNIK);
        map.setBuiltInZoomControls(true);
        map.setMultiTouchControls(true);
        IMapController mapController = map.getController();
        mapController.setZoom(9.5);
        GeoPoint startPoint = new GeoPoint(48.8583, 2.2944);
        mapController.setCenter(startPoint);
    }

    public void onResume(){
        super.onResume();
        map.onResume();
    }

    public void onPause(){
        super.onPause();
        map.onPause();
    }
}

Shouldn't the world map show up upon running?
Thanks in advance!
Comment: Did you add the required permissions to your AndroidManifest.xml, i.e. at least `INTERNET` and `ACCESS_NETWORK_STATE`? If this doesn't help then check your log messages.
Answer: just change your .xml to below snippet
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <org.osmdroid.views.MapView android:id="@+id/map"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

    </LinearLayout>

OSMDroid world map not showing up


How to fix this expression

Question: I am trying to print multiple * based on rating value. In Javascript console Array(10).join('*') produces 10 stars. When using it in Angularjs view, this expression is not evaluated. Am I missing something?

{{skill.name}} - {{Array(skill.rating).join('*')}}

App.js
app.controller('SkillsController', function($scope){
    $scope.skills = [
        { name: 'Ruby', rating: 5 },
        { name: 'Java', rating: 10}
    ];
})

Answer: Array is not part of the $scope. You can do the following in your controller.
app.controller('SkillsController', function($scope){
    $scope.skills = [
        { name: 'Ruby', rating: 5 },
        { name: 'Java', rating: 10}
    ];

    $scope.Array = Array;
});

I would however do this transformation in a filter or directive.
app.filter('stars', function() {
  return function(input) {
    return Array(input).join('*');
  };
});

And then
{{skill.rating | stars}}

Comment: I agree. Make a directive for this :)
Comment: Brilliant. Is it possible to limit the scope of filter to `SkillsController`?
Comment: Also, I noticed that the number of stars returned is always `N-1`
Answer: From my point of view, the best way to create a method in $scope of controller to get rating transformed as you wish. From this method call another method placed in service. Thus, you'll separate business logic from presentation logic and from view.
So, View

{{skill.name}} - {{ getRating(skill) }}

Controller
app.controller('SkillsController', function($scope, myService){
    $scope.skills = [
        { name: 'Ruby', rating: 5 },
        { name: 'Java', rating: 10}
    ];
    $scope.getRating = function (skill) {
        return myService.transformRatings(skill.rating);
    }
});

Service:
app.service('myService', function(){
    return {
        transformRatings: function (stars) {
            return Array(stars).join('*');
        }
    }
});

How to fix this expression


Como eu trato uma tabela em html como se fosse um formulário

Question: Estou desenvolvendo em django uma aplicação para pesquisa processual e ela seria feita com base em planilhas excel. Eu achei na internet tutoriais para selecionar as linhas da tabela, entretanto, não sei como desenvolver um botão com uma função que envie as linhas selecionadas como listas em Python para realizar a busca.
o HTML esta bem simples e a função javascript copiei de um tutorial da internet:

var tabela = document.getElementById("minhaTabela");
var linhas = tabela.getElementsByTagName("tr");

for(var i = 0; i < linhas.length; i++){
    var linha = linhas[i];
  linha.addEventListener("click", function(){

        selLinha(this, true);
    });
}

function selLinha(linha, multiplos){
    if(!multiplos){
    var linhas = linha.parentElement.getElementsByTagName("tr");
    for(var i = 0; i < linhas.length; i++){
      var linha_ = linhas[i];
      linha_.classList.remove("selecionado");
    }
  }
  linha.classList.toggle("selecionado");
}

var btnVisualizar = document.getElementById("visualizarDados");

btnVisualizar.addEventListener("click", function(){
    var selecionados = tabela.getElementsByClassName("selecionado");
  //Verificar se eestá selecionado
  if(selecionados.length < 1){
    alert("Selecione pelo menos uma linha");
    return false;
  }

  var dados = "";

  for(var i = 0; i < selecionados.length; i++){
    var selecionado = selecionados[i];
    selecionado = selecionado.getElementsByTagName("td");
    dados += "CNPJ: " + selecionado[0].innerHTML + " - RAZÃO SOCIAL: " + selecionado[1].innerHTML + " - NOME FANTASIA: " + selecionado[2].innerHTML + "\n";
  }

  alert(dados);
});
{% load static %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>
    <link  rel="stylesheet" href="{% static 'css/banco.css' %}">

<button id="visualizarDados">Visualizar Dados</button>

      CNPJ
      RazaoSocial
      NomeFantasia

      0
      00000000000
      xxxxxxxxxxxxx S/A
      xxxxxxxxxxx

      1
      111111111111
      yyyyyyyyyyyy S/A
      yyyyyyyyyyyyyy

Só que ao invés de enviar o alerta na tela, gostaria de receber essas como se os itens selecionados na tabela fossem um formulário. Não sei se isso é possível, porém não entendo praticamente nada de Javascript e não consegui achar esse tipo de informação na internet.
Answer: Bom, se alguém um dia precisar fazer isso o mesmo que fiz, vou deixar minha solução aqui. Resolvi através de uma gambiarra em que alterei o valor do botão atribuindo a variável dados que tinha no javascript.
Para isso, primeiro atribui um name e um value ao botão e o inseri dentro de um form:
<form action="{% url 'banco_de_dados' %}" method="post" class="form" name="form" id="formElem">

<button formmethod="post" name="botao" type="submit" value="" id="visualizarDados">Visualizar Dados</button>

</form>

Depois, no documento js, inseri no final, abaixo de alert(dados) o seguinte comando:
document.form.botao.value = dados

Então, quando clicava no botão ele mandava como valor as informações das linhas selecionadas.
No views no django eu acessei as informações através do seguinte comando:
def banco_de_dados(request):
    if request.method == 'POST':
        location4 = str(request.POST.get('botao'))
...

Ai depois foi só tratar os dados.
Repito, não sei se essa é a melhor solução, entretanto, foi  a que consegui encontrar e que é funcional, espero que ela  possa ser útil para alguém.


Overwrite previous values with last one given some group

Question: I have transposed and populated a data frame which now looks like this:

Now I am trying to overwrite all of the values in columns Signal1 and Signal 2 in upward direction by grouping them by ID and Date simultaneously. All of the previous rows should be populated by the last value for a given group. The output should look like this:

I tried to approach the problem with dplyr but not sure how to handle it:
df %>% group_by(ID, Date) %>% mutate (...)
Have to perform this operation on many more columns (Signal1 - Signal 30) so hopefully an universal solution is available.
Comment: Please provide your example data with using `dput` on your data and copying the resulting text/code into your question, don't use images to show the data
Comment: maybe this works? `df_new <- df %>%
  group_by(ID, Date) %>%
  arrange(Date) %>%
  mutate(across(starts_with("Signal"), last()))`
Comment: @starja  what is the significant of the `last()` can u explain pls?
Comment: @linkonabe I've made a mistake there, it should only be `last`. `last` returns the last value for every column (taking the grouping variable into account), because @Pavel Kaloferov wants to replace all values in a group/Signal column with the last value
Answer: This should do it -
df %>%
  group_by(ID, Date) %>%
  mutate(
    Signal1 = last(Signal1),
    Signal2 = last(Signal2)
  ) %>%
  ungroup()

EDIT: Didn't see the last part of the question. @starja 's comment is right on the money; to apply to many columns use -
df %>%
  group_by(ID, Date) %>%
  mutate(across(starts_with("Signal"), last)) %>%
  ungroup()


Central Limit Theorem & Sample Mean

Question: This is a question which was given to me in an exam, and I'm confused about the approach taken in the Answer Key. The question is summarised as follows:

A bank has 500 customers
The total annual loan repayments made by an individual is a RV with mean 750, and standard deviation 900
What is the probability that the average total annual repayments across all 500 customers is greater than 755?

Using CLT, the population distribution can be expressed as $N(750,1620)$ because
$ \frac {(900)(900)}{500} = 1620$
My Attempt:
$ P(Z>755) = 1 - \phi(\frac {755-750}{\sqrt(1620)}) = 1 - \phi(0.124) $ = 0.45
Correct Answer:
$ P(Z>755) = 1 - \phi(\frac {755-750}{\sqrt(1620)(500)}) = 1 - \phi(2.76) $ = 0.0029
The only difference is in the denominator, where my professor has once again used $\sigma \sqrt n$, where I only used it when applying the CLT to arrive at a population distribution.
I'm assuming my professor is correct of course, so I'm looking for an explanation of what exactly he is doing here, and why it's not alright to simply use $ \frac {X - \mu}{\sigma}$ directly after applying the CLT.
Thanks in advance for answering what I'm sure is a very basic question!
Comment: Your answer is correct (i.e. the correct answer is about 0.45). However, conventionally, $\phi$ is the standard normal *density*; the cdf is usually denoted $\Phi$.
Answer: Your solution is the correct one because sample mean has the deviation $\sigma/\sqrt{n}$. Also, when we substitute $1620=\frac{900^2}{500}$, your professor doesn't seem to be using $n$ in its solution.
Answer: At an intuitive level, if the standard deviation is 500, then assuming a normal distribution, 66% of the time the loan repayments will be within 900 of the mean. So a loan repayment of 5 above the mean is such a tiny fraction of 900 that it's unlikely that the probability would be so low. One can verify this by drawing out the curve and the probabilities within 1, 2 and 3 standard deviations. Running a quick Monte Carlo simulation in Python verifies this.
On an empirical level, loan repayments are not independent and not normally distributed (look at the financial crash in 2007), so this question implies a fundamentally flawed grasp of many topics in STEM and history.

Central Limit Theorem & Sample Mean


Problem with drupal $queue->DrupalQueue::get and $queue->createItem

Question: I am updating approx 10000 nodes using hook_cron_queue_info and hook_cron(), it execute only for 25 nodes.
Is there any problem?
<code>function my_module_cron_queue_info() {
  $queues['my_module_batch'] = array(
    'worker callback' => '_my_module_process_queue',
    'skip on cron' => FALSE,
  );
  return $queues;
}

function my_module_cron() {
  $contents = lode_update_nodes(); // get node list for updation 10000 nodes.
  $queue = DrupalQueue::get('my_module_batch');
  foreach ($contents as $p_file) {
    $process_data = array(
    // set values for process
    );
    $queue->createItem($process_data);
  }
}

function _my_module_process_queue($arr) {
    // code for updation
    watchdog('update node', 'Custom msg');
}
</code>
Comment: You could also use the batch API, then you can call it from the admin, or use it in cron :)
Comment: Using a queue is the correct thing to do, since cron task are not attended tasks. The batch API requires interaction with a user who starts the action from their browser, which is not the case of cron tasks.
Answer: You have to add the 'time' key in de function modulename_cron_queue_info() because the default call time for the queues are 15 seconds. In order to update 100000 nodes you need to asign more time, so you have to try adding time until all 100000 nodes are updated:
<code>$queues['my_module_batch'] = array(
  'worker callback' => '_my_module_process_queue',
  'skip on cron' => FALSE,
  'time' => 60,
);
</code>


Parsing date with Joda API

Question: I have a string which contains a date "25 December 1985". How to parse it using Joda API?
DateTime dt = new DateTime("25 December 1985");
System.out.println(dt.getDayOfWeek());

I need to get a day of week.
Answer: Try this:
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd MMMM YYYY").withLocale(Locale.ENGLISH);
DateTime dt = dtf.parseDateTime("25 December 1985");
System.out.println(dt.getDayOfWeek());

Comment: Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "25 December 1985" is malformed at "December 1985"
Comment: What is your version of Joda lib?
Answer: With reference to http://joda-time.sourceforge.net/userguide.html
getDayOfWeek()
int iDoW = dt.getDayOfWeek();

where iDoW can take the values (from class DateTimeConstants)
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
public static final int SATURDAY = 6;
public static final int SUNDAY = 7;

or dayOfWeek()
DateTime.Property pDoW = dt.dayOfWeek();
String strST = pDoW.getAsShortText(); // returns "Mon", "Tue", etc.
String strT = pDoW.getAsText(); // returns "Monday", "Tuesday", etc.

Comment: Ah I see, you never said an exception was being thrown.
Comment: Ok. But how to parse a string "25 December 1985? My example don't work. It throws an exeption.

Parsing date with Joda API


Struggling on what to write more for acceptance tests of user stories, use cases as well

Question: I am not exactly clear on what an acceptance test is, is it basically information about the feature?
Answer: Ask the Product Owner "How are you going to test that this is good enough to deploy?" Everything they tell you is part of your battery of acceptance tests.
Answer: A User Story will typically have a number of Acceptance Criteria.  They are typically written in an "As a [Role] I want [Feature] so that [Benefit]".  Writing them in this way conveys good contextual information to the development team (what they need to do, why they need to do it, and who the user is).
An Acceptance test will verify one of the acceptance criteria on a User Story.  Your Product Owner will write the Acceptance criteria, and ideally collaborate with you as much as possible to get them running technically in Spec Flow, Fitnesse, Cucumber etc...


Validation not working with saveMany

Question: Validations are not working with saveMany for all values.its only working for first value. I am using translate behavior.
My code:
public function admin_add() {

    if ($this->request->is('post')) {
        $this->FaqCategory->create();
        $this->request->data['FaqCategory']['name'] = Inflector::slug($this->request->data['FaqCategory']['name'], $replacement = '-');
        if ($this->FaqCategory->saveMany($this->request->data)) {
            $this->Session->setFlash('The faq category has been saved', 'default', array('class' => 'success'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The faq category could not be saved. Please, try again.'));
        }
    }
    $languages = $this->Language->getlangs();
    $this->set('langs', $languages);
}

Comment: Is there any error?If yes then please post it here.and can you put $this->request->data dump
Comment: use $this->set( $this->request->data)
Answer: Try this: $this->FaqCategory->saveMany($this->request->data, array('validate' => true));

Validation not working with saveMany


Ponteiros na faculdade

Question: Estou estudando ponteiros e esse é um código usado como exemplo que esta no material dado pela faculdade. Fui replicar esse código na minha maquina e a saída é diferente da apresentada no material.
Código:
#include <stdio.h>

int main()
{
    int x=5, y=7, teste=21, aux=17;
    int *px, *py;

    px = &y;
    py = &x;

    printf("py - px = %d\n",py-px);
    printf("px = %u, *px=%d, &px = %d\n",px, *px, &px);
    printf("py = %u, *py=%d, &py = %d\n",py, *py, &py);
    px++;
    printf("px = %u, px=%d, &px = %d\n",px, *px, &px);

    py = px+3;
    printf("py = %u, *py=%d, &py = %d\n",py, *py, &py);
    printf("py - px = %d\n",py - px);

    return 0;
}

Logo abaixo esta a saída do programa na minha maquina:
py - px = -1

px = 3782591132, *px=7, &px = -512376152
py = 3782591128, *py=5, &py = -512376144
px = 3782591136, *px=21, &px = -512376152
py = 3782591148, *py=32767, &py = -512376144
py - px = 3

Também utilizo uma IDE Online de C para estudar e a saída do programa é a mesma que esta no material da faculdade.
Saída no IDE Online:
py - px = 1
px = 2271354488, *px=7, &px = -2023612824
py = 2271354492, *py=5, &py = -2023612832
px = 2271354492, *px=5, &px = -2023612824
py = 2271354504, *py=593585370, &py = -2023612832
py - px = 3

De acordo com o material, o ponteiro px aponta para a variável x e após o incremento ela deveria apontar para a variável y.
No entanto na minha máquina, esta apontando para a variável teste. E na linha de subtração entre os ponteiros px e py o resulta seria 1 e não -1.
Não sei o que pode estar de errado.
Estou usando Ubuntu 16.4.5 com gcc 5.4 e gcc 7.1 ambos com mesma saída.
E a IDE Online é RED HAT 7.1.1-3 com gcc 7.1.1.
Comment: Você não tem garantia que `x` e `y` estão consecutivos. O compilador é livre para por a ordem desejada
Answer: No caso apresentado o programa realmente apresentará saídas diferentes em cada máquina, e às vezes a cada execução, pois o valor armazenado em um ponteiro é um endereço de memória. O problema é que por não ser um array, pode ser que x e y não sejam posições contíguas na memória então incrementar x não necessariamente vai parar em y. (Lembrando que na aritmética de ponteiros a soma e a subtração levam para frente a para trás nas posições de memória)
Para exemplificar o que estou dizendo veja a alteração que fiz no seu código:
#include <stdio.h>

int main(){

    int array[] = {5, 7, 21, 17, 50};
    int *px, *py;

    px = array;
    py = px+1;

    printf("py - px = %d\n", py - px);
    printf("px = %u, *px=%d, &px = %d\n",px, *px, &px);
    printf("py = %u, *py=%d, &py = %d\n",py, *py, &py);
    px++;
    printf("px = %u, px=%d, &px = %d\n",px, *px, &px);

    py = px+3;
    printf("py = %u, *py=%d, &py = %d\n",py, *py, &py);
    printf("py - px = %d\n",py - px);

    return 0;
}

Obs.: Tive que colocar mais uma posição no array pois py+3 acessava uma variável fora do array.
A saída apresentada é a seguinte:
py - px = 1 // 1 espaço de diferença
px = 2865090736, *px=5, &px = -1429876568
py = 2865090740, *py=7, &py = -1429876576
px = 2865090740, px=7, &px = -1429876568
py = 2865090752, *py=50, &py = -1429876576
py - px = 3

Perceba agora as posições na memória:
 x ->  0. 2865090736 // 2865090736 + 4*0
 y ->  1. 2865090740 // 2865090736 + 4*1
       2. 2865090744 // 2865090736 + 4*2
       3. 2865090748 // 2865090736 + 4*3
y+3->  4. 2865090752 // 2865090736 + 4*4

4 bytes é o espaço que um int ocupa.

Ponteiros na faculdade


how to create two or more view with in a single view

Question: I want to create a view which outputs as page . Within that view ,i need to create two or more views they will react based on the arguments to their parent view
Comment: What do you mean by "the value to their parent view"?
Are you referring to exposed filters? - If so you can try adding attachment displays - which can inherit the user input from the parent view.
Comment: Sorry @rooby I mean to say arguments
Comment: If you add an attachment display it has an option "Inherit contextual filters". Set that to "Yes" (which is the default) and it will inherit the arguments from the parent view. It is more limited than a block though in terms of where you can place it.
Answer: What you need is a views attachment to the main parent view. Fist you create a new Views Display, say a block. then on the parent view, attach that view to it. Now turn on inherit contextual filters so you can pass the arguments over to the other view. If you want finer control with the output and fields you can try: http://drupal.org/project/views_php
Answer: Have you tried Views Field View?

This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.
Comment: Ya i tried that module it's working for simple case with one contextual filter. I have to use more than two filter. What i do


Preprocessed var not being passed to twig template

Question: I created a custom theme called wdocs as a sub theme of d8w3css. I made a template to override the menu template for the user account menu, calling it menu--account.html.twig. For my theme, I added the function wdocs_preprocess_menu__account() to my wdocs.theme file, and introduced a new variable with $variables['tollfree_number'] = '555-1212'; So far so good; in phpStorm I can set a breakpoint there are do see it is getting set in $variables. In my twig, I have some text, followed by {{ tollfree_number }}. The text gets displayed, but not the variable.
The problem is the twig calls a macro; I can access the var outside of the macro, but not within it. Googling suggested I pass context when calling the macro, so I changed the call to
{{ menus.menu_links(items, attributes, 0, menu_name, _context) }}

I also tried "context" (no underscore). And also tried dereferencing it with {{ _context['tollfree_number'] }}, but nothing seems to help. Where am I going wrong?
Comment: You would need to change the macro definition as well. Or simply put the variable in an item below $variables['items'] and then display it: {{ item.foo }}
Answer: You're correct in thinking that trying to access your var from within the macro is the issue. See Twig's macro documentation.

But as with PHP functions, macros don't have access to the current template variables.

You can pass your variable into the macro.
{{ menus.menu_links(items, attributes, 0, menu_name, tollfree_number) }}

Then you have two options, you can update the macro definition to add an extra parameter for your custom var.
{% macro menu_links(items, attributes, 0, menu_name, toll_free) %}
  {# etc.. #}
  {{ toll_free }}
{% endmacro %}

Or you can use the special varargs variable without updating the macro definition.

If extra positional arguments are passed to a macro, they end up in the special varargs variable as a list of values.

Pass the var to the macro the same way, then access it like:
{% macro menu_links(items, attributes, 0, menu_name) %}
  {# varargs[0] has the first extra arg, varargs[1] has the second, etc #}
  {{ varargs[0] }}
{% endmacro %}

Using the special _context and varargs vars:
{{ menus.menu_links(items, attributes, 0, menu_name, _context) }}

{% macro menu_links(items, attributes, 0, menu_name) %}
  {{ varargs[0].tollfree_number }}
{% endmacro %}


Coin flipping example

Question: I have a bag of 10 coins; 1 of them has heads on both sides, while the rest are normal (have heads on one side and tails on the other). Each face of a coin is equally probable when tossed.  You choose 1 of the coins from the bag at random and then flip it 100 times observing heads every time.  What is the probability that you chose a normal coin?
The probability that we take a normal coin is 9/10 and in 100 turns, it may be (9/10)^100, but I am not sure if this is correct.
Comment: This question is [routine bookwork](http://stats.stackexchange.com/tags/self-study/info) (please read the link carefully). As such it should carry the `self-study` tag (please edit your question to add the tag), and it should follow the guidelines at the link (please edit your question to be in accord with the guidelines).
Comment: Hello Challis! Well I don't know from where to start! Updated.
Comment: Is it i) you draw a coin, toss, put the coin back and repeat for another 99 times, OR ii) you draw a coin, toss it 100 times? Also, having a head and a tail does not mean it's a fair coin. Does the question specify anything else?
Comment: Yes, having tail and head is fair coin. And it's II. @Penguin_Knight
Answer: You can also look at it from the Bayes rule perspective:
you are looking for the probability of the coin being normal, given the result of 100 heads - P(normal|result)
Now, according to said rule:
$$
P(normal|result) = \frac{P(result|normal)*P(normal)}{P(result)}
$$
and, expanding the denominator:
$$
P(result) = P(result|bad coin) * P(bad coin) + P(result|normal) * P(normal)
$$
Finally, plugging in the known values:
$$
P(result|bad coin) = 1
$$
$$
P(result|normal) = \frac{1}{2^{100}}
$$
$$
P(bad coin) = 1 - P(normal) = \frac{1}{10}
$$
And you get:
$$
P(normal|result) = \frac{9}{9+2^{100}} \approx 0
$$
Answer: Label the coins 1 to 10, and let coin 10 be the one with two heads.  Say that we chose coin 1.  For the experiment of flipping it 100 times and recording which sides land up, we get $2^{100}$ equally likely outcomes (since the coin is fair), one of which has $100$ heads landing up.  The same is true for coins 2 to 9.  For coin 10, there are also $2^{100}$ equally-likely outcomes, but all of them have $100$ heads landing up.  Thus, the experiment "choose one of the ten coins, flip it 100 times, and record which sides land up" has $10\times 2^{100}$ equally likely outcomes.  Of these, $(9\times 1)+(1\times 2^{100})$ have 100 heads landing up.  Of these, $1\times 2^{100}$ are for coin 10.  Now, the probability that (you chose coin 10) given that (100 heads landed up) is just (the probability that you chose coin 10 and 100 heads landed up) divided by (the probability that 100 heads landed up).

Coin flipping example


How to increase available disk space in thinly provisioned VM?

Question: I created a thinly provisioned CentOS VM on an ESXi instance. To use nice numbers, let's say I configured a max disk space of 500 GB. After installing the OS and booting, when I open File Manager and navigate to computer, it shows that ~20 GB are used and ~30 GB are left (50 GB total). So far so good - I expect the size to grow as that gap closes.
But I need to install software that requires 40 GB of free space. When I run the installer, it sees that only 30 GB are available and exits. This raises several questions for me:

Why did VMware decide to initialize the VM with 50 GB when the max was 500 GB?
Could I have customized the initial size to allow enough space to install the software?
How can I force the disk to grow to make room for the software I'm trying to install?
Comment: In ESXi you can use either Thin Provisioned or Thick Provisioned drives. I assume, you have created 50GB Thick Provisioned drive, which CentOS VM can see. You should be able to extend it in the Edit VM menu. Max Size shown in this menu is maximum available size on your Datastore. Might be helpful:
https://www.vmwareblog.org/vmware-esxi-disk-provision-work-difference-one-better/
Comment: Thanks for the suggestion. I created a 500 GB Thin Provisioned drive. The VM's settings show this. However, the volume available in CentOS is 50 GB.
Answer: I found the answer. When installing the OS, you must select Installation Destination > Storage Configuration > Custom, and then you can set the partitions however you'd like.

On this next screen, you can click Done to accept the defaults, then go back and change them.

If you don't have the luxury of installing the OS from scratch and must modify partitions, I found this answer helpful: How to shrink /home and add more space on CentOS7


Como fazer uma imagem girar

Question: preciso fazer uma imagem girar infinitamente somente com HTML e CSS e possível se sim como que pode ser feito.
Answer: Uma pergunta semelhante no SOen ia de encontro com sua duvida:
HTML:

CSS:
.image {
    position: absolute;
    /**top: 50%;**/
    /**left: 50%;**/
    width: 120px;
    height: 120px;
    /**margin:-60px 0 0 -60px;**/
    -webkit-animation:spin 4s linear infinite;
    -moz-animation:spin 4s linear infinite;
    animation:spin 4s linear infinite;
}
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }

Fica a seu gosto adicionar margens ou não mas as comentei seguindo o informe do usuário @renan
Comment: As regras de margem e posicionamento não são necessárias.
Comment: @renan, editado.

Como fazer uma imagem girar


R Megre Data Frame Column and Recode

Question: I have 2 R data frames that looks like this:
DATA FRAME 1:

identifier
ef_posterior
position_no
classification

11111
0.260
1
yes

11111
0.0822
2
yes

11111
0.00797
3
yes

11111
0.04
4
no

11111
0.245
5
yes

11111
0.432
6
yes

11112
0.342
1
maybe

11112
0.453
2
yes

11112
0.0032
3
yes

11112
0.241
5
no

11112
0.0422
6
yes

11112
0.311
4
no

DATAFRAME 2:

study_identifier
%LVEF

11111
62

11112
76

I want to merge and rearrange these two data frames into something like this:
Study_identifier and identifier are the same thing (just different column names). Additionally, I would like to recode the classification so that yes = 0, no = 1, maybe = 2

identifier
pos_1
pos_1_class
pos_2
pos_2_class
pos_3
pos_3_class
pos_4
pos_4_class
pos_5
pos_5_class
pos_6
pos_6_class
%LVEF

11111
0.260
0
0.0822
0
0.00797
0
0.04
1
0.245
0
0.432
0
62

11112
0.342
2
0.453
0
0.0032
0
0.311
1
0.241
1
0.0422
0
76

df1 %>% mutate(position_no = paste0("position_", position_no)) %>%
  pivot_wider(id_cols = identifier, names_from = position_no, values_from = ef_posterior) %>%
  left_join(df2 %>% mutate(study_identifier = as.numeric(as.character(study_identifier))), by = c("identifier" = "study_identifier"))

This is the code I have right now, but I can't figure out where to put in the code for the classification column
How would I go about doing this?
Any help would be very much appreciated!
Answer: You can recode quite easily with dplyr and case_when:
df1 %>% mutate(
  classification =
    case_when( classification == "yes" ~ 1,
               classification == "no" ~ 0,
               classification == "maybe" ~ 2)
)

I would solve it the following way:
library(tidyverse)
df1 <- data.frame(
  stringsAsFactors = FALSE,
  identifier = c(11111L,11111L,11111L,11111L,
                 11111L,11111L,11112L,11112L,11112L,11112L,11112L,
                 11112L),
  ef_posterior = c(0.26,0.0822,0.00797,0.04,
                   0.245,0.432,0.342,0.453,0.0032,0.241,0.0422,0.311),
  position_no = c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 5L, 6L, 4L),
  classification = c("yes","yes","yes","no",
                     "yes","yes","maybe","yes","yes","no","yes","no")
)

df2 <- data.frame(
  check.names = FALSE,
  study_identifier = c(11111L, 11112L),
  `%LVEF` = c(62L, 76L)
)

df1 %>% mutate(
  classification =
    case_when( classification == "yes" ~ 1,
               classification == "no" ~ 0,
               classification == "maybe" ~ 2)
) %>%
  pivot_wider(
    id_cols = c(identifier), names_from = c(position_no), values_from = c(classification,ef_posterior)) %>%
left_join(df2, by = c("identifier" = "study_identifier"))
#> # A tibble: 2 x 14
#>   identifier classification_1 classification_2 classification_3 classification_4
#>        <int>            <dbl>            <dbl>            <dbl>            <dbl>
#> 1      11111                1                1                1                0
#> 2      11112                2                1                1                0
#> # … with 9 more variables: classification_5 <dbl>, classification_6 <dbl>,
#> #   ef_posterior_1 <dbl>, ef_posterior_2 <dbl>, ef_posterior_3 <dbl>,
#> #   ef_posterior_4 <dbl>, ef_posterior_5 <dbl>, ef_posterior_6 <dbl>,
#> #   `%LVEF` <int>

Created on 2021-04-12 by the reprex package (v0.3.0)

R Megre Data Frame Column and Recode


How to perform multiple tests of contingency tables with more power: Fisher's / Barnard's test vs Logistic regression

Question: I have a sample of answers to Yes / No questions:
\begin{array} {c | c c c c}
\hline
\text{Case} & X_1 & X_2 & X_3 & X_4 \\
\hline
1 & 1 & 1 & 1 & 1 \\
2 & 0 & 1 & 0 & 0 \\
. & . & . & . & . \\
. & . & . & . & . \\
40 & 1 & 1 & 0 & 1 \\
\end{array}
from, we assume randomly chosen, $n=40$ medical institutions from population of $N = 250$ institutions.
Out of ${4\choose 2}=6$ possible dependencies between two variables, I am interested in testing 3 hypotheses:

$H_0:$ $X_2$ and $X_1$ are independent;
$H_0:$ $X_3$ and $X_1$ are independent;
$H_0:$ $X_4$ and $X_2$ are independent.

First question: I do not know if we should treat this data as paired?
Second question: Could you please recommend me some good approach to test this hypotheses?
I considered the following:

Using Fisher's exact test where there are no fixed margins can lead to lower power comparing to Barnard's test; as described in this book. So I would rather not perform Fisher's exact test if better approach is possible.
Could I use Barnard's test to test independence? If yes, can we assume pooled variance?
Since all the data are binary and there are overlapping variables, could I just use logistic regression; eg. in R:

<code> glm(X4~X2+X1, data = data1, family = binomial)
 glm(X3~X1, data = data1, family = binomial)
</code>
where this is the only meaningful direction of dependance.
Comment: I read these topics, still I am not sure what to use and whether this data is considered paired? If I am only interested in testing hypothesis that two variables are independent, I could use Fisher's / Barnard's test, but only if the data is not paired?
Comment: Similar questions have been asked before: https://stats.stackexchange.com/questions/125985/why-do-p-values-for-test-of-likelihood-ratio-vs-fishers-exact-test-not-agree,   and see all the links in comments at https://stats.stackexchange.com/questions/438188/how-can-i-calculate-the-power-of-my-analysis-with-binary-response-data?noredirect=1#comment816376_438188
Answer: Fisher's exact test assumes fixed (conditioned) row and column totals. It looks like the total number of 1's for your dataset is not fixed and could have been anything from 0 to 40. In other words, you do not know in advance the margins of your contingency table to which you will apply the test:
\begin{array}{l | ll | l}
          & X_{2} = 0 & X_2 = 1 & \text{Total} \\
\hline
X_1 = 0 & \text{...} & \text{...} & \text{?} \\
X_1 = 1 & \text{...} & \text{...} & \text{?} \\
\hline
\text{Total} & \text{?} & \text{?} & 40
\end{array}
This means that both the row and column totals are unconditioned in your case. Therefore Fisher's exact test is not exact in your case and it is true that applying it means you have less power on average. Barnard's exact test and it's variant Boscholoo's test, do not condition on any margin, so you have more power using them on average. To help you decide between Bernard's and Boscholoo's test see this.
Regarding multiple testing, you could simply apply Bonferroni correction for multiple comparisons. This means with 3 pairwise comparisons, at P < 0.05 significance level, the P value must be less than 0.05/3 to be significant.
Regarding your first question. I don't see any matched pairs of subjects in this data. What I understand by paired data:

For example using some additional treatment information we can have contingency table:

\begin{array}{l | ll }
          & X_{\text{after}} = 0 & X_{\text{after}} = 1 \\
\hline
X_{\text{before}} = 0 & \text{...} & \text{...} \\
X_{\text{before}} = 1 & \text{...} & \text{...} \\
\end{array}

Or by using some additional similarity information, something like this:
\begin{array}{l | ll }
          & X_{\text{sibling}} = 0 & X_{\text{sibling}} = 1 \\
\hline
X = 0 & \text{...} & \text{...} \\
X = 1 & \text{...} & \text{...} \\
\end{array}

For this kind of paired data we can use the McNemar's test.
In logistic regression example you probably meant:
<code>glm(X1 ~ X2 + X3, data = data1, family = binomial)
glm(X4 ~ X2, data = data1, family = binomial)
</code>
Comment: Thank you for the answer. I understand now that data is unpaired. Sure, if I perform Fisher's or Barnard's test I should use correction for multiple testing.


Nginx Secure Download (IP address)

Question: I'm configuring nginx to work with secure_download and has made it to work without any problems.
However I want to modify it and make the download link for a specific IP only.
I can achieve this using the $remote_addr variable. However there are certain ISPs that I know of that changes IP too often (once every 2 or 3 seconds).
My ISP does this too, eg:
I got 18.104.22.168 as my IP right now, after I refresh it'll be 18.104.22.168. This behavior is set by the ISP, not by my modem or router and I know a few more ISPs which does the same.
Now, with the IP changing too fast, secure download will not work because upon loading the page, the IP might've changed already, rendering the download link invalid for the new IP.
What I'm thinking of is telling nginx to just look at the first 3 blocks on the ip address, in this case 112.112.11.x would be able to download the same file with the same secure download link. Would this be possible using nginx conf?
Any other alternatives is welcome.
Answer: You can add a new variable using the map directive that will only include the first three octets of $remote_addr:
map $remote_addr $remote_net {
   default $remote_addr;
    ~^(?<octets>\d+\.\d+\.\d+) $octets;
}

Then just use $remote_net instead of $remote_addr.  The default will leave the variable alone for ipv6 clients, and just have the first three octets for ipv4 clients.
Answer: You can stop access at the OS level. Use iptables to allow inbound traffic on ports 80 and 443 from that range of hosts, then reject all other traffic on ports 80 and 443.
Comment: Hi. Im not being hacked, I dunno how blocking ports is related to my question. This system is dynamically generating download links for files and I want to allow IP range instead of the exact IP for that particular file link. http://wiki.nginx.org/HttpSecureDownload

Nginx Secure Download (IP address)