Stochastic ordering

Question: I'm a bit stuck with the following.
Assume $X$ ~$N(0,1)$ and $Y$~$N(1,1)$.
Is $Y$ stochastic bigger than $X$?
And the same question goes for $X$~$N(0,1)$, $Y$~$N(0,4)$..
I simply don't have a clue how to approach it. Can one please guide me?
Thanks!
Answer: According to Wikipedia:

A real random variable $X$ is smaller than a random variable $Y$ in the "usual stochastic order" if:
$$ \forall \ r \in \mathbb{R}, \ \mathbb{P}(X>r) \leq \mathbb{P}(Y>r) $$

This is equivalent to saying:
$$ \forall \ r \in \mathbb{R}, \ \mathbb{P}(X\leq r) \geq \mathbb{P}(Y\leq r) $$
Now, let $X \sim \mathcal{N}(0,1)$ and $Y \sim \mathcal{N}(1,1)$. We have:
$$ \begin{align}
\mathbb{P}(Y \leq r) & = \int_{-\infty}^r\frac{1}{\sqrt{2\pi}}e^{-\frac{(u-1)^2}{2}}du
\end{align} $$
Doing the change of variable $u = t+1$:
$$ \begin{align}
\mathbb{P}(Y \leq r) & = \int_{-\infty}^{r-1}\frac{1}{\sqrt{2\pi}}e^{-\frac{t^2}{2}}du
\\[12pt]
& = \mathbb{P}(X \leq r-1)
\\[12pt]
& \leq \mathbb{P}(X \leq r)
\end{align} $$
Because $\mathbb{P}(Y \leq r) \leq \mathbb{P}(X \leq r)$, $X$ is stochastically-smaller than $Y$ $-$ this is rather intuitive if you consider the behaviour of normal random variables and the fact that $\mathbb{E}[Y] \geq \mathbb{E}[X]$.
Now, let $X \sim \mathcal{N}(0,1)$ and $Y \sim \mathcal{N}(0,4)$ $-$ I am assuming the 2nd argument of $\mathcal{N}(\cdot,\cdot)$ is the variance. We have:
$$ \begin{align}
\mathbb{P}(Y \leq r) & = \int_{-\infty}^r\frac{1}{\sqrt{2\pi 2^2}}e^{-\frac{1}{2}\left(\frac{u}{2}\right)^2}du
\end{align} $$
Doing the change of variable $u = 2t$:
$$ \begin{align}
\mathbb{P}(Y \leq r) & = \frac{1}{2}\int_{-\infty}^{\frac{r}{2}}\frac{1}{\sqrt{2\pi}}e^{-\frac{t^2}{2}}\frac{du}{2}
\\[12pt]
& = \frac{1}{4}\mathbb{P}\left(X \leq \frac{r}{2}\right)
\end{align} $$
As pointed out by @Dilip Sarwate and @Mark L. Stone $-$ big mistake on my side... $-$ in this case neither is stochastically-bigger in the sense above $-$ indeed whether $\mathbb{P}(Y \leq r)$ or $\mathbb{P}(X \leq r)$ is bigger will depend on the sign of $r$. Sorry for the mistake!
Generally speaking, if we let $X \sim \mathcal{N}(0,1)$ and $Y \sim \mathcal{N}(\mu,\sigma^2)$, we have $-$ this can be shown through a change of variables, like above:
$$ \mathbb{P}(Y \leq r) = \frac{1}{\sigma^2}\mathbb{P}\left(X \leq \frac{r-\mu}{\sigma}\right)$$
Comment: I don't think your second argument is correct. Consider the case $r = -2$. From $$P\left(Y\leq -2\right) \leq P\left(X\leq -1\right)$$ how do you get to $$P\left(Y\leq -2\right) \leq P\left(X\leq -2\right)??$$ Your argument seems to work for $r > 0$ because then $\frac r2 < r$ and so $P\left(X\leq r/2\right)\leq P\left(X\leq r\right)$ but for $r < 0$, $r/2 > r$.
Comment: N(0,4) is not stochastically greater than N(0,1).  That holds for (argument) values greater than (or equal to) zero, but the reverse is true for (argument) values less than zero.
Comment: Indeed, totally wrong!

Stochastic ordering


Expected value of $X$ given $X > Y$

Question: I'm doing some research and I'm trying to compute a closed form for $ \mathbb{E}[ X \mid X > Y] $ where $X$, $Y$ are independent normal (but not identical) random variables. Is this known?
Comment: Do the random variables have zero mean and different variances?  Or are they entirely arbitrary?
Comment: Alternatively is there a tight upper bound for this quantity?
Comment: @bijection, you can edit the question to add extra stuff, if you want. DO not use the answer box for that, though, because it should be reserved for, well, answers :-)
Answer: One can reduce the problem to the computation of $E(U\mid U\gt aV-b)$ where $(U,V)$ are i.i.d. standard normal. Let $\varphi$ denote the standard normal PDF, then $u\varphi(u)=-\varphi'(u)$ hence $$E(U;U\gt aV-b)=\int_\mathbb R\varphi(v)\mathrm dv\int_{av-b}^\infty u\varphi(u)\mathrm du=\int_\mathbb R\varphi(v)\varphi(av-b)\mathrm dv.$$ Computing the product $\varphi(v)\varphi(av-b)$ and using the change of variable $w=cv$ with $$c=\sqrt{1+a^2},$$ one gets $$E(U;U\gt aV-b)=\varphi(b/c)/c.$$ On the other hand, $U-aV$ is centered normal with variance $c^2$ hence $$P(U\gt aV-b)=\Phi(b/c),$$ where $\Phi$ denotes the standard normal CDF. Thus, $$E(U\mid U\gt aV-b)=\frac{\varphi(b/c)}{c\Phi(b/c)}.$$ For general independent normal random variables $X$ and $Y$, note that $$E(X\mid X\gt Y)=\mu_X+\sigma_XE(U\mid U\gt aV-b),$$ with $$a=\sigma_Y/\sigma_X,\qquad b=(\mu_X-\mu_Y)/\sigma_X,$$ that is,
$$
E(X\mid X\gt Y)=\mu_X+\tau\sigma_X\frac{\varphi(\tau\nu)}{\Phi\left(\tau\nu\right)},\qquad\nu=\mu_X-\mu_Y,\qquad\tau=\frac{\sigma_X}{\sqrt{\sigma_X^2+\sigma_Y^2}}.$$
Answer: Hint: you can directly do the double integrals in the district $x>y$ for $xf(x)$, not so hard, I remember.
Answer: yes, $\mathbb{E}(X|X > y)$ has a closed form as the expectation of a truncated normal. However, integrating that expression times the pdf of $Y$, is difficult. The normal r.v. are arbitrary. Does anyone have a satisfactory answer or is there no known closed form?
Answer: Explicitly, we have for $X \sim \operatorname{Normal}(\mu_x, \sigma_x^2)$ and $Y \sim \operatorname{Normal}(\mu_y, \sigma_y^2)$, $$\operatorname{E}[X \mid X > Y] = \int_{y=-\infty}^\infty \int_{x=y}^\infty x f_{X,Y}(x,y) \, dx \, dy$$ where $$f_{X,Y}(x,y) = \frac{1}{2\pi \sigma_x \sigma_y} \exp \biggl(-\frac{(x-\mu_x)^2}{2\sigma_x^2} - \frac{(y-\mu_y)^2}{2\sigma_y^2} \biggr)$$ is a bivariate normal density with zero correlation (since $X$, $Y$ are independent).  This integral does not, for general parameters, have an elementary closed form.
Comment: How do we know it doesn't have a general closed form?
Comment: Shouldn't the final answer be divided by P(X > Y)?
Comment: "This integral does not, for general parameters, have an elementary closed form." Hmmm...

Expected value of $X$ given $X > Y$


Distribution of "sample" mahalanobis distances

Question: Let $x_1,\dots,x_n$ be i.i.d. observations from $N_p(0,\Sigma)$. Let $\hat S=\frac1n\sum_{i=1}^n x_ix_i^T$ be the sample covariance of the samples. Recall that the Mahalanobis distance is defined: $d_i(x_i)^2=x_i^T\hat S^{-1}x_i$
A previous question considered the distribution of $d(\bar{x})$.
What can we say about the distribution of $d_i(x_i)$? Has this been studied? If this has been done, a reference would be appreciated. I'm not sure it can be connected to the previous question.
Comment: Hint: Notice that you can choose $\Sigma = I$ without loss of generality.
Comment: That is not quiet correct. Your definition of the squared MD is a bit off: it should be $(x-\hat{\mu})^\top\hat{S}^{-1}(x-\hat{\mu})$
Answer: if $\{\pmb x_i\}_{i=1}^n$ is your data with $\pmb x_i\underset{\text{i.i.d.}}{\sim}\mathcal{N}_p(\pmb \mu,\pmb \varSigma)$ where $\pmb \mu\in\mathbb{R}^p$
and $\pmb \varSigma\succ0$ and we denote:
$$(\mbox{ave}\;\pmb x_i,\mbox{cov}\;\pmb x_i)$$
the usual Gaussian estimates of mean and covariance, then
$$d^2(\pmb x_i,\mbox{ave}\;\pmb x_i,\mbox{cov}\;\pmb x_i)=(\pmb x_i-\mbox{ave}\;\pmb x_i)^\top(\mbox{cov}\;\pmb x_i)^{-1}(\pmb x_i-\mbox{ave}\;\pmb x_i)$$
has distribution [0, p113][1, p562]:
$$d^2(\pmb x_i,\mbox{ave}\;\pmb x_i,\mbox{cov}\;\pmb x_i)\sim\frac{(n-1)^2}{n}\mbox{Beta}\left(p/2,(n-p-1)/2\right)$$

[0] Gnanadesikan, R. and Kettenring, J.(1972).
Robust estimates, residuals, and outlier detection with multiresponse data. Biometrics,28:81--124.
[1] Wilks, S. (1962). Mathematical Statistics. John Wiley.
Comment: @whuber: good catch, fixed (as per the equation on p113 of the first entry of my reference list)
Comment: I don't understand your distance function, which takes 3 parameters. Can you explain?
Comment: @Lepidopterist: This is the actual definition of the squared [Mahalanobis distance](https://en.wikipedia.org/wiki/Mahalanobis_distance)
Comment: How does this relate to the quantity that I wrote (incorrectly) as the Mahalanobis distance?
Comment: @Lepidopterist: what do you mean by *this*?
Comment: @whuber What if we used the farthest neighbor to define the scale, and look at the distribution of the distances to the other samples?
Answer: If your estimate of $\Sigma$ is not too far off, it is the Euclidean distance of a multivariate standard normal distribution, i.e. $\chi$ distributed.
To understand this, assume your estimate is perfect: $\hat S =\Sigma$. The math then should be straightforward, because you can essentially remove all the variance, and it is the same solution as for $\Sigma=I$.
For small sample sizes $n$, the results can be all over the place. The covariance matrix can be arbitrary bad for small samples - just assume all your sample is the same point, $n$ times (so this could still happen at $n\rightarrow\infty$, except that it is unlikely to happen).


Let $\alpha: F \rightarrow F$ be a one to one field homomorphism, prove $\alpha$ fixes the prime subfield of $F$ elementwise

Question: Let $\alpha: F \rightarrow F$ be a one to one field homomorphism, prove $\alpha$ fixes the prime subfield of $F$ elementwise.
So I already proved that $\alpha$ fixes the identity element and used that to prove that $\alpha$ fixes the prime subfield of $F$ when $Char(F)=p$, which was easy because in this case the prime subfield is just $\mathbb{Z_p}$. I'm not trying to do this when $Char(F)=0$, so the prime subfield of $F$ is going to be isomorphic to $\mathbb{Q}$. I as going to proceed the same way, let $\frac{a}{b} \in \mathbb{Q}$ then $\alpha (\frac{a}{b})=\alpha(\frac{1+1+...+1_a}{1+1+1...+1_b})$.. but I got a little thrown off because i'm not used to using the multiplicative properties of a homomorphism when there is a denominator involved... I guess I could write the denomoniator $(1+1+1+....1_b)^{-1}$ and go from there but I just wanted to double check with yall, and besides that every time I ask something on here I get some new insight into something so I thought why not. Thanks in advance!
Comment: Yes, I also get some new insight form this site, reading so many great answers. I saw [this answer](https://math.stackexchange.com/questions/1758671/how-would-you-show-that-field-automorphisms-fix-prime-subfields), by the way.
Answer: You appear to be comfortable showing that $\alpha(a)=a$ for $a\in\mathbb{Z}$. It is now enough to show that $$\displaystyle b\alpha\left(\frac{a}{b}\right)=a.$$ Well,
\begin{align}
b\alpha\left(\frac{a}{b}\right)&=\alpha(b)\alpha\left(\frac{a}{b}\right)\\
&=\alpha\left(b\frac{a}{b}\right)\\
&=\alpha(a)\\&=a.
\end{align}
Comment: Also, using $\alpha(ab^{-1})=\alpha(a)\alpha(b)^{-1}$ is another fine proof.


Sum is an isomorphism, finitely generated modules

Question: Suppose $R$ is a local ring with maximal ideal $m$ and suppose $M$ and $N$ are $R$-finitely generated modules. Let $f,g: M \rightarrow N$ be an $R$-module homomorphism. If $f$ is an isomorphism and $g(M) \subset mN$ why is $f+g$ in fact an isomorphism?  I think this might follow by Nakayama's lemma but I don't see this. Can you please help?
Comment: There are three good answers here, but no votes (other than mine).  Surely something is wrong with our voting habits?
Comment: @Jack I have said it before on meta http://tinyurl.com/4ams5jk and I will say it again here: if you worry too much about voting on this site, you will lose your sleep. It's not worth it!
Answer: The hypotheses ensure that $g \otimes  R/\mathfrak{m}: M/\mathfrak{m}M \rightarrow N/\mathfrak{m} N$ is zero and thus that $(f+g) \otimes R/\mathfrak{m}$ is an isomorphism.  It is a standard consequence of Nakayama's Lemma that this implies that $f+g$ is surjective: see e.g. the end of Section 3.8.1 of my commutative algebra notes.
We still need to show that $f+g: M \rightarrow N$ is injective.  Let $K$ be the kernel of this map.  If we may assume that $K$ is a finitely generated $R$-module, then again this follows from Nakayama's Lemma since the hypotheses give $K/\mathfrak{m} K =
\ker ((f+g) \otimes R/\mathfrak{m}) = 0$.
However, the assumption of the previous paragraph does seem to be an additional assumption, albeit a mild one.  It is automatic if $M$ is not just finitely generated but finitely presented and this in turn is automatic if the ring $R$ is Noetherian.  (In the olden days, "local rings" were required to be Noetherian.  I wonder if that's what you meant?)  Whether the result is still true without any additional assumptions I'm not sure off the top of my head.  Perhaps some context would be helpful: why do you think this result is true?
Comment: Dear Pete, it is a theorem (which follows from the Cayley-Hamilton theorem; see http://math.columbia.edu/~dejong/wordpress/?p=1070) that any surjective endomorphism of a finitely generated module over *any* commutative ring is an isomorphism. So since $M$ and $N$ are known to be isomorphic already (under $f$), I do not think we need noetherianness.
Comment: (In case people are wondering "how does Pete L. Clark know what's at Johan de Jong's bedside?"  The answer is that I don't.  It happens that I know Johan and his wife pretty well from my graduate school days, but **not that well**, of course.  But in the blog post Akhil links to, Brian Conrad points out that Johan must have seen the result in question from Matsumura's book and Johan replies that he does not own that particular book of Matsumura.)
Comment: @Akhil: thanks for this.  Like Johan de Jong, I was blissfully unaware of this (although unlike him, I have a well-thumbed copy of Matsumura at my bedside).  The best way I know to remember this fact in the future is to write it up, so I will incorporate it into my commutative algebra notes in the near future.
Answer: You need to apply Nakayama to both the kernel of $f+g$ and to the cokernel of $f+g$.  I suspect that you need to suppose $R$ to be Noetherian local, in order to know that the kernel is again finitely generated.
Now if $K$ is either the kernel or the cokernel, you must argue that $K = mK$.
Give it a try...
Answer: Composing with $f^{-1}$ allows us to assume $M=N$, $f=\mathrm{Id}$.
Let $M'=(\mathrm{Id}+g)(M)$.
Then $P=M/M'$ satisfies $P=mP$ (if $x \in M$, $x=x+g(x)-g(x) \in M' + mM$) and is finitely generated, so that $P=0$.
Moreover, for all $x \in K = \ker (\mathrm{Id}+g)$, $x=-g(x)=g^2(x)=\ldots=(-1)^n g^n(x)$ for any integer $n$, so that $K \subset \bigcap_{n \geq 0} m^n M$.
Now if $R$ is noetherian, this last module is finitely generated and satisfies the same condition as $P$, so Nakayama's lemma can be applied again and $K=0$.
Comment: Actually the fact that $M'' = \bigcap_{n \geq 0} m^n M$ satisfies $M''=mM''$ is not really obvious, but follows from Artin-Rees lemma: http://en.wikipedia.org/wiki/Artin%E2%80%93Rees_lemma


Send prefill message PrivateMsg

Question: I need a feature for my website, I want that users can send pre-filled messages to others users.
Like in an user's profile page, they just have to click on a button and then, the pre-filled message is sent.
I'm using PrivateMsg module, I don't know if this module could do the job
(By the way I'm new to Drupal).
Thanks for your help !
Answer: You may implement this: hook_privatemsg_message_presave_alter.

Change the message before it is stored.

The $message variable contains the message's body (as well as much more parameters) ready to be edited. Note that you can include html tags in your message. Here is a code sample:
/**
 * Implements hook_privatemsg_message_presave_alter().
 * Change the message before it is stored.
 */
function my_module_privatemsg_message_presave_alter(&$message) {
  // dsm($message); print out the $message contents
  $name = $message->recipients['user_1']->name; // use foreach for many recipients
  $message->body = "Dear $user,\n you rock!";
}

Send prefill message PrivateMsg


Running gradle release on gitlab pipeline triggers 3 more build jobs

Question: This is my gitlab pipeline:
image: docker:latest
services:
  - docker:dind

variables:
  DOCKER_DRIVER: overlay
  SPRING_PROFILES_ACTIVE: gitlab-ci

before_script:
  - git remote set-url origin https://gitlab-ci-token:$CICD_GIT_TOKEN@$CI_SERVER_HOST/$CI_PROJECT_PATH.git
  - git config --global user.email 'email@example.com'
  - git config --global user.name 'Gitlab (Me)'
  - git checkout -b $CI_COMMIT_BRANCH

stages:
  - build
  - package
  - deploy

gradle-build:
  image: gradle:alpine
  stage: build
  script:
    - PROJECT_VERSION=`./gradlew -quiet printVersion`
    - ./gradlew release
  artifacts:
    paths:
      - build/libs/*.jar

docker-build:
  stage: package
  script:
  - docker build -t registry.gitlab.com/me/myproject:$PROJECT_VERSION .
  - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN registry.gitlab.com
  - docker push registry.gitlab.com/me/myproject:PROJECT_VERSION

Not sure why the 3 builds get triggered (maybe because the plugin does a commit) and not sure how to fix this.
Any help would be appreciated.
Thanks.
Comment: there is no `rules` to limit the action, so every commit will trigger the jobs
Comment: @Ôrel there actually is one, and it's called exactly "rules"
Answer: After taking a look here:
https://docs.gitlab.com/ee/ci/yaml/
I added the following section to the pipeline:
workflow:
  rules:
    - if: $CI_COMMIT_AUTHOR =~ /^Gitlab Pipeline/
      when: never
    - when: always

Moved the stuff in "before_script" under script, and changed the git username:
  script:
    - git remote set-url origin https://gitlab-ci-token:$CICD_GIT_TOKEN@$CI_SERVER_HOST/$CI_PROJECT_PATH.git
    - git config --global user.email 'firstname.lastname@example.com'
    - git config --global user.name 'Gitlab Pipeline'
    - git checkout -b $CI_COMMIT_BRANCH
    - ./gradlew release

Now the commits with the name "Gitlab Pipeline" don't trigger a build anymore.
The extra builds were triggered because the release plugin also does a pre-tag commit, followed by a new version commit at the end. This would trigger 2 builds, which in turn would each trigger 2 more and so on.
Now the pipeline behaves as expected.


Installing a dual display graphics card in a Windows 2008 server

Question: Trying to hook up a Dell Poweredge T620 to 2 27" monitors via a PNY Nvidia NVS 310.
Server running Windows 2008 R2 Standard SP1.
Nothing fancy, but need a very large desktop area (2 x 2560 x 1440).
Fitted the card into the 'SLOT2 PCIE_G3_X16(CPU1)' slot (the server has two CPUs, and notice there are PCI slots for each CPU, not sure if this is relevant or not but haven't installed a graphics card in a multi-CPU system before).
Installed drivers "331.65-quadro-tesla-grid-winserv2008-2008r2-2012-64bit-international-whql" as recommended on the Nvidia drivers page, installed with the default options.
The graphics card now appears to be installed and detected by Windows, appearing alongside the on-board "Matrox G200eR" adapter in Device manager as "NVIDIA NVS 310", no errors/issues reported.
Card is connected up to the monitors using DVI cables.
Now... problem is

Cannot detect any monitors in 'Screen Resolution' screen, only listing the monitor connected to the on-board/Matrox VGA port.
Looking at the advanced settings only show settings for the Matrox display.
Right clicking on desktop and opening 'nView Desktop Manager' nothing happens & no new processes.

Disabling the Matrox display adaptor in Device manager doesn't have an effect on the Nvidia card.
Only options in the BIOS setup appear to be enable/disable the PCI slots on the server. I could disable the embedded display from here, but worry that I'd lose all display output.
ETA
Trying the drivers (clean install) that came with the card, version 310.90. No change.
There's two Nvidia control panel items - 'NVIDIA nView Desktop Manager' which doesn't do anything and 'NVIDIA Control Panel' which launches nvcplui.exe (Control Panel Application) and reports 'NVIDIA Display Settings are not available. You are currently not using a display attached to an NVIDIA GPU.'
There's several Nvidia applications running in the background

1 x nvvsvc (Driver helper service)
2 x nvwmi64 (WMI Provider Core)
2 x nvxdsync (User Experience Driver Component)

Tried swapping the card over to another port PCIe port - SLOT7 PCIE_G3_X16(CPU2) - sadly no change.
ETA (again)
Tried using DirectPort cables (rather than the DirectPort to DVI adapter cable). No difference.
Answer: Try disabling the on-board graphics adapter from BIOS setup. If you are worried that you'll lose all video, document all settings in there so you safely can reset the CMOS in case it doesn't work. Removing the Nvidia card should also revert to the onboard adapter.
Comment: Actually, quick google mentions this: [link](http://en.community.dell.com/support-forums/servers/f/956/t/19502455.aspx) "With most Dell servers, they won't support using a 3rd party video card in the server. The 12th generation servers differ in the fact that you can use the 3rd party video cards in them, but in a GPGPU use. Not for the sake of video display. So they support 3rd party video cards, not for using for display, but as a graphic processor."
Comment: That did the trick. I wasn't too hopeful after reading that Dell support forum thread, but I noticed that the option to disable the on-board graphics could only be set if the Nvidia card was fitted. Once disabled and rebooted, the server started using the Nvidia card for all display output.


IllegalStateException at start up Spring JUnit test

Question: I've made a simple Maven Spring REST project. (this one: https://spring.io/guides/gs/rest-service/)
Afterwards I made a simple JUnit test using MockMVC to test the REST functionality. In this case: does my code respond to /greeting?
When I run my test (using IntelliJ) I get this IllegalStateException.
How can I resolve this?
Comment: Post the stack trace as text, not as an image. And post the relevant code.
Answer: You're probably using incompatible versions of spring-test and spring-boot. spring-test calls SpringApplicationContextLoader.getResourceSuffixes (plural form) since v4.1.0.RC2. spring-boot's SpringApplicationContextLoader.getResourceSufffix (singular) throws that exception since v1.3.0.RC1.
You would have to either upgrade to spring-test >= 4.1.0 or downgrade to spring-boot < 1.3.0
Comment: Oh, sorry - spring moved the test classes back into the framework repository. You need to upgrade your spring-test dependency to > 4.1.0
Comment: Okay, I changed that tot 4.2.5. I think that error is resolved. Now, I get a few other errors I don't understand: http://puu.sh/nM1FB/b39002b018.png
Comment: @John if this answer resolved the problem described in your question, it would be nice to upvote + accept this answer, and ask a completely new question with the next problems you're experiencing


Receber Lista na View. Asp.Net Mvc

Question: Eu estou com problema na Action Editar.
eu tenho um classe chamada ClienteEmpresa essa classe tem Uma coleção de Sistema.
Por Exemplo: O Cliente X usa os sistemas A, C e F.
Meu problema é como apresentar esses sistema na View Editar.
Essa é minha View Get Editar
public ActionResult Editar(int? id)
{
if (id == null)
{
   return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
   ClienteEmpresa clienteEmpresa = db.ClienteEmpresaDb.Find(id);
    if (clienteEmpresa == null)
    {
      return HttpNotFound();
    }
      ViewBag.SistemasComerciais =  clienteEmpresa.TipoDeSistemas.ToList();
      ViewBag.RamoDeAtividade = clienteEmpresa.RamoAtividade;
      return View(clienteEmpresa);
}

Eu tentei enviar em uma viewBag, mas deu esse erro

O item ViewData que possui a chave 'SistemasComerciais' é do tipo
  'System.Collections.Generic.List`1[[Smc.Dominio.Model.TipoDeSistemas,
  Smc.Dominio, Version=188.8.131.52, Culture=neutral, PublicKeyToken=null]]',
  mas precisa ser do tipo 'IEnumerable'.

Esse é o html que recebe essa lista.

Tipo De Sistema
@Html.DropDownList("SistemasComerciais", null, htmlAttributes: new { @class = "standardSelect", multiple = "multiple", placeholder = "Selecione..." })

Esse é o código da classe TipoDeSistemas:
public class TipoDeSistemas
{
   [Key]
   public int Id { get; set; }

   [Required]
   public string Descricao { get; set; }

   public string Cod { get; set; }

   [Required]
   public DateTime DataCadastro { get; set; }

   public virtual ICollection<ClienteEmpresa> ClienteEmpresa { get; set; }
}

Alguém sabe como eu posso mostrar essa lista de sistemas, que meu cliente usa?
Answer: O Html.Helper para dropDownList é:
MvcHtmlString Html.DropDownList(string name, IEnumerable<SelectLestItem> selectList, string optionLabel, object htmlAttributes)

e o tipo passado no Viewbag é uma List
Você pode ou enviar um IEnumerable ou popular o dropDown manualmente.
Comment: Não entendi muiito bem, tem como vc fazer esse helper ai, com esses dados aqui.
`@Html.DropDownList("SistemasComerciais", null, htmlAttributes: new { @class = "standardSelect", multiple = "multiple", placeholder = "Selecione..." })`
Comment: Tente passando os dados em um `IEnumerable` ao invés de uma `List`
Answer: O erro ocorre porque você está usando null onde deveria passar o objeto com seus itens.
Tente assim:
@Html.DropDownList("SistemasComerciais", new SelectList(ViewBag.SistemasComerciais, "Id", "Nome"),
    htmlAttributes: new { @class = "standardSelect", multiple = "multiple", placeholder = "Selecione..." })

Nesse exemplo eu estou inferindo que você possui uma classe (SistemasComerciais por exemplo) com as proprieades Id e Nome, se o nome das propriedades forem diferentes basta substituir onde está "Id" e "Nome" pelos nomes que você usa em suas propriedades.
A primeira propriedade (nesse exemplo "Id") renderiza o atributo value no HTML e a segunda propriedade (nesse exemplo "Nome") será renderizada como uma descrição:
<select class="standardSelect" id="SistemasComerciais" multiple="multiple" name="SistemasComerciais" placeholder="Selecione...">
   <option value="1">SistemaComercial a</option>
   <option value="2">SistemaComercial b</option>
   <option value="3">SistemaComercial c</option>
</select>

Edição:

Exemplo completo:
Model:
public class TipoDeSistemas
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Descricao { get; set; }
}

Action:
public ActionResult ViewBagComDropdown()
{
    List<TipoDeSistemas> lista = new List<TipoDeSistemas>()
    {
        new TipoDeSistemas { Id = 1, Descricao = "a" },
        new TipoDeSistemas { Id = 2, Descricao = "b" },
        new TipoDeSistemas { Id = 3, Descricao = "c" }
    };
    ViewBag.SistemasComerciais = lista;
    return View();
}

View:

    @Html.DropDownList("SistemasComerciais", new SelectList(ViewBag.SistemasComerciais, "Id", "Descricao", "Selecione... "),
    htmlAttributes: new { @class = "standardSelect", multiple = "multiple" })

Minha View renderizada:
Comment: Agora deu essa mensagem. `DataBinding: 'System.Web.Mvc.SelectListItem' não contém uma propriedade com o nome 'Id'.`---- Porém eu tenho essa propriedade Id.
é Id e Descricao que uso.
Comment: `public class TipoDeSistemas
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string Descricao { get; set; }
        public string Cod { get; set; }
        [Required]
        public DateTime DataCadastro { get; set; }
        public virtual ICollection ClienteEmpresa { get; set; }
    }`
Comment: Ok, adicionei o código da classe na pergunta. Bom quanto ao erro `DataBinding: 'System.Web.Mvc.SelectListItem' não contém uma propriedade com o nome 'Id'.` te aconselho a debugar seu código e verificar o retorno dessa propriedade após obter retorno na linha  `ViewBag.SistemasComerciais =  clienteEmpresa.TipoDeSistemas.ToList();`
Comment: Fiz aqui rapidinho um exemplo completo e adicionei para você na minha resposta.
Comment: Agora de certo \o/..obrigado!!...

Receber Lista na View. Asp.Net Mvc


How to give developer shell access to use GIT and manage code, nothing else?

Question: In CentOS 6.5 (SElinux off, chroot) with Webmin/Virtualmin (latest version) I want to give a developer access to SSH within /home/site so he can use only git to manage the code. I also want to give him access to FTP into /home/site/ and MySQL access to the 3 DBs (site and 2 sub-servers)
SSH: I created an user called dev_ssh. SSH is cert based only login and I have SSH to /home/dev_ssh working. I want to give this user access to the /home/site directory, but the user cannot cd to /home/site unless I add him to sudoers.
FTP: I created 1 user for the site (dev.site), he can access the entire /home/site. This part is working fine.
MySQL: I created a mysql user dev_mysql, and gave this user access to all 3 DBs (main one and sub-servers' DBs). The MySQL access I might have to keep it this way, as that user has access to remotely login to MySQL only for those 3 DBs (whereas the unix user can only access from MySQL localhost). This part is working fine.
How do I solve the SSH access to /home/site issue?
Additionally, is this entire setup the proper way to set this up in a Webmin environment?
Comment: http://git-scm.com/docs/git-shell.html
Comment: thanks, but that only helps after the user can access the needed folders.
Comment: The idea of git is that the whole repository is being distributed. So I suggest thinking about why developers really need a shell access on that machine at all.
Comment: @MarcStürmer the repo is bitbucket. the server is where he needs to deploy the code.
Answer: Use system group to give access to directory. Change the group ownership of /home/site to a common group such as git and add user dev_ssh in to that group.
chgrp -Rvf git /home/site
usermod -a -G git dev_ssh

Comment: I cannot change the ownership of the group as that would mess up the entire setup. It's an apache folder, and the folder is owned by sitename.
Comment: Is it possible to add dev_ssh to the group which owns /home/site ?
Comment: that's what I tried to do. didn't work. couldn't even CD into /home/site.
Comment: Make sure group has read and execute permission to that directorychmod g+rx /home/siteusermod -a -G sitename dev_ssh
Comment: I added dev_ssh to the group. The group owns the dir (recursively). Didn't work. execute permissions are not needed for a simple `cd`
Comment: That's weird. what's groups dev_ssh and ls - ld /home/{,site} ?
Comment: Sorry, I don't understand your question.
Answer: In ~/.ssh/authorized_keys
command="git",no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty ssh-dss [...]

Comment: This does not solve the permissions issue.
Answer: You can restrict the 'git' user to only doing Git activities with a limited shell tool called git-shell that comes with Git. If you set this as your 'git' user's login shell, then the 'git' user can't have normal shell access to your server. To use this, specify git-shell instead of bash or csh for your user's login shell. To do so, you'll likely have to edit your /etc/passwd file.
Comment: yes, git-shell is the way to go but that only helps after the user can access the needed folders.
Comment: Perhaps you don't fully understand.  You change the shell from /bin/bash or /bin/sh (whatever is defined for the user in /etc/passwd) to /bin/git-shell.  Then when the user logs in, he/she can only perform git related actions.

To restrict their commands:
Place a directory named 'git-shell-commands' in the home directory of a user whose shell is git-shell. Then anyone logging in as that user will be able to run executables in the 'git-shell-commands' directory.
Comment: you can control what commands are available to the git user by adding links to the commands in their /home/git/git-shell-commands directory. The first of which would be "git" itself.  If you want them to have specific commands available such as "ls", then you need to make a link to ls in their git-shell-commands directory: ln -s /bin/ls ls   --- now they'll be able to execute ls from their git-shell connection.
Comment: git-shell will be implemented, but he still will not be able to use the commands on the folders he doesn't have permission to. he can't cd to /home/site even if I add dev_ssh to the group that owns that directory. it must be a chroot problem.
Comment: permissions will be honored.  You'll have to add cd to his git-shell-commands for him to be able to change directories at all.  I haven't found that command in my setup... thinking it's part of shell.
Comment: Yes, since they will be honored, my problem is not git-shell. it's the setup/chroot within this environment (a standard CentOS system with Webmin/Virtualmin)
Comment: If you want to change to user's home directory, simply modify the /etc/passwd file.

dev_ssh:x:32016:32018::/home/site:/bin/git-shell
Comment: I would do that if I wanted to give him access to a dir and all it's subdirs. But since he works on /home/site and /home/othersite I'd have to give him access to /home, which cannot be done.
Answer: setfacl -m d:u:dev_ssh:rx /home/site

Make sure the filesystem containing /home/site has been mounted with the acl option.
Source: CentOS Access Control List docs.
Comment: It's surely mounted with the ACL option, otherwise dev_ssh wouldn't get denied when trying to `cd /home/site`
Comment: @Gaia OK. How did the `setfacl` command work out for you?
Comment: Didn't run it, don't want to mess anything up.


ModuleNotFoundError: No module named 'bs4' e não consigo acessar o modulo bs4

Question: Estou tentando importar o modulo bs4 em um código e toda vez que eu tento o seguinte erro é exibido
ModuleNotFoundError: No module named 'bs4'

Teoricamente o modulo bs4 já foi instalado e quando eu executo no terminal o comando pip install bs4 aparece a seguinte mensagem:
C:\Users\gabri>pip install bs4
Requirement already satisfied: bs4 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (0.0.1)
Requirement already satisfied: beautifulsoup4 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from bs4) (4.9.3)
Requirement already satisfied: soupsieve>1.2 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from beautifulsoup4->bs4) (2.2.1)

O modulo requests está funcionando e quando eu tento instalar ele dá a seguinte, mensagem. Estava tentando comparar com o modulo bs4 para ver se estavam instalados em locais diferentes mas não seguinte encontrar o erro
C:\Users\gabri>pip install requests
Requirement already satisfied: requests in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (2.25.1)
Requirement already satisfied: idna<3,>=2.5 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from requests) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from requests) (2020.12.5)
Requirement already satisfied: chardet<5,>=3.0.2 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from requests) (4.0.0)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from requests) (1.26.5)

minha versão atual do python é essa:
Python 3.9.5

minha versão atual do pip é essa:
pip 21.1.2 from c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages\pip (python 3.9)

E esse é o código que estou tentando usar o comando e está dando erro:
import requests as r
from bs4 import BeautifulSoup

try:
    result = r.get('https://www.google.com.br/search?q=Python')

except Exception as err:
    print("Something went wrong: ",err)

else:
    response = result.text
    soup = BeautifulSoup(response,'html.parser')

    print(soup.title)
    print(soup.title.string)

If i try to install bs4 using the commanda pip3 install bs4 i get this messages:
Requirement already satisfied: bs4 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (0.0.1)
Requirement already satisfied: beautifulsoup4 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from bs4) (4.9.3)
Requirement already satisfied: soupsieve>1.2 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from beautifulsoup4->bs4) (2.2.1)

Não sei se isso ajuda de alguma forma mais o python 3.9 parece estar nesse caminho aqui
C:\Users\gabri\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9

Segue uma foto de como está configuradas as variáveis de ambiente
Comment: Poderia esclarecer qual IDE está usando para programar?
Comment: Estou usando o Thonny e também tenho o pycharm instalado
Comment: Em relação ao pycharm isto pode ser a causa do problema, porque o pycharm utilizar um virtualenv para o projeto (ele não compartilha o env com o sistema operacional), desta forma como instalou no S.O. pode estar faltando instalar no "env" da IDE.
Comment: Mas eu estava usando somente o Thonny para rodar os códigos. O pycharm eu instalei e nem usei mais. A ideia seria desinstalar o pychamr? Eu consegui resolver o problema colocando o arquivo que queria rodar o código dentro da pasta que o bs4 está, mas isso não pareceu a melhor forma de resolver o problema
Comment: Não conheço o Thonny, não sei como funciona. Me desculpe.
Comment: quais versões do python estão instaladas no teu pc (há a versão 2.7 ou 3.6) alem da  3.9?
Comment: Todo ide, possui no setting ou em outra especificação a escolha de qual interpretador sera usado, pode ter acontecido estar usando um versão padrão e não a que você instalou as libs, atribuindo isso o retorno do erro, o ide pode estar usando uma versão diferente, se for isso apenas altere qual  interpretador sera usando.
Comment: Era bem próximo disso. A ide estava usando o sys.path das pastas erradas, dessa forma, ela tentava importar os módulos de pastas diferentes das que eles estavam instalados. Como sou bem recente em programação, não fazia nem ideia disso, então muito obrigado pelas ajudas pessoal.
Answer: Com a ajuda do @stack.cardoso eu consegui encontrar uma resposta. Basicamente a minha IDE estava buscando o modulo bs4 em um path diferente do que ele estava instalado. Para resolver isso eu mudei o path que minha IDE buscava as importações nas proprias configurações da IDE. Agora ela está sempre buscando nas mesmas pastas que o pip instala os módulos. Para descobrir qual o path que a IDE estava usando eu digitei no console da iDE:
import sys
for sys in sys.path:
    print(sys)

Answer: Oi. Onde acho esse console, estou trabalhando com bs4 e dar erro, trabalhando com vscode, pelo terminal, e pasta PATH não acho, como busco? Ou que devo fazer
Erro mensagem de from bs4 nao existe
import requests
from bs4 import BeautifulSoup
Coletar a primeira página da lista de artistas
page = requests.get('https://web.archive.org/web/20121007172955/https://www.nga.gov/collection/anZ1.htm')
Criar o objeto BeautifulSoup
soup = BeautifulSoup(page.text, 'html.parser')


Taking first differences and then running PACF?

Question: If I first difference my non stationary time series data and then run a PACF to find the optimal lags to be 2 and 3 only, does this mean I found the best lags for my ORIGINAL data or only for my differenced data?
In other words, when I difference the data and run a PACF, are the results for my original data or for my differenced data, or for both? I'm having a hard time finding any information on this elsewhere. My goal is to understand my original data, not the differenced data. It's my understanding you can first difference the data and use all the results you get as estimates for your original data.
Comment: Granted that your code is correct and the 1st differences were passed to the PACF function, the ARI(2,1) or ARI(3,1) model appears appropriate for the original data, where 2 or 3 represent the number of autoregressive parameters and 1 represents the first difference.  Can you upload the PACF plot?

Did you also create an ACF to check if it tails off?  How about the EACF?
Comment: Thank you. I will simply create a question with much more detail. I didn't realize it was this complicated!
Answer: First, differencing is not a general remedy to non-stationarity. It's simply a way to factor out unit roots from the characteristic polynomial, such that the remainder implies stationary behavior. If you don't have a unit root, you should not difference.
Define the characteristic polynomial $\Phi(x) = 1-\phi_1 x - \ldots - \phi_p x^p$ to write an $AR(p)$ model as:
$$\Phi(L)Y_t = \varepsilon_t$$
$\Phi(x)$ has degree $p$ and so has exactly $p$ (possibly complex) roots. If one of those is 1 (a unit root), then you can use synthetic division to compute $\Phi'(x)$ such that:
$$\Phi(x) = \Phi'(x) (1-x)$$
$\Phi'(x)$ then has degree $p-1$. Going back to our $AR(p)$ process, we have:
$$\Phi(L)Y_t = \Phi'(L)(1-L)Y_t = \Phi'(L)\Delta Y_t = \varepsilon_t$$
That is, the differenced process follows an $AR(p-1)$ process with characteristic polynomial $\Phi'(x)$.
To answer your question more directly, if an $AR(2)$ process is appropriate for your differenced data, then a restricted $AR(3)$ process is appropriate for the original data; the restriction being that one of the roots of the characteristic polynomial is set to exactly one instead of being estimated freely. Differencing is just a trick for applying those restrictions.
I'm not sure what your last sentence ("first difference the data and use all the results you get as estimates for your original data") means, but consider this example. Say you use an $AR(2)$ model for your differenced data:
$$\Delta Y_t = \phi_1 \Delta Y_{t-1} + \phi_2 \Delta Y_{t-2} + \varepsilon_t$$
Replacing $\Delta Y_t$ by $Y_t - Y_{t-1}$ and collecting lags together, you find that:
$$Y_t = (1+\phi_1) Y_{t-1} + (\phi_2-\phi_1) Y_{t-2} - \phi_2 Y_{t-3} + \varepsilon_t$$
That is, the coefficients for the lag 1 and 2 are not the same for the original and differenced data.
Comment: My series have units roots as evidenced by an ADF test. My goal is to understand the original series and I was told if I first difference the data I can get an estimate of the beta coefficient so naturally I thought everything from my first differenced model would tell me about my original data, but clearly not from you me answer! I suppose it is better sometimes to just interpret the results from the first differenced model and interpret in terms of differences. Probably easier right?


Why we have elementary operations on matrix?

Question: I just started with matrices, so this might be the stupidest question I ever asked.

When we had to find the inverse of a matrix $A$, we write $A$ as $A = IA$ then we use elementary operations to convert $A$ on LHS to $I$.
The elementary operations I have been taught is $R_i \to kR_j$, $R_i \to R_j$ and $R_i \to R_i + kR_j$.
I want to know why we have only these operations and not something like $R_i \to R_i + 10$ ?
How did somebody came up this 3 operations ?
It would be nice if the answers are a little bit beginner friendly because I don't know much about linear algebra.
Comment: The reasoning behind these operations is that, if you consider the corresponding system of linear equations, the operations preserve the set of solutions.
Comment: Also, don't worry, this is not a stupid question. In fact, it's very good of you to think about the things you learn in this way - trying to get to know _why_ things are defined the way they are is a big part in trying to understand it.
Comment: @Wojowu Actually I don't know how linear equations and matrices are connected.
Comment: because  in mathematics it's only about construction, I don't see why the "why" would be anything good. Just implies you do not know (yet) how to deal with matrices. Once you reach that point feel free to explore others ways.
Answer: Computing with matrices is really within the domain of computer-based calculations. From this point of view the elementary operations you describe are the most basic things which can be done with the matrix as it would be stored as a data structure in a computer.
For instance take $R_j \rightarrow kR_j$. A computer can implement this quickly by pulling the registers being used to store the binary numbers in $R_j$ and performing bitwise operations to multiply them by $k$. Since this is the same process on each register, the computer can do it all in parallel if you program it right. The other two are similar.
From a practical standpoint, that's why the elementary operations are useful.
Now, onto the question of why they are elementary. If $V$ is a finite-dimensional linear space, any linear operator from $V$ to itself (for instance, change of coordinates, scaling, rotation) can be written as a square matrix. Since two square matrices of the same dimension yield a third of the same dimension, this also holds for the set of matrices on $V$ themselves regarded as a vector space. If a matrix is multiplied by another matrix, it can be regarded by taking linear combinations of the rows of the first and reading them into the rows of the result. Your elementary operations are all that is needed to construct any linear combination and read it into any row.

I want to know why we have only these operations and not something like    $R_i→R_i+10$?

This is a scalar being added to a vector -- you can't do that.
More generally, the reason these operations yield the matrix $A^{-1}$ is because each of them is an irreducible operation which, performed in the right order, send $A$ to $I$. Each operation has a matrix representation and the product of these operations is again a matrix (of the reasons stated above). This matrix must be the inverse, since multiplying it by $A$ gives the identity.
Comment: You said that every row is a vector then can I do cross multiplication   with them ? Like $R_i \to R_i \times R_j$.
Comment: Thank  you for the answer.
Comment: Remember that the cross product is only three dimensional. In the case of a $3\times 3$ it is possible, but I am not sure it would have any meaning.
Comment: Maybe I can use it to find the inverse quicker than with these three operations.
Comment: Sounds like a google search / term paper :-)
Comment: What is a term paper ?
Answer: These operations are called elementary row operation because they are the more simpler three operations  with which  we can construct all the invertible matrices starting from the identity matrix (and that can be represented by a matrix multiplication as you will see later).
Comment: What are the other three operation called ? I want to search them.


I am not able to save image in external storage in android

Question: My logcat is as follow pls help me
4-21 01:29:26.288 21536-21536/? I/art: Late-enabling -Xcheck:jni
04-21 01:29:26.324 21536-21536/? D/TidaProvider: TidaProvider()
04-21 01:29:26.331 21536-21536/? W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
        at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
        at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
        at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
        at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
        at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
        at android.os.Looper.prepareMainLooper(Looper.java:111)
        at android.app.ActivityThread.main(ActivityThread.java:5584)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
04-21 01:29:26.363 21536-21536/? W/ResourceType: No package identifier when getting name for resource number 0x00000000
04-21 01:29:26.373 21536-21536/? W/System: ClassLoader referenced unknown path: /data/app/com.example.quotescreator-2/lib/arm64
04-21 01:29:26.410 21536-21536/? W/ResourceType: No package identifier when getting name for resource number 0x00000000
04-21 01:29:26.422 21536-21536/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-21 01:29:26.454 21536-21536/? D/AccessibilityManager: current package=com.example.quotescreator, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=false, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
04-21 01:29:26.480 21536-21536/? I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
04-21 01:29:26.481 21536-21536/? I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
04-21 01:29:26.604 21536-21579/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-21 01:29:26.714 21536-21579/? I/Adreno: QUALCOMM build                   : 10c9f68, I74772a33ad
    Build Date                       : 02/07/17
    OpenGL ES Shader Compiler Version: XE031.07.00.01
    Local Branch                     :
    Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.5.1_RB1.06.00.01.192.038
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
04-21 01:29:26.761 21536-21579/? I/OpenGLRenderer: Initialized EGL, version 1.4
04-21 01:29:28.493 21536-21536/com.example.quotescreator I/Timeline: Timeline: Activity_launch_request time:18521828
04-21 01:29:29.956 21536-21536/com.example.quotescreator D/path: /data/user/0/com.example.quotescreator/app_imageDir/UniqueFileName.jpg
04-21 01:29:41.239 21536-21536/com.example.quotescreator I/Timeline: Timeline: Activity_launch_request time:18534574
04-21 01:29:41.829 21536-21579/com.example.quotescreator D/OpenGLRenderer: endAllStagingAnimators on 0x559e61e8e0 (InsetDrawable) with handle 0x559e5cda60
04-21 01:30:55.099 21536-21536/com.example.quotescreator W/IInputConnectionWrapper: getExtractedText on inactive InputConnection
04-21 01:30:55.125 21536-21536/com.example.quotescreator W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection

// This is my code
    public void SaveImage(View view) {
            // coneverting relative layout in image  to save as we have to save image with text written
            // on it i.e we have to save the whole layout
            Bitmap bitmap = Bitmap.createBitmap(relativeLayout.getWidth(), relativeLayout.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            relativeLayout.draw(canvas);
            ContextWrapper cw = new ContextWrapper(getApplicationContext());
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            File file = new File(directory, "UniqueFileName" + ".jpg");
            if (!file.exists()) {
                Log.d("path", file.toString());
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (java.io.IOException e) {
                    e.printStackTrace();
                }
            }

        }

Answer: Are you sure that you have already checked if the user has granted permission to external storage or not?
Then try this one (your code does not work for 20 API levels and above):
private void saveImageToExternalStorage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
    file.delete();
try {
    FileOutputStream out = new FileOutputStream(file);
    finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    out.flush();
    out.close();
}
catch (Exception e) {
    e.printStackTrace();
}

// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
        new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Log.i("ExternalStorage", "Scanned " + path + ":");
                Log.i("ExternalStorage", "-> uri=" + uri);
            }
});

}

thx from Yar


Android textDirection anyRtl not working for English text

Question: I need an EditText box that shows the entered text (English) from right to left.
So if the user enters the word "him" on the keyboard, the EditText should show the following - first "h" then "ih" and finally "mih".
I thought android:textDirection="anyRtl" would achieve the same. I'm on API level 22.
But it doesn't seem to be working. This is my EditText code:
<EditText
    android:id="@+id/editText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:textDirection="anyRtl"
    android:gravity="right"
    android:fontFamily="@font/digital"
    android:minEms="7"
    android:maxLength="10"
    />

Any reason why rtl or anyRtl isn't working. Am I misunderstanding how it works? How can I achieve my required use-case?
Comment: Is this for arabic ?
Comment: Hi Indra, it's for English. I've edited the question.
Comment: Do you want to reverse the words [English] in EditText ?
Comment: @SirosBaghban hey so whatever he enters should be prepended to the EditText text instead of appended.
Answer: Through Android document:

If the text contains any strong right to left non-format character, determines that the direction is right to left, falling back to left to right if it finds none.

Your input 'him' is obviously an English word, which contains no RTL character.
In your case, I think that you may choose "rtl" or "locale".
Seeing: https://developer.android.com/reference/android/text/TextDirectionHeuristics.html


What characteristics of the distribution of a test statistic can be inferred using a bootstrap?

Question: UPDATE 06/2020: I just revisited this question and realised that there is a fairly clear cut answer. Specifically, the required condition is uniform integrability. Basically the class of functions of the distribution that are uniformly integrable can be in inferred using a bootstrap. Without uniform integrability, all bets are off. I'm fairly sure, although can't remember off the top of my head, that there is theorem in one of Brillinger's textbooks for exactly this situation.
Setup: Let $p_n(x) = \mathbb{P}(S_n \leq x)$ and let $p_n^*(x) = \mathbb{P}^*(S_n^* - S_n \leq x)$, where $S_n$ is some zero-mean test statistic that can validly be bootstrapped, eg a sample mean, and $S_n^*$ is a bootstrap re-sample of $S_n$. Note that $\mathbb{P}^*$ implies the probability is conditional on the underlying data. Assuming the conditions of some bootstrap theorem, eg stationary bootstrap, are fulfilled, we have the main bootstrap result:
\begin{equation}
\sup_{x \in \mathbb{R}} | p_n(x) - p_n^*(x)| \overset{\mathbb{P}}{\rightarrow} 0, \: \textrm{as} \: n \rightarrow \infty
\end{equation}
My question has two parts:
Question 1: The main bootstrap result is usually used to assert that bootstrapped confidence intervals are asymptotically valid. Can we make this assertion because of Slutsky's theorem? If so, why isn't continuity an issue?
Currently, my understanding is that the argument works as follows:
1) For some fixed point $x \in \mathbb{R}$, we use the above result to assert that $p_n^*(x) \overset{\mathbb{P}}{\rightarrow} p_n(x)$, as $n \rightarrow \infty$.
2)Use Slutsky's theorem to assert that $g(p_n^*(x)) \overset{\mathbb{P}}{\rightarrow} g(p_n(x))$, as $n \rightarrow \infty$, for some Borel function $g(a)$ that is continuous at $a$.
3) Choose $g(a)$ to be the quantile function, ie $g(F(x)) = \inf \{ x \in \mathbb{R} : \lambda \leq F(x) \}$ where $F(x)$ is a cdf and $\lambda \in (0, 1)$. The result then follows.
The problem with this argument as it stands is that, for general cdf functions, the quantile function is only guaranteed to be left continuous. I'm assuming that we get around this problem by exploiting the fact that $p_n(x)$ and $p_n^*(x)$ are both converging to the Normal, which has a continuous cdf, but I've never seen this stated formally anywhere, so I am wondering if my reasoning is actually correct.
Question 2: Having established that we can build asymptotically valid confidence intervals, I'm wondering what other characteristics of the distribution of $S_n$ we can consistently estimate?
I know that most bootstrap theorems also include a result of the form $\mathbb{V}^*S_n^* \overset{\mathbb{P}}{\rightarrow} \mathbb{V} S_n$, as $n \rightarrow \infty$, so that takes care of the variance. What about other moments? For example, can we infer from the main bootstrap result that $\mathbb{E}^* S_n^{*4} \overset{\mathbb{P}}{\rightarrow} \mathbb{E} S_n^4$, as $n \rightarrow \infty$? As in the case of confidence intervals, I tried to prove this using Slutsky's theorem, but was not comfortable with the resulting expression:
\begin{equation}
\int x^4 dp_n^*(x) \overset{\mathbb{P}}{\rightarrow} \int x^4 dp_n(x), \: \mathrm{as} \: n \rightarrow \infty ,
\end{equation}
since it is not clear to me that we are not accumulating lots of "small" errors in the integral.
EDIT: I asked the question here since it is about the bootstrap. However, since it is also about probability theory, if users feel it would be more appropriate in stack exchange mathematics, please let me know.
Comment: Assuming that the actual sampling distribution converges uniformly in n to the true sampling distribution, then any function of this distributoion will also converge, since you can bring the limit under the integral in the functional via uniform convergene theorem.
Comment: I think almost any statstical functional can be validly boostrapped, with varying levels of confidence and precision. A key requirement is uniform convergence of the boostrap distribution for a statistic to the actual statistic. Also, jacknife-after-boostrap diagnostics can be done to determine how robust your statistic is.
Comment: @Eupraxis1981 Thanks for the comment. Do you know of a formal proof, or reference to one? I've read a fair bit of the literature on this, eg Efron (1979), Politis and Romano (1994), Lahiri (2003), and no-one ever really offers a formal proof of convergence of characteristics of the distribution, other than the main result I mention in the question, which only covers convergence of the cdf at a given fixed point. Perhaps I'm being a bit dense, but I just don't see how it is obvious that this extends to convergence of other characteristics of the distribution, such as moments.
Comment: @Eupraxis1981 Thanks, that definitely got me reading in the right direction. One minor point still worries me. My reading of the uniform convergence theorem suggests that it is used when the function in question is the *integrand*. But in my example above, $p_n^*(x)$ is the *integrator*. Does the theorem still apply in this situation? I can see that it should if $p_n^*(x)$ is everywhere differentiable, but that condition may not hold for general cdf's. If you can respond to this and turn it into an answer, I'll tick and upvote. Thanks.
Comment: I've posted an answer based on our exchange. I think the mention of the uniform convergence theorem took this too far afield. There are much simpler reasons why you can calculate almost any other statistic of the sampling distribution using bootstrapping.
Comment: Also, a good book on applied boostrap that I rely on is "Bootstrap Methods and Their Applicatoin" by Davison and Hinkley. They go into some of the theoreticals, but not too dense.
Answer: The essense of the nonparametric boostrap method is to use the EDF as if it were the true distribution and then perform monte carlo sampling/analysis to the EDF. Therefore, as long as the EDF is a good representation of the true CDF, the boostrap sampling distribution will be a good approximation of the true sampling distribution, and hence any statistics dervied from this approximate sampling distribution will be apprximately correct to the degree that your original data accurately depict the true underlying distribution. Hence, as the sample size gets bigger, both the EDF and the associated sample statistics converge to the true values. The convergence therorem I cited is useful for continuous functions, but its really not needed. All we need to know is that as the sample size gets bigger, the statistical error in treating the EDF as the CDF approaches zero by the law of large numbers. Therefore, simulation from this estimated distribution converges to simulation from the true distribution as the sample size grows.
The major caveat to this is when your sampling statsistic does not uniformly converge to the true value, with maximial order statsitics being a classic example.
Therefore, the answer to your question is that any quantity of your sampling distribution can be estimated from the boostrap sampling distribution as long as the bootstrap sampling distribution itself converges uniformly to the true sampling distribution. Below are some links, some of which contain further links to very interesting papers, on when this condition is not met.
This paper will also be interesting for you. the encyclopedia of mathematics has a good entry on boostrap failure as well. This has also been discussed previously on Cross validated: What are examples where a "naive bootstrap" fails?


converter string para double elasticsearch

Question: olá, pessoal to precisando de uma ajuda com elasticsearch.
estou tentando fazer uma conversão por script,  de um campo string, para double, mas infelizmente, não estou conseguindo. o ultimo script que fiz foi esse:
def cod=0;  if(String.valueOf(doc['codProduto.keyword'].value)!=null){ String sCod = doc['codProduto.keyword'].value; cod = Double.parseDouble(sCod);} return cod;

porem retorna esse erro
"caused_by" : {
            "type" : "illegal_state_exception",
            "reason" : "A document doesn't have a value for a field! Use doc[].size()==0 to check if a document is missing a field!"
mas se eu fizer o script dessa forma:
def cod=0;  if(doc['codProduto'].size()>=0){ String sCod = doc['codProduto.keyword'].value; cod = Double.parseDouble(sCod);} return cod;

retorna esse erro:
**
"Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [codProduto] in order to load field data by uninverting the inverted index. Note that this can use significant memory."
**
Answer: Consegui resolver, então estou postando a resposta, caso alguem precise
"int cod = 0; if(doc['codProduto.keyword'].empty){return 0;}else{cod = Integer.parseInt(doc['codProduto.keyword'].value);} return cod;"


Can Mono run Windows universal apps?

Question: I'm writing a universal app by using windows 10, visual studio 2015 and C#. I would like to run this app on windows, Linux and mac. I know mono doesn't implements windows presentation framework, so, if I write a WPF app it runs onluy on windows. Now, if I write a universal app, can mono run that? If yes, how?
Answer: The holy grail .Net UI question :-)
TL;DR Answer = No.
Universal Windows Platform (UWP) core APIs (also known as Windows Runtime / WinRT) and the resulting APPX based applications only target Windows 10 platforms (Phone, PC, Tablet...) as those APIs and runtime do not exist on the other desktops.
Using Xamarin/Mono you could reuse a portion of the C# app's 'business' level logic but the presentation layer and GUI logic would have to be re-written using a different GUI (Native Widgets, GTK#, QTSharp, HTML/CSS/NodeJs, etc...). Same model that people have been using Xamarin for C# based mobile development applies, share your C# app logic across platforms and use Xamarin.Mac to build a native OS-X UI, and/or build a UI using GTK#, embed your app's runtime logic into a Electron/Blink shell, etc..
Currently the Windows 10 for Apache Cordova project which is HTML, JavaScript, and CSS, only targets Mobile (WinPhone, iOS, Android) and Windows 10 PC/Tablet platforms. That is not to say someone could not develop a new Cordova target to include OS-X and Linux desktop manager support (but I do not know of any that have not already stalled) :-/
Even Microsoft's xplat-based Visual Studio Code for Linux and OS-X uses Electron (Chromium based) to deploy the io.js based application along with the Blink layout engine to render the UI, all done in HTML/CSS/JS.

Can Mono run Windows universal apps?


Simulating random variables from a discrete distribution II

Question: I have the following discrete probability distribution where $p$, $q$ and $r$  are known constants:
$P(X=0)=q$, $0<q<1$
$P(X=1)=1-p-q-r$, $0<p+q+r<1$
$P(X=2)=p$, $0<p<1$
$P(X=3)=r$, $0<r<1$
How can I sample from this distribution?
Answer: To generate $n$ independent values from this distribution, you can use:
sample(0:3, size = n, replace = TRUE, prob = c(p, 1-p-q-r, q, r))

For example, here we generate $n=10^6$ values and show the sample proportions:
#Generate a large number of values from this distribution
set.seed(1)
p <- 0.11
q <- 0.20
r <- 0.35
n <- 10^6
X <- sample(0:3, size = n, replace = TRUE, prob = c(p, 1-p-q-r, q, r))

#Show sample proportions
table(X)/n

X
       0        1        2        3
0.109570 0.340265 0.200222 0.349943

Comment: How do you do this in SPSS? You may be able to create an SPSS syntax file with the sps extension.
Answer: There is a quite simple strategy for discrete distributions such as this with small number of elements in the support:
u <- generate a uniform RV in [0,1]
if u < q: x <- 0
elseif u < 1-p-r: x <- 1
elseif u < 1-r: x <- 2
else x <- 3

This is basically an over simplification of Inverse Transform Sampling.
Comment: Now I understood. With p = 0.05, q = 0.03 and r = 0.01 in SPSS the syntax is: COMPUTE U=RV.UNIFORM(0,1).
RECODE U (0.0 thru 0.03=0) (0.03 thru 0.94=1) (0.94 thru 0.99=2) (ELSE=3).
EXECUTE.
Comment: @ gunes Thanks a lot for all your help.
Comment: How do you do this in SPSS? You may be able to create an SPSS syntax file with the sps extension.
Comment: I don't know SPSS. But, it's so simple that you should be able to implement it in almost every language you're familiar with.
Comment: Which programming language did you use?
Comment: My answer is pseudo-code. Ben has written it in R.
Comment: @AdvanderVen yes, that seems correct.
Comment: @AdvanderVen if you find the answers useful, can you please accept and/or upvote it/them?
Comment: I do not know how to do this.
Comment: @AdvanderVen to accept it, you'll click the tick under the arrow next to the answer you want to accept. And if you want to upvote it as well, you'll click the arrow pointing towards upwards which you can do it for any answer.


Permission page broken

Question:
All other pages are being loaded fine but when I go to permissions page it comes like this. What may be the reason for this ? Please help.
Comment: I tried in different browsers and also cleared the cache. Still getting the page like that.
Answer: I had exactly the same problem few days ago.
Do you have the devel module install?
For me it was the problem, i can't explain why but when i desintalled it, all worked fine.
So maybe, try to desactivate and unistall it and maybe your page permission will work again.
PS: i just re-install the devel module to make a test and i have exatly the same permission page than you. For me it's the devel module the problem. (I'm new in Drupal so i had certainly make a mistake somewhere)
Comment: Oh you are right. Uninstalling devel module solved the problem for now :). But we should also look for the permanent solution.
Answer: This could probably be a PHP Memory Limit issue. Is this only happening on your local / dev or also on your remote server?
Comment: I have not uploaded to remote server yet.Still developing. If PHP memory is issue , how to solve it ?
Comment: Run a phpinfo() (or use the devel module /devel/phpinfo) to see how much memory you have. Its the memory_limit value. TO increase, you need to set another value in the php.ini or ask your hoster.
Comment: @Lance- I increased the memory limit from 128 to 256 in /etc/php5/apache2/php.ini . But still showing the problem when I install devel module. Any other reasons for this problem that you know ? Is the php.ini file that I edited was correct or I should get the file somewhere else ? I need to solve the problem permanently. Thank you.
Answer: I have the exact problem noted above, but after checking my modules, I do not have devel installed.  Are there any other solutions to this issue out there?
Answer: May be the permission listing makes the memory problem.You have to update the permission listing page to a simple one.
Try the Filter permissions module
Comment: How would this module help, exactly?
Comment: There may be lots of user roles within the app. While loading all the permission together may cause the page break..
Comment: This module will let you select each role with many types. All to All is also possible too
Comment: Please edit your answer to provide details. Comments are for more "side" tasks, like asking for claifications ot notifying they were made.

Permission page broken


Table height is not working in react bootstrap

Question: I am using react-bootstrap components. I have a table covered by a div. The table has six rows. I have added height to my div, but table is not sized according to height.
I need the table to fit inside the div, and the table header should be fixed and table body content should scroll.
UI Looks like this below

It overflows in the div. I tried applying height and scroll. But it's not working.
Here's the Code I tried:
import Table from "react-bootstrap/Table";
import "bootstrap/dist/css/bootstrap.min.css";

export default function App() {
  return (

            #
            First Name
            Last Name
            Username

            1
            Mark
            Otto
            @mdo

            2
            Jacob
            Thornton
            @fat

            3
            Mark
            Otto
            @mdo

            4
            Jacob
            Thornton
            @fat

            5
            Mark
            Otto
            @mdo

            6
            Jacob
            Thornton
            @fat

  );
}

I don't know how to make it. Please help me with some solutions.
Code SandBox Link: https://codesandbox.io/s/agitated-hamilton-qh1eh5?file=/src/App.js
Answer: Based on the current CSS you have given, it should be fixed by placing an overflow-y: scroll to your container div. Since the styling is done as inline javascript, you must write it as overflowY: "scroll".
EDIT: Since the actual question was about getting it fixed, you need to add position: sticky and top:0 to the table header (and background color, otherwise it's transparent), and the previous overflowY: scroll should be overflowY: auto instead. Here is the result for that:

import "./styles.css";
import Table from "react-bootstrap/Table";
import "bootstrap/dist/css/bootstrap.min.css";

export default function App() {
  return (

            #
            First Name
            Last Name
            Username

            1
            Mark
            Otto
            @mdo

            2
            Jacob
            Thornton
            @fat

            3
            Mark
            Otto
            @mdo

            4
            Jacob
            Thornton
            @fat

            5
            Mark
            Otto
            @mdo

            6
            Jacob
            Thornton
            @fat

  );
}
Comment: I added overflow-Y, it still not working. codesandbox link:  https://codesandbox.io/s/agitated-hamilton-qh1eh5?file=/src/App.js
Comment: I have added a solution, it works on your CodePen.
Comment: Thanks. But I want the header to be fixed, only table content should scroll
Comment: This is an entirely different issue and should be informed in the post.
Comment: New edited answer above
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/249702/discussion-between-erecodes-and-bovop4).
Answer: Here in documentation, https://react-bootstrap.github.io/components/table/#always-responsive

Across every breakpoint, use responsive for horizontally scrolling tables.

Have you tried adding responsive in Table?

import Table from "react-bootstrap/Table";
import "bootstrap/dist/css/bootstrap.min.css";

export default function App() {
  return (

                    <--------

            #
            First Name
            Last Name
            Username

        .....

)}

Comment: Ya. I have added that. Its not working. Code sandbox link: https://codesandbox.io/s/agitated-hamilton-qh1eh5?file=/src/App.js


null cannot be cast to non-null type kotlin.collections.List

Question: Most of my app users don't experience any crashes. However, some of my app users are getting this fatal exception:
Fatal Exception: java.lang.NullPointerException: null cannot be cast to non-null type kotlin.collections.List<com.android.billingclient.api.Purchase>
       at com.company.appname.ActivityClass$loadAllSKUs$1.onSkuDetailsResponse(ActivityClass.java:10)
       at com.android.billingclient.api.zzj.run(zzj.java:7)
       at android.os.Handler.handleCallback(Handler.java:873)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:226)
       at android.app.ActivityThread.main(ActivityThread.java:7178)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:503)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:942)

Here is my code. I use it to see if a user has already bought an in-app purchase. If he didn't, launch the billing flow.
  private lateinit var billingClient: BillingClient
  private val skuList = listOf("product")
  private boolean isOwned = false

  private fun loadAllSKUs() {
    if (billingClient.isReady)
    {
      val params = SkuDetailsParams.newBuilder()
              .setSkusList(skuList)
              .setType(BillingClient.SkuType.INAPP)
              .build()
      billingClient.querySkuDetailsAsync(params) { billingResult, skuDetailsList ->
        if (skuDetailsList != null)
        {
          if (billingResult.responseCode === BillingClient.BillingResponseCode.OK && !skuDetailsList.isEmpty())
          {
            for (skuDetailsObject in skuDetailsList)
            {
              val skuDetails = skuDetailsObject
              if (skuDetails.sku.equals("product"))
              {
                val result: Purchase.PurchasesResult = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
                val purchases: List<Purchase> = result.getPurchasesList() as List<Purchase>

                for (purchase in purchases)
                {
                  val thisSKU = purchase.sku
                  if (thisSKU == "product")
                  {
                    isOwned = true;
                    // System.out.println("OWNED")
                  }
                }

if(isOwned == false){
                    val billingFlowParams = BillingFlowParams
                            .newBuilder()
                            .setSkuDetails(skuDetails)
                            .build()
                    billingClient.launchBillingFlow(this@ActivityClass, billingFlowParams)
}
              }
            }
          }
        }
      }
    }
  }

Please tell me how to fix this, thanks. This question gets the same error but a fix has not been found apparently.
Comment: `result.getPurchasesList()` is null and you are casting it to non null type `List` which is causing the issue
Comment: @NongthonbamTonthoi I understand. But, why is this happening on some devices and not all of them? And how can I fix this issue? Thanks.
Comment: "why is this happening on some devices and not all of them" can't be answered without knowing the API you are dealing with. "how can I fix this issue?" This depends on: 1. Why are you casting (`as List`) in the first place? 2. what do you want to do if you get `null` there?
Answer: As it was said, the error points to the forced cast of result.getPurchasesList()
You need to check for that case and capture more data on what it returns and why, when your application is in that state.
As for the answer above and the error on  Unresolved reference: it, to use takeIf you must pass a predicate so you have to change those parentheses to {}
    billingClient.takeIf{it.isReady}?.let {

Check https://medium.com/mobile-app-development-publication/using-kotlin-takeif-or-takeunless-c9eeb7099c22
Comment: Do you think the answer above solves the `result.getPurchasesList()` error?
Comment: yes sorry, I've edited the code manually and I didn't notice :D
Answer: Kotlin is a lot more expressive than a lot of cascading if...
Also, Kollin handles nullity at compile time so IDE should notify you if is null or not.
I tried to rewrite your code because is very undebuggable.
I honestly don't know if it works and if it does the same things (it should but as i saidall those if are difficult to understand) but I find it more readable and debuggable.
Remember that in order to remove all if !=null you can use ?. operator
Hope it helps you to understand Kotlin expressivity
private fun loadAllSKUs() {
    billingClient.takeIf{it.isReady}
    ?.let {
    val params = SkuDetailsParams.newBuilder()
            .setSkusList(skuList)
            .setType(BillingClient.SkuType.INAPP)
            .build()
    billingClient.querySkuDetailsAsync(params) { billingResult, skuDetailsList ->
    skuDetailsList
        ?.takeIf{ billingResult.responseCode === BillingClient.BillingResponseCode.OK && skuDetailsList.isNotEmpty() }
        ?.filter {it.sku.equals("product")}
        ?.forEach { skuDetails ->
            val result: Purchase.PurchasesResult = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
            val purchases: List<Purchase>? = result.getPurchasesList() as? List<Purchase>
            val isOwned = purchases?.any { it.sku == "product" }?:false

            if(!isOwned){
                val billingFlowParams = BillingFlowParams
                        .newBuilder()
                        .setSkuDetails(skuDetails)
                        .build()
                billingClient.launchBillingFlow(skuDetails@ActivityClass, billingFlowParams)
                }
            }
        }
    }

Comment: The code is neater but I don't think it solves the issue I'm encountering on some devices.
Comment: A comment said that it's because `result.getPurchasesList()` is null and I'm casting it to non null type `List`
Comment: Also, I get `Unresolved reference: it` in the 2nd line
Comment: I've edited the snippet with a cast to null for List

I think you should look into Kotlin lang reference https://kotlinlang.org/docs/reference/


What permissions are required for enumerating users groups in Active Directory

Question: I have a .net web application which needs to obtain the groups a user is a member of in Active Directory.
Todo this I am using the memberOf attribute on the users records.
I need to know the permissions required to read this attribute on all users records.
Currently I am getting inconsistent results when trying to read this attribute. For example I have a user group of 30 users in the same OU path. Using my own credentials to query AD - I can read the memberOf attribute for some users but not others. I know all the users have a memberOf attribute set as I have checked when logged on with a domain admin account.
Answer: On your domain object, you need to assign the querying user the "Read MemberOf" right to User objects.

Open AD U&C browse to your domain object
Right click and go to properties:
(source: sysadmin1138.net)
Security tab, click Advanced
Click Add
Enter the user name to add
Click the Properties tab
In 'Apply Onto' change the type to User
Click the "Read MemberOf" checkbox:
(source: sysadmin1138.net)
OK out of there

That should set it up so that the specified account can read the group memberships of all User accounts in the domain.
Comment: Ah, that's it. Go to View  and select Advanced Features. It'll show up once that's turned on. I always have that on so I forget that it's there :}
Comment: Thanks sysadmin - I still cannot see a security tab when clicking properties on my test domain (its a server 2003 vm - set up by me.. a developer :P so could be wrong).. heres a picture of the properties screen I see. http://tinypic.com/r/10p7cdy/4
Comment: FWIW, this does not seem to apply to Windows Server 2012 where the Add dialog is quite different.
Comment: For the benefit of any users on Server 2008R2, these instructions are equally applicable, but the property tab is slightly different than what is described/pictured. The setting is labeled "Apply to:" and the correct value is "Descendant User Objects". All other instructions remain the same.
Comment: Many, many permissions... http://sysadmin1138.net/images/ldap-read-member-of.png
Answer: I had a similar issue and solved it on another level with a request to the AD:
<code>(&(objectClass=group)(objectClass=top)(member=UserDN))
</code>
for the "dn" attribute.
As groups are readable by default, this will return an equal result to the "membersOf" property.
I know this is not really an answer to the permission question, but i landed here searching for a way to get the memberOf property without a permission-change in AD.


linking G Suite and Windows Domain Controller for user management

Question: I manage a small business and use G Suite for user management of all google apps as well as authentication for as many third party services as possible (like slack, atlassin and so on).
Then we also have an intranet with internally hosted services where I use a Windows Server Domain Controller with AD to manage users and use LDAP to authenticate users on all the internally hosted services in the intranet.
So currently I have to manage all user profiles twice, once for the intranet through the windows DC and once for all the cloud services we use through G Suite.
Now afaik G Suite can't act as a DC, so it can't replace AD. But I wonder whether there's a way to link our local DC with G Suite to sync accounts and permissions. Optimally I'd manage all the user accounts only through G Suite.
Is there some way to do this?
If not, what's the best way to have only a single user account which can be used for internal services as well as for various cloud subscriptions?
Answer: There is Google Cloud Directory Sync (actually the first Google result for gsuite ad sync!):

With Google Cloud Directory Sync (GCDS), you can synchronize the data
  in your Google domain with your Microsoft® Active Directory® or LDAP
  server. Your Google users, groups, and shared contacts are
  synchronized to match the information in your LDAP server.

However, this synchronizes from AD to G Suite, so you'd have to manage your G Suite users through AD, not the other way around.


Auto scroll on woocommerce

Question: i work on a project with woo.
On the mobile version of the site, the cart is a popup window.
When the customer adds many different products he must scroll down to see the buttons "view cart" "pay".
I try to add an autoscroll js code. When someone opens the cart it must scroll down automatically and stops at buttons "view cart" "pay".
I found some codes for "autoscroll to div" but none of them worked for me.
One simple js code i play with is this
$('#start').click(function() {
$('html,body').animate({
    scrollTop: $('#bodycontainer').position().top
}, 1000 );});

but nothing happened.
Any help?
Thanks
Answer: You are trying to scroll the wrong thing, if it is the container that has the scroll. Replace it with this:
$('#start').click(function() {
$('#bodycontainer').animate({
   scrollTop: 10000
}, 1000 );});

Now if you aren't using a container, then you may wish to add one.
Answer: I totally confused
My code for mini-cart is this
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

global $woocommerce;
?>

<?php do_action( 'woocommerce_before_mini_cart' ); ?>

<div class="cart_list <?php echo esc_attr( $args['list_class'] ); ?>">

    <?php if ( ! WC()->cart->is_empty() ) : ?>

        <?php
            foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
                $_product     = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
                $product_id   = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );

                if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_widget_cart_item_visible', true, $cart_item, $cart_item_key ) ) {

                    $product_name  = apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key );
                    $thumbnail     = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );
                    $product_price     = apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key );
                    $product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key );
                    ?>

                            <a href="<?php echo esc_url( $product_permalink ); ?>" class="image pull-left">
                                <?php echo trim($thumbnail); ?>

                                <a href="<?php echo esc_url( $product_permalink ); ?>">
                                    <?php echo trim($product_name); ?>

                                <?php echo wc_get_formatted_cart_item_data( $cart_item ); ?>
                                <?php echo apply_filters( 'woocommerce_widget_cart_item_quantity', '' . sprintf( '%s × %s', $cart_item['quantity'], $product_price ) . '', $cart_item, $cart_item_key ); ?>

                            <?php
                            echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf(
                            '×',
                                esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
                                __( 'Remove this item', 'opal_drop' ),
                                esc_attr( $product_id ),
                            esc_attr( $cart_item_key ),
                                esc_attr( $_product->get_sku() )
                            ), $cart_item_key );
                            ?>

                    <?php
                }
            }
        ?>

    <?php else : ?>

<?php esc_html_e( 'No products in the cart.', 'opal_drop' ); ?>

    <?php endif; ?>

<?php if ( ! WC()->cart->is_empty() ) : ?>

<?php esc_html_e( 'Subtotal', 'opal_drop' ); ?>: <?php echo WC()->cart->get_cart_subtotal(); ?>

    <?php do_action( 'woocommerce_widget_shopping_cart_before_buttons' ); ?>

        <a href="<?php echo esc_url(wc_get_cart_url()); ?>" class="btn view-cart btn-default pull-left wc-forward"><?php esc_html_e( 'View Cart', 'opal_drop' ); ?>
        <a href="<?php echo esc_url( wc_get_checkout_url() ); ?>" class="btn check-out btn-primary text-white pull-right checkout wc-forward"><?php esc_html_e( 'Checkout', 'opal_drop' ); ?>

<?php endif; ?>

<?php do_action( 'woocommerce_after_mini_cart' ); ?>

and i try this
jQuery(document).ready(function($){
                    if ( $(window).width() < 768 || window.Touch) {
                        $('html, body').animate({
        scrollTop: $("#cart-main-content .media-body").offset().top
    }, 2000);
                    }
});

With no luck. Now i practise with jquery

Auto scroll on woocommerce


Retrieve data from jQuery Object

Question: I am having problems with my jQuery object which I recieve from Ajax function.
console.log(data) ==> dumps {"isUnique":true}

and
console.log(data.isUnique) ==> dumps undefined

How should I get these "isUnique" data?
Code
Js:
$.ajax({
       type: "POST",
       async: false,
       url: ...some url ,
       data: { 'email' : value },
       dataType: "text",
       success: function(data){
             console.log(data);
             console.log(data.isUnique);
       }
 });

Comment: Can you paste the raw response here? Also the code you are using for the request.. Thanks!
Comment: Maybe `data` is still a string, and not a javascript object? Because otherwise, this works just fine. See http://jsbin.com/qonutemedo/edit?js,console
Comment: var s = data.isUnique   or   var s = data["isUnique"]
Comment: I assume that your data is a string and not a javascript object.
Comment: Please show full context of where these logs are done in request.
Comment: Have you set the dataType of yout ajax-call to `json`?
Answer: It sounds as you're getting a JSON. You can use parseJSON.
var obj = jQuery.parseJSON(data);
var myValue = obj.isUnique;

As mentioned by charlietfl in the comments, you can easily avoid this by manually setting dataType in the request.

The type of data that you're expecting back from the server. If none
  is specified, jQuery will try to infer it based on the MIME type of
  the response (an XML MIME type will yield XML, in 1.4 JSON will yield
  a JavaScript object, in 1.4 script will execute the script, and
  anything else will be returned as a string).

...

"json": Evaluates the response as JSON and returns a JavaScript
  object. Cross-domain "json" requests are converted to "jsonp" unless
  the request includes jsonp: false in its request options. The JSON
  data is parsed in a strict manner; any malformed JSON is rejected and
  a parse error is thrown. As of jQuery 1.9, an empty response is also
  rejected; the server should return a response of null or {} instead.
  (See json.org for more information on proper JSON formatting.)

$.ajax({
    type: 'post', // or 'get' if you prefer.
    url: 'your_url',
    dataType: 'json',
    success: function(data){
        alert(data.isUnique);
    }
});

var obj = jQuery.parseJSON( '{"isUnique":true}' );
alert( obj.isUnique);

Comment: No need for this when use proper `dataType` for the request
Comment: @charlietfl - Yes, very true. The answer is based on the first information given by the OP.  I'll update my answer.
Answer: Your dataType is incorrect
Change
dataType: "text",

To
dataType: "json",

This will tell jQuery to parse the response to an object from string internally
Comment: Also never use `async:false`. It is terrible practice and you should see deprecation warning in your browser console.
Comment: It completely blocks everything in the page until request completes. Just don't use it. Cause bad user experience
Comment: Yea... that's why this happend. This answer is better than the last one :) thank you
Comment: What is this used for? I've just deleted it and my Ajax loading goes more fluently then before! :)
Comment: Yea! I could not write while loading. Tyvm, op answer :)

Retrieve data from jQuery Object


Code will loop itself three time and runs "If" statement twice and "Else" statement once

Question: i do not know why but this bit of code repeats itself 3 times when adding "questionwords" in the message, specifically it will run the else statement one and the main if statement twice.
bot.on('message', function(message) {
    const words = message.content.split(' ');

    if (words.includes('sans')) {
        var questionwords = ['can', 'is', 'was', ];

        for (i in questionwords)
            if (!words.includes(questionwords[i])) {
                if (message.author.bot) return;
                var chance = Math.floor(Math.random() * 2);

                if (chance == 0) {
                    message.channel.send('<:annoying_sans:520355361425981440>');
                }

                if (chance == 1) {
                    message.channel.send('<:sans:519723756403425294>');
                }
            } else {
                var chance = Math.floor(Math.random() * 3);

                if (chance == 0) {
                    message.channel.send('Maybe.');
                }

                if (chance == 1) {
                    message.channel.send('Yes.');
                }

                if (chance == 2) {
                    message.channel.send('No.');
                }

            }

    }
});

Comment: `message.channel.send(...)` triggers `bot.on("message", ...)` again ...
Comment: What is the value of `message` being passed in, is it a string `"questionwords"`?
Comment: There are 3 elements in the questionwords array and you're looping over it, so the if/else runs 3 times.
Answer: To me it looks like you want to know if the words in the questionwords array were in the message.  You already know how to check a single word using Array.includes(), but multiple words are more complicated.
If you just want to know if any word in the words array matches any word in the questionwords array, you can use Array.some():
var wereAnyFound = words.some(word => questionwords.indexOf(word) > -1);
// true or false

Maybe you want to make sure they are ALL in there, use Array.every():
var wereAllPresent = words.every(word => questionwords.indexOf(word) > -1);
// true or false

Maybe you want to know how many, or you want to get the matches (Array.filter()):
var matches = words.filter(word => questionwords.indexOf(word) > -1);
// an array of matches

var howMany = matches.length;
// number

Answer: Like James said in the comments, because there are three words in the questionwords array, your for loop will run three times. It will then reply once for each word.
However, if you remove the for loop and change
if (!words.includes(questionwords[i]))
to
if (!words.includes("can" || "is" || "was"))
you'll get the same result without the bot repeating itself, as it will search for "can" or "is" or "was" instead of "can" and then "is" and then "was".


What are the minimum required modules to run WordPress

Question: Recently a 'consultant' came in to talk to bean counters at my place of employment, with regards to being more efficient with our IT infrastructure.
They suggested to be more efficient we should only load the Apache modules that are required on our web servers. (This is just 1 of 1Ks of suggestions). The Bean Counters are very excited, and prepared for me to spend the time to investigate this avenue of cost cutting.
I don't mind this mundane exercise, I see it as a learning experience!
I guess this leads me to the actual question: How can I determine the minimum required apache modules for a PHP based application without actually going through the code, or plain old trial and error?
Comment: You should try to get the consultant to really specify what kind of efficiency he's talking about like in $/day or such. Then ask if he can show a distict difference by benchmarking loaded and not loaded modules.
Comment: What modules are we talking about here? Like server components or something else?
Comment: Oops! Apache Modules - Lemme update my question
Comment: What on earth do they hope to accomplish by not loading a few redundant modules? It's not like extra modules loded are hogging up alot of extra power, especially if they are not used. This almost sounds like the kind of person who would suggest removing bold fonts because that costs extra cpu power.
Comment: Sandokan - I'm currently in the middle of that argument right now with the powers that be, I'm explained that the savings gain pretty much already been wiped out by just the interest on the consultants fee!
Comment: About the only thing I would think about here is possibly reducing size of apache allowing more apache instances to reside on fewer servers (or VMs).  Reducing unnecessary modules can lessen the memory cost of each httpd process.
Comment: Sandokan -- I'm not privvy to that info, but I'm sure he should have mentioned it to the bean counters. I'll chase that up, it's a good idea.
Answer: Your consultant is blowing smoke. And probably getting very highly paid to do so. We're all in the wrong business...
There are good reasons to limit the Apache modules that you install and use. Security and stability come to mind as the top reasons. But efficiency? Do they mean power savings? Unused code doesn't consume any electricity. I can't imagine what is supposed to be meant by this. You've spent more than a year's power savings from such "efficiency" just typing out your question.
As for WordPress, its requirements are pretty minimal. You don't even need Apache...
And advise the bean counters that they aren't getting their money's worth from that moron consultant. I'd ballpark the savings from this one at around 3 cents per year per server. You can use that as an example of the quality of recommendations you're receiving.
Comment: Disabling Apache modules will reduce RAM usage of an Apache worker process, I suppose, but unless you're running something on the scale of WordPress.com it's unlikely to make much of a difference.
Comment: Thanks Michael!! This is my current argument with the suits - I could understand if we hosted 100K+ websites/instances, but it's under 200 actual sites, using WP in MU mode - Thanks for giving me the confidence to talk back to the people who can fire me!
Comment: @MisterITGuru I've been using WordPress since 2004 and I even contributed a few bug fixes and enhancements to it. So I know a few things about it. :)