Two different answers when integrating with respect to Brownian motion

Question: Consider the integral with respect to Brownian motion
$$\int_{0}^{t}s  \ dB_{s} \ . $$
A textbook I am reading uses integration by parts to rewrite the above integral as
$$tB_{t}-\int_{0}^{t}B_{s} \ ds.$$
However, I am familiar with the fact that
$$\int_{0}^{t}g(s) \ dB_{s}\sim \mathcal{N}\left ( 0,
\int_{0}^{t}g^{2}(s) \ ds \right ).$$
If I use this idea, then $g(s)=s$, and
$$\int_{0}^{t}s  \ dB_{s}\sim \mathcal{N}\left ( 0,
\frac{t^3}{3} \right ).$$
But then,
$$tB_{t}-\int_{0}^{t}B_{s} \ ds \neq \int_{0}^{t}s  \ dB_{s}\sim \mathcal{N}\left ( 0,
\frac{t^3}{3} \right ).$$
So it seems I am getting two different answers.  Or maybe, the above equation is actually an $\textit{equality}.$  If that is the case, I guess I am not seeing it. Can anyone help me understand this?
Thanks in advance!
Comment: Where is $s^2$? You only show $s$ in calculations. Is there a typo somewhere?
Comment: Sorry, it should just be $s$.  When you integrate, it turns into $s^2$, which is what I was thinking.  Just a notation error.
Comment: Just to be sure: Are you not sure why the equation for integration by parts is correct?
Comment: Note that $t B_t - \int_0^t B_s \, ds$ **is** Gaussian with mean $0$ and variance $t^3/3$.
Comment: @saz How?  I guess that's what I'm confused on- it doesn't seem to have that distribution. Do you mind showing me?
Answer: There is no contradiction in the two results which you mention. It does hold true that $$t B_t - \int_0^t B_s \, ds = \int_0^t s dB_s \sim N(0,t^3/3).$$
To prove that $t B_t- \int_0^t B_s \, ds$ is Gaussian (without using the integration by parts formula) we can reason as follows:
Since the Brownian motion $(B_t)_{t \geq 0}$ is a Gaussian process, we know that the random vector  $(B_{s_1},\ldots,s_{m})$ is Gaussian for any choice of $0<s_1 < \ldots < s_m$ and $m \in \mathbb{N}$. This, in turn, implies that sums of the form
$$\sum_{j=1}^m \alpha_j B_{s_j} \tag{1}$$
are Gaussian for real coeficients $\alpha_j \in \mathbb{R}$.If we choose $s_j := t j/m$ for fixed $t>0$, we find in particular that
$$t B_t - \frac{1}{m} \sum_{j=1}^{m-1} B_{t j/m} $$
is Gaussian (simple choose $\alpha_j := -1/m$ for $j=1,\ldots,m-1$ and $\alpha_m := t$ in $(1)$). Noting that
$$\frac{1}{m} \sum_{j=1}^{m-1} B_{tj/m}$$
is a Riemann sums which converges pointwise to the integral $\int_0^t B_s \, ds$ as $m \to \infty$ we conclude that $$t B_t - \int_0^t B_s \, ds$$ is Gaussian as a (pointwise) limit of Gaussian random variables. Applying Fubini's theorem we find that the random variable has expectation zero; showing that the variance equals $t^3/3$ equals a bit more work but is not too difficult using known identities for moments of Brownian motion.


Cópia de Arquivos utilizando biblioteca shutil

Question: Olá,
Estou aprendendo  a progamação em Python e surgiu uma dúvida referente a biblioteca shutil.
Teoricamente, consigo realizar a cópia do arquivo utilizando esta biblioteca, porém, gostaria de saber se há uma forma de ao colar o arquivo em outro diretório, o nome do arquivo seja alterado, adicionando a data do dia atual, de maneira automática, para executar todos os dias.
Para copiar o arquivo para o diretorio de maneira bem rústica, realizo a troca manual no destino, alterando seu nome diretamente no código.
Estou utilizando a seguinte programação:
from shutil import copy

orig = r 'diretorio1\arquivo.txt'
des = r 'diretorio2\arquivo_(dia_de_hoje).txt' #aqui realizo o preenchimento manual do dia do hoje, e gostaria que essa parte fosse automática.

copy(orig, des)

O resultado que busco é :
arquivo(dia_de_hoje).txt sendo gerado sem eu precisar realizar essa substituição manual no código.
Comment: O que acontece se na variável `des` você definir o novo nome do arquivo? Tipo `des = 'diretorio2/novo.txt'`
Comment: Obrigado pela resposta. O arquivo é renomeado, porém nesse caso, a substituição é manual.Gostaria de saber se há uma forma de que esse arquivo seja copiado todos os dias so que com a data do dia atual de forma que não seja necessario preencher manualmente a data do dia.
Comment: Use a biblioteca `datetime` para obter a data atual, define o nome do arquivo usando ela e depois configura uma tarefa agendada no seu sistema para executar o código todos os dias.
Answer: Olá, amigo. Então, tem uma forma pouco rebuscada de fazer essa transferência de dados + mudança de diretório + alteração do nome do arquivo. Não sei se vai simpatizar, mas vou colocar o código aqui.
Definindo a data
Há uma forma bem mais rápida de definir a data, utilizando a função datetime(), mas não costumo utilizá-la para ter uma liberdade maior de manipulação do output. Eis como uso:
import time
t = time.localtime ()

dia = t.tm_mday
mês = t.tm_mon

if dia < 10:
    dia = str(0) + str(dia) #Acrescentando o 0 em dias menores que 10
if mês < 10:
    mês = str(0) + str(mês) #Acrescentando o 0 em meses menores que 10

ano = t.tm_year

data = str(dia) + str(mês) + str(ano)

Arquivo de origem e arquivo de saída
Observe: esta parte do código parte do pressuposto que o arquivo de origem esteja na mesma pasta em que o código está sendo executado. Para mudar isso, basta acrescentar o caminho (path) da pasta, assim como foi feito em "saída".
origem = input("Digite o nome do arquivo de origem: ")
arquivo = open(origem + ".txt", "r")
saída = open("/users/HP/" + origem + str(data) + ".txt", "w") #Nome com data. Note que você pode alterar o path para o que deseja. Este "/users/HP/" é apenas um exemplo.

Escrevendo no novo arquivo
for linha in arquivo.readlines():
    palavra = linha
    saída.write(palavra)

saída.close()

Código completo
import time
t = time.localtime ()

dia = t.tm_mday
mês = t.tm_mon

if dia < 10:
    dia = str(0) + str(dia)
if mês < 10:
    mês = str(0) + str(mês)

ano = t.tm_year

data = str(dia) + str(mês) + str(ano)

origem = input("Digite o nome do arquivo de origem: ")
arquivo = open(origem + ".txt", "r")
saída = open("/users/HP/" + origem + str(data) + ".txt", "w")

for linha in arquivo.readlines():
    palavra = linha
    saída.write(palavra)

saída.close()

Por fim, basta procurar o novo arquivo no diretório que você escolheu. Espero que tenha conseguido ajudar. Boa sorte!
Answer: Pelo que entendi você está tentando implementar um código que seja capaz de copiar um arquivo de um diretório para outro renomeando de modo que o novo nome contenha o nome antigo, mais o carácter de "_", mais a data atual do sistema no modo AAAAMMDD, mais extensão.
OBSERVAÇÂO:
A extensão do arquivo é importantíssimo. Pois, o arquivo só poderá ser manipulado, se o mesmo tiver uma extensão válida.
Para implementarmos um código descente devemos prestar atenção na seguinte lógica:

Importar as bibliotecas necessárias;
Capturar e tratar a data atual;
Capturar o caminho de origem do arquivo;
Informar o nome completo do arquivo desejado;
Capturar o caminho de destino;
Copiar e renomear o arquivo.

Pois bem, seguindo esta lógica podemos implementar o seguinte código:
from os import chdir, listdir, rename
from shutil import copy
from os.path import isfile
import time

t = time.localtime()
t1, t2, t3 = f'{t[0]}', f'{t[1]:02}', f'{t[2]:02}'

cam = input('Informe o caminho arquivo: ')
chdir(cam)
for i in listdir():
    if isfile(i):
        print(i)
nome = input('Informe o nome completo do arquivo desejado: ')
cam2 = input('Informe o caminho destino: ')
copy(nome, cam2)

chdir(cam2)
for j in listdir():
    if isfile(j) and j == nome:
        rename(nome, nome[:-4] + '_' + t1 + t2 + t3 + nome[-4:])

Observe que a primeira coisa no código é a importação das bibliotecas e métodos necessários. Em seguida, é capturada e tratada a data atual. Pois, o método time.localtime() nos retorna uma tupla contendo 9 parâmetros, dentre os quis, sevemos nos importar apenas com os três primeiros, que nos fornece, respectivamente, as informações de ano, mês e dia. Desse modo temos t[0] = ano, t[1] = mês e t[2] = dia.
Prosseguindo a lógica, o código nos solicitará o caminho do diretório de origem do arquivo. Este caminho, obviamente, é o caminho da pasta que contém o arquivo, o qual desejamos copia-lo.
Depois de informarmos o caminho do arquivo, o código foca no caminho especificado e o primeiro bloco for irá percorrer a pasta indicada, listando todos os arquivos da referida pasta.
Nesse momento devemos escolher e informar o nome completo - nome + extensão - do arquivo desejado. Posteriormente, devemos informar o caminho do diretório de destino.
Em seguida, o código copia o arquivo na pasta de destino e, depois, o renomeia.


Maximum number of vertices such that no edge exists between any 2 vertices

Question: Given a graph $G$ and $n$ vertices and $k$ edges. Is there an algorithm that finds the maximum number of vertices such that no edge exists between any vertices in this set?
Comment: you want to find the largest independent set https://en.wikipedia.org/wiki/Independent_set_(graph_theory)#Maximum_independent_sets_and_maximum_cliques.
Comment: Check Caroi wei theorem
Answer: You can solve the maximum independent set problem via integer linear programming as follows.  Let binary decision variable $x_i$ indicate whether node $i\in N$ is selected.  The problem is to maximize $\sum_{i\in N} x_i$ subject to
$$x_i + x_j \le 1 \quad \text{for all $(i,j)\in E$}.$$
These constraints enforce $(i,j)\in E \implies \lnot(x_i \land x_j)$.  That is, if $(i,j)$ is an edge you cannot select both nodes $i$ and $j$.
In practice, integer linear programming is much more efficient than brute force.
Comment: What is the complexity of the algorithm using integer linear programming?
Comment: Still exponential in the worst case.
Answer: Unfortunately, this is NP Hard problem. NP hard problem don't have any efficient polynomial time solution and can be only solved in exponential time. You have to check all possible subsets of vertices, to get maximum independent set. There are approximate algorithms for such problems, which gives close to ideal answer efficiently.


Variance of $X^2$ if $X \sim \mathcal{N}(0,1)$?

Question: I'm trying to find the variance of $X^2$, considering that $X$ is distributed as a standard normal $(X \sim \mathcal{N}(0,1))$.
I can find that $E(X^2)=1$, by using that $\sigma^2(X)=E(X^2)-(E(X))^2=1$, but I'm stuck trying to find the variance.
Comment: To compute the variance of $X^2$, you need to compute $E[X^4]$ at some point. To do this, write $E[X^4]$ as an integral, and do integration by parts.
Comment: @angryavian: both $X$ and $X^2$ have the same density function?
Answer: If $X\sim N(0,1)$, then $Z=X^2 \sim \chi^2(1)$.
So, we can use the Gamma($\frac{1}{2},\frac{1}{2}$) distribution to get:
$$\mathbb{E}[Z] = \frac{\left(\frac 12\right)}{\frac 12} = 1; \quad
\mathbb{E}[Z^2] = \frac{\left(\frac 12+1\right)\left(\frac 12\right)}{\left(\frac 12\right)^2} = 3$$
$\therefore Var(X^2)  = 3 - 1 = 2$
Answer: The comment posted by angryavian is the way to go. I'll give you a few more details. We know that $\sigma^2(X)=E(X^2)-E(X)^2$, so by extension, $\sigma^2(X^2)=E(X^4)-E(X^2)^2$. Now for a standard normal distribution, we know that $E(X^2)=\sigma^2(X)=1$, so we must just find the value of $E(X^4)$. By definition,
$$E(X^4)=\left(\int_{-\infty}^{\infty} x^4e^{-x^2/2} dx \right)/\sqrt{2 \pi}$$
(The $\sqrt{2 \pi}$ in the denominator comes from the function for the standard normal distribution.) Using $u=x^3$ and $dv=xe^{\frac{-x^2}{2}} dx$, we just have to integrate a couple times and use the well-known fact:
$$\sqrt{\pi}=\int_{-\infty}^{\infty} e^{-x^2} dx$$
Carrying this out, we will see that $E(X^4)=3$ and therefore $\sigma^2(X^2)=E(X^4)-E(X^2)^2=2$. You can further show that $E(X^{2n})=(2n-1)!!$, where the double factorial function is the product of the integers less than or equal to a number of the same parity. For example, $5!!=(5)(3)(1)=15$ and $6!!=(6)(4)(2)=48$.


:after pseudo class not working when using in stylesheet and importing in react

Question: I am using style-loader and css-loader to import stylesheets in react:
require('../css/gallery/style.css');

The stylesheet's working fine, except for this rule:
.grid::after {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}

I already have a div which belongs to a the grid class here:

    {display_images}

The new element which should be created by the :after pseudoclass is not being created here. I know that React does not support pseudoclasses in its inline styles, but I don't know whether we are allowed to use them in stylesheets and then import them. If it isn't allowed, what are the alternatives?
Comment: This should work. Could you check in the `
Answer: Use a single colon, not two: .grid: after { /* your code*/ }. Also ensure your class .grid has position: relative.
Answer: The CSS-after that you have shown in your question doesn't display anything. I can't guarantee this is your solution without further investigation but I would recommend adding a temporary background colour so you can see the effect.
see the following JSFiddle for an example:
https://jsfiddle.net/o410b2h5/
.grid::after
{
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: red;
}

background: red;
Comment: I just checked using this method, and you're right, the `after` element exists. Should have thought about this sooner.


jQuery Mobile content does not appear unless page refresh

Question: The code manipulation that I am doing in Javascript at the bottom does not happen unless I manually refresh the page. Is there any way to prevent this? If not, how can I dynamically refresh the page as soon as it is loaded? Thanks for your help!
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Universal Travel Flights</title>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
    <link rel="stylesheet" href="css/my.css" />

                            Book

                            Deals

                            Contact

            <form id="inputform" name="inputform" method="get" action="payment.html">
                <input type="hidden" name="flightID" id="flightID" />

                <input type="submit" value="Continue" data-theme="b" data-icon="arrow-r" data-iconpos="right"/>
            </form>

                Back

Comment: how do you navigate to this page or is this a standalone/first page ?
Comment: Because `pageinit` is fired once and before the page is shown. Replace it with `.on('pageshow', function() { your code });`
Comment: And for collapsibles `$('#id').collapsible();` and controlgroup `$('#id').controlgroup('refresh')`
Comment: Your example works correctly, pageinit is triggered but your javascript is not working. Why, omg why are you using plain javascript with jQuery?
Answer: Ok I think I figured it out...Wrap your Script with this:

That should do it.
Comment: I tried Omar's and Frank's suggestion, I still need to refresh. I think Gajotres has a point, I should probably be using jQuery instead of Javascript, it's just easier for me...
Comment: Sorry dear...No law against mixing but for troubleshooting it would make better sense for us troubleshooters.  Good luck!


How to theme content edit page

Question: I themed page to create custom type node and named it page--node--add--book.tpl.php
It works well, but when I tried to theme content edit page and named it page--node--edit--book.tpl.php
nothing happening. Help to fix this.
Tried suggestions:
function bookhive_theme() {
  return array(
    'book_node_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'book-node-form',
        'render element' => 'form',
    ),
  );
}

and
suggestion from here
http://www.wdtutorials.com/how-to-override-forms-using-custom-template-drupal-tutorial/7

Comment: What you have defined in template.php for this?
Comment: I tried suggestion from here, http://www.wdtutorials.com/how-to-override-forms-using-custom-template-drupal-tutorial/7
Answer: Ok, I find an answer. In my case the proper theme suggestion was html--node--edit.tpl.php I used theme debug mode to find it.
Also, to make page--node--edit.tpl.php works I need to delete my page--contenttype.tpl.php file. To customize my content type page I just used simple check in page.tpl.php if($node->type == 'book'):

Answer: page--node--edit--book.tpl.php isn't a valid theme template suggestion. From the d.o. D7 Template docs for page.tpl.php...

The list of suggested template files is in order of specificity based
  on internal paths. One suggestion is made for every element of the
  current path, though numeric elements are not carried to subsequent
  suggestions. For example, "http://www.example.com/node/1/edit" would
  result in the following suggestions:

page--node--edit.tpl.php
page--node--1.tpl.php
page--node.tpl.php
page.tpl.php

If you're looking to theme a node edit page, use page--node--edit.tpl.php.
Comment: oh, I tried page--node--edit.tpl.php but, thats not work too. at least for me.
Comment: Two things to note why it might not work: You need to clear the Drupal cache / You're using the administration theme for page editing (i.e. the ***Use the administration theme when editing or creating content*** on theme administration page).
Comment: I use Devel to rebuild theme registry on every page reload, I cleared cache manually few times and I check this from regular user account.
Comment: page--node--edit.tpl.php works only with page like website.com/node/edit but not with node/1/edit
Comment: *website.com/node/edit* would not be a valid path in Drupal.

How to theme content edit page


How to show this equality for operator norm?

Question: Let $(X,\Sigma_\mu,d\mu)$ and $(Y,\Sigma_\nu,d\nu)$ be two positive $\sigma$-finite measure space and let $M(d\mu)$ and $M(d\nu)$ be spaces of complex-valued $d\mu$-measurable and $d\nu$-measurable functions. Consider linear integral operator of the form $$\mathcal{K}u(y) = \int k(x,y)u(x)d\mu(x),$$
where $k$ is complex measurable function (with respect to the product $\sigma$-algebra).
I would like to show that $\|\mathcal{K}\|_{B(L^p,L^\infty)}=\|k\|_{L^\infty(L^{p^*})}$, where $B(L^p,L^\infty)$ is the space of boudned operators from $L^p$ to $L^\infty$, $\|.\|_{L^\infty(L^{p^*})}$ denotes iterated norm, and $p^{-1}+p^{^*-1}=1$. The bound $\|\mathcal{K}\|_{B(L^p,L^\infty)}\leq \|k\|_{L^\infty(L^{p^*})}$ follows from Holder's inequality.
But I don't see how to show the reverse inequality. In fact, I'm interested in a simpler case, when $X$ and $Y$ are some bounded and connected subsets of $\mathbb{R}^d$ spaces and $p=p^*=2$, but this does not help me to find a way around it.
Answer: Using
Theorem (Hölder's inequality). Let (S, Σ, μ) be a measure space and let $p, q ∈ [1, ∞]$ with $1/p + 1/q = 1.$ Then, for all measurable real- or complex-valued functions f and g on S,
${\displaystyle \|fg\|_{1}\leq \|f\|_{p}\|g\|_{q}.} \|fg\|_{1}\leq \|f\|_{p}\|g\|_{q}.$
you can see that
$$|\mathcal{K}u(y)| = |\int k(x,y)u(x)d\mu(x)|\leq \|k(x,y)\|\|u(x)\| \implies (operator \ norm \ of \ \mathcal{K} \leq\|k(.,y)\| $$
where norms are understood, and note that norm of $k(x,y)$ is for fixed $y$, since we integrate with respect to $x$.
Then you take maximum of these norm as $y$ varies. It is looking for supremum of real numbers, so $\|.\|_\infty$ of norm $\|.\|_p$'s is calculated for $k(x,y).$ So, the end result is $\|k(x,y)\|_{L^\infty(L^p)}$.
Comment: How about this outline? Given $\epsilon$ pick a $y$ that will give $\|k(.,y)\|$ close ($\epsilon$ much) to the supremum of such norms. Now that $y$ has been fixed, show that you can pick $u(x)$ such that $\mathcal{K}u$ ($y$ fixed integral operator) will be close to $\|\mathcal{K}u\|$, which will imply that $mathcal{K}$ does approach the bound we found.

I am sure if you write out on paper, it'll come out.
Comment: Beham, thank you for your answer. This inequality I agree on. I don't understand, how can we get the reverse, to prove that we have equality.


How to configure totally open DMZ with OpenWRT?

Question: I have OpenWRT router.
I have NAS in my LAN, which i need to access from WAN and from all computers in the LAN. So, it should be accessible from any computer and it needs to access some of them, too.
I read OpenWRT wiki and forums, and they recommend VLAN for network separation, but i do not need that - i want it all be on one network, so it can be visible to each other, and NAS visible from the WAN?
Any idea, how that can be done?
In case, if its important my equipment:

Router Model: Buffalo WZR-HP-G300NH
Firmware Version: OpenWrt Backfire 10.03.1 / LuCI 0.10.0 Release (0.10.0)
Answer: I have met similar problem and I can share solution which appears to be very simple.
In OpenWRT the feature you are looking at is plain port forward.
Open you router IP, typically http://192.168.1.1
In Network menu, choose Firewall, the Port Frowards.
Scroll down to "New port forward" and add:

Name: ALL->DMZ
Protocol: choose do you need both TCP=UDP or just TCP
External zone: wan
External Port: leave empty!!!
Internal zone: lan
Internal IP address: choose IP of host, in your case it's NAS
Internal port: leave empty!!!

Click Add, and Save & Apply.
That will work exactly the same as in other routers firmware "DMZ host", the host with ALL external traffic redirected to it by default.
To have more security I recommend you to forward only ports you need, without exposing it widely to Internet.
If you will want to add additional SINGLE Port Forwards, they will be added to the end of list.
IMPORTANT: always move rule ALL->DMZ to the bottom of the list and "Save & Apply". The rules are processed in the order, so the first one met condition and others do not work.
Best Regards,
Arunas B.
Comment: Clever! This worked perfectly.
Answer: As advised above, I'd really recommend just forwarding the port(s) needed for discovery and data retrieval. Forwarding all ports will expose the administration login mechanism on your device to the entire internet. Being that your storage will likely contain personal data which I'm pretty sure you wouldn't want just anyone to be able to read, the DMZ/forward all is a terrible choice.
Research which ports your device uses for discovery/data retrieval and ONLY forward those ports. Best way to research this is to look at your product manual. Likely it will recommend opening certain ports on a firewall, this is where you'll get the information you need.


Could anyone explain the terms "Hypothesis space" "sample space" "parameter space" "feature space in machine learning with one concrete example?

Question: I am confused with these machine learning terms, and trying to distinguish them with one concrete example.
for instance, use logistic regression to classify a bunch of cat images.
assume there are 1,000 images with labels indicating the corresponding image is or is not a cat image.
each image has a size of 100*100.
given above, is my following understanding right?
the sample space is the 1,000 images.
the feature space is 100*100 pixels.
the parameter space is a vector that has a length of 100*100+1.
the Hypothesis space is the set of all the possible hyperplanes that have some attribute that I have no idea.
Answer: People are a bit loose with their definitions (meaning different people will use different definitions, depending on the context), but let me put what I would say. I will do so more in the context of modern computer vision.
First, more generally, define $X$ as the space of the input data, and $Y$ as the output label space (some subset of the integers or equivalently one-hot vectors). A dataset is then $D=\{ d=(x,y)\in X\times Y \}$, where $d\sim P_{X\times Y}$ is sampled from some joint distribution over the input and output space.
Now, let $\mathcal{H}$ be a set of functions such that an element $f \in \mathcal{H}$ is a map $f: X\rightarrow Y$. This is the space of functions we will consider for our problem. And finally, let $g_\theta \in \mathcal{H}$ be some specific function with parameters $\theta\in\mathbb{R}^n$, such that we denote $\widehat{y} = g_\theta(x|\theta)$.
Finally, lets assume that any $f\in\mathcal{H}$ consists of a sequence of mappings $f=f_\ell\circ f_{\ell-1}\circ\ldots\circ f_2\circ f_1$, where $f_i: F_{i}\rightarrow F_{i+1}$ and $F_1 = X, \, F_{\ell+1}=Y$.
Ok, now for the definitions:

Hypothesis space (HS): the HS is the abstract function space you consider in solving your problem. Here it is denoted $\mathcal{H}$. I find that this term does not appear very often in applied ML, rather, it is mostly used in theoretical contexts (e.g., PAC theory).
Sample space (SS): the sample space is simply the input (or instance) space $X$. This is the same as in probability theory, regarding each training input as a random sample instance1.
Parameter space (PS): for a fixed classifier $g_\theta$, the PS is simply the space of possible values of $\theta$. It defines the space covered by the single architecture that you train2. Usually it does not include hyper-parameters when people say it.
Feature space (FS): for many models, there are multiple feature spaces. I've denoted them here as $F_2,\ldots, F_\ell$. They are essentially the intermediate outputs due to the model's layered processing (but see note1). For CNNs, these "feature maps" at different layers are often used for different things, hence distinction is important.

For your example:

The HS is almost the same as the PS once you've chosen logistic regression (except that the HS includes the models arising from different hyper-parameters as well, whereas the PS is fixed for a given set of hyper-parameters). Indeed, here, the HS is the set of all hyperplanes (and the PS could be as well, depending on the presence of e.g. regularization parameters).

The sample space is the set of all possible cat images; i.e., $X$. It is not usually restricted in meaning to be $D$, which is usually just called the training set.

The feature space in your case is indeed $F_1 = X$, assuming that you feed the raw pixels to the logistic regression (so $\ell = 1$).3

1Some people treat some processed form of the input as the input. E.g., replacing an image $I$ with its HOG or wavelet features $u(I)$. Then they define the sample space $X_u = \{ u(I_k) \;\forall\; k \}$, i.e., as the features rather than the images. However, I would argue that you should leave $I\in X$ and simply set $F_1 = X_u$, i.e., treat it as the first feature space.
2Note that each $\theta$ defines a different trained model, which is in the HS. However, not all members of $\mathcal{H}$ can be reached by varying the parameter vector. For instance, you might search over the number of layers in a CNN, but the parameter space of a single CNN will not cover that. (Though note again that $\mathcal{H}$ tends to be used more in theoretical contexts). One distinction between HS and PS appears in the context of error decompositions of approximation vs estimation noise.
3Normally (in "older" computer vision) you would extract features from the image and feed that to e.g. logistic regression. The modern version of this is attaching a fully connected (linear) layer with a softmax at the end of a CNN.
Answer: I'll approach this from a more colloquial point of view:
The sample space consists of your sample-level input data, which are instances of specific values in feature space. In your example, your sample space consists of 1000 images.
The feature space consists of the individual components that make up a sample, and potentially intermediate, derived features that express combinations of the raw features. In your example, the feature space is the 10,000 pixels and the color values they can take.
The hypothesis space covers all potential solutions that you could arrive at with your choice of model. A model that draws a linear boundary in feature space, for example, does not have any nonlinear solutions in its hypothesis space. In most cases, you can't enumerate the hypothesis space, but it's useful to know what types of solutions it's even possible for your model to generate.
The parameter space covers the possible values that the model parameters can take, which will vary depending on your model. A logistic regression, for example, will have a weight parameter for every feature that varies between -Inf and +Inf. You could also build a coin flip model that guesses "cat" randomly with probability X, where X is the single parameter that varies from 0 to 100.


Powershell pipe into exe and wait

Question: I am piping an array of data into a executable program but I need it to block after every call in the foreach loop. It will leave the loop before it even opens the program from the first call.
 Set-Alias program "whatever.exe"

 foreach ($data in $all_data)
  {
       $data| %{ program /command:update /path:"$_" /closeonend:2 }
  }

Comment: This is not related to your problem, but you have an unnecessary `foreach` loop in your code. You can simplify your loop to one of these:

`foreach ($data in $all_data)
  {
       program /command:update /path:$data /closeonend:2 }
  }`
 or
`$all_data | %{ program /command:update /path:"$_" /closeonend:2 }`
Comment: So "you need to wait until the external call finishes before the next iteration takes place"?
Answer: I can think of two ways to tackle this:

pipe your executable call to Out-Null
shell out the call to cmd.exe /c (as shown in @BobLobLaw's answer)

I made your sample code a little more specific so I could run and test my solutions; hopefully it'll translate.  Here's what I started with to be equivalent to your sample code, i.e. the script executes with no waiting on the executable to finish.
# I picked a specific program
Set-Alias program "notepad.exe"

# And put some values in $all_data, specifically the paths to three text files.
$all_data = Get-Item B:\matt\Documents\*.txt

# This opens each file in notepad; three instances of notepad are running
# when the script finishes executing.
$all_data | %{ program "$_" }

Here's the same code as above, but piping to Out-Null forces the script to wait on each iteration of the loop.
# I picked a specific program
Set-Alias program "notepad.exe"

# And put some values in $all_data, specifically the paths to three text files.
$all_data = Get-Item B:\matt\Documents\*.txt

# Piping the executable call to out-null forces the script execution to wait
# for the program to complete. So in this example, the first document opens
# in notepad, but the second won't open until the first one is closed, and so on.
$all_data | %{ program "$_" | Out-Null}

And, lastly, the same code (more or less) using cmd /c to call the executable and make the script wait.
# Still using notepad, but I couldn't work out the correct call for
# cmd.exe using Set-Alias. We can do something similar by putting
# the program name in a plain old variable, though.
#Set-Alias program "notepad.exe"
$program = "notepad.exe"

# Put some values in $all_data, specifically the paths to three text files.
$all_data = Get-Item B:\matt\Documents\*.txt

# This forces script execution to wait until the call to $program
# completes.  Again, the first document opens in notepad, but the second
# won't open until the first one is closed, and so on.
$all_data | %{ cmd /c $program "$_" }

Answer: I like PowerShell but I never really learned Invoke-Command. So whenever I need to run an EXE I always use cmd. If you type cmd /? you get its help, look at the "c" switch. I'd do something like this:
foreach ($data in $all_data){
    $data |
    Foreach-Object{
        cmd /c "whatever.exe" /command:update /path:"$_" /closeonend:2
    }
}

If you don't like the cmd /c thing you could use Jobs.
foreach ($data in $all_data){
    $data |
    Foreach-Object{
        $job = Start-Job -InitializationScript {Set-Alias program "whatever.exe"} -ScriptBlock {program /command:update /path:"$($args[0])" /closeonend:2} -ArgumentList $_
        while($job.Status -eq 'Running'){
            Start-Sleep -Seconds 3
            #Could make it more robust and add some error checking.
        }
    }
}

Answer: Depending on your scenario, wait-job might be overkill. If you have a programmatic way to know that whatever.exe has done its thing, you could try something like
do {start-sleep -sec 2} until ($done -eq $true)
Oh and.

Powershell pipe into exe and wait


Como setar Title em uma `img`?

Question: Existe alguma forma de setar o título (Text) do componente img no code behind?

Comment: você quis dizer o atributo `alt` do  ?
Comment: Explique o que você chama de *title*. O que quer exatamente?
Comment: @bigown , seria o texto que a imagem apresenta quando o link (src) não é encontrado, peguei uma aplicação para fazer manutenção e me deparei com isso   ``, estou levando tudo que é **TEXT** para o **code behind** para fazer tradução para outros idiomas, mas pelo que pesquisei o componente IMG do .NET não tem o _title_ .
Answer: Isso pode ser colocado no code behind assim:
this.ProximoMes.Attributes.Add("title", "Alguma coisa aqui");

Coloquei no GitHub para referência futura.
Comment: faltou dizer que ele precisa colocar o runat="server"
Comment: Esta nos comentários .
Comment: Isso mesmo vlw.

Como setar Title em uma `img`?


I can't render default values on form element in theme_table()

Question: For the last few days and some of last week I've been trying to fix up the interface of a page we have on one of our modules since it was difficult to use. I decided to take this data and just display it in a table so that it's simple and organized by column.
Here is a very basic recreation of the code.
function _ss_menu_zone_test($form, $form_state) {

  $formfield = array(
    '#type' => 'textfield',
    '#default_value' => '10' // default value set
  );
  $formselect = array(
    '#type' => 'select',
    '#options' => array(1,2,3,4,5,6),
    '#default_value' => 3  // default value set
  );

  $tablesort_headers =array(
    array('data' => t('Price'), 'field' => 'price'),
  );

  $tablesort_rows = array(
    array('price' => 'test row format 1'), // example of basic string row
    array('price' => array('data' => 'test row format 2')), // example of simple string but using data
    array('price' => drupal_render($formfield)),
    array('price' => array('data' => $formfield)),
    array('price' => drupal_render($formselect)),
  );

  // render the tablesort of menu items.
  $form['category_' . $tid]['items'] = array(
    '#theme' => 'table',
    '#header' => $tablesort_headers,
    '#rows' => $tablesort_rows,
    '#sticky' => TRUE,
    '#attributes' => array('id' => 'zone-items-' . $tid)
  );

  return $form;
}

In this example I have one column for the test data and a couple rows to show the differences. The primary issue I've run into here is if I try to add a form API textfield to a cell somewhere it drops value for the #default_value. the field renders correctly with any other key I've specified.
Does anyone know how to go about getting this #default_value to actually populate the field like it does EVERYWHERE else in the Form API?
Answer: In FAPI (and renderable arrays in general), keys starting with a # are considered properties - so not renderable elements. This means their children aren't processed for content properly.
There are several methods to do what you want, but the easiest is probably references. In your specific example, it would look like this (I've trimmed out some stuff to make my changes more clear):
function _ss_menu_zone_test($form, &$form_state) {

  $tablesort_headers =array(
    array('data' => t('Price'), 'field' => 'price'),
  );

  // render the tablesort of menu items.
  $form['category_' . $tid]['items'] = array(
    '#theme' => 'table',
    '#header' => $tablesort_headers,
    '#rows' => array(),
    '#sticky' => TRUE,
    '#attributes' => array('id' => 'zone-items-' . $tid)
  );

  $formfield = array(
    '#type' => 'textfield',
    '#default_value' => '10' // default value set
  );

  //We need to include the field in the form so it's rendered. This wont display because we're using #theme => table.
  $form['category_' . $tid]['items'][] = array('formfield' => &$formfield);

  //These are your rows, note the byreference on the formfield.
  $tablesort_rows = array(
    array('price' => 'test row format 1'), // example of basic string row
    array('price' => array('data' => 'test row format 2')), // example of simple string but using data
    array('price' => array('data' => &$formfield)),
  );

  //Add your rows to the table.
  $form['category_' . $tid]['items']['#rows'] = $tablesort_rows;

  //Since we used references we want to unset the variables we created.
  unset($formfield);

  return $form;
}

Comment: Where is the Op using a _#_ that doesn't allow the child items to be rendered?
Comment: #rows would be the property that is not rendering the form items properly.
Comment: Does the default_value actually appear in the field in this example? I don't see why it's passed by reference. Drupal's internal theme function for table cells does a drupal render on the form api element which should just return the markup of the element. It does, however, the value isn't populated as expected.
Comment: In my example in the initial post the following renders the element but with out the value i'm expecting.

`array('price' => array('data' => $formfield)),`
Comment: Also `$form['category_' . $tid]['items'][] = array('formfield' => &$formfield);` Adds the element to that array but it goes unused or would end up rendering the element after the table is themed out which is not what i'm looking for.
Comment: It works and gives me a good idea of what's going on here. I figured that since the whole page is a form that the formbuilder would probably handle this.
Comment: @ChadPayne Basically, the items inside #rows are being ignored by the form render. The reason they are being rendered is theme_table is running on the items, so it's partially rendering them - but the form itself has no idea they exist, and so it doesn't set the default value.

My solution gives the item to the form to render properly, but then because we're attaching it to the table render array and it's not under rows or headers it doesn't actually display the item. The then rendered item is being added to the table row with the byreference call.
Answer: I create the elements dynamicaly in ajax and i have common problem. The #default_value if not acting in render() function, but #value does. You can ensure it watching the form_select_options() Using #value is bad practice.
May be post i found (below) could be useful in your case for form generation? https://www.drupal.org/node/1000568#comment-3840362
Also, no need to use render() is $row[]=>('data'=>) drupal will render on his own
Also take a look at this elegant trick https:// passingcuriosity.com/ 2011/drupal-7-forms-tables/
(remove spaces please my reputation dont allow me to post more than 2 links)


Setter method not generated for JAX B object of type list

Question: Setter method is not generated when i create JAX classes from XSD,for maxOccurs=unbounded type. I need to manually add setter method for DetailType .Is this the right approach since i need to populate DetailType inside the root element
@XmlRootElement(name = "WPExchangeRate")
public class WPExchangeRate {

    @XmlElement(name = "Header")
    protected HeaderType header;
    @XmlElement(name = "Detail", required = true)
    protected List<DetailType> detail;
    @XmlElement(name = "Trailer")
    protected TrailerType trailer;

Answer: This is by design. Just do getDetail().add(myDetail).
Answer: If you are using Maven:
In your pom.xml add to the plugin's <configuration>:
<args>
    <arg>-Xsetters</arg>
</args>

If you want to configure generation method: -Xsetters-mode=accessor or -Xsetters-mode=direct.

If you are generating from command line:
Add -Xsetters to the command (same for -Xsetters-mode).


How to add a Related Products View for Commerce Kickstart?

Question: I am trying to show related products in the products display for Commerce Kickstart. I tried using the method outlined in this tutorial but ran into a couple of issues:

The "Target Type" in the entity reference field (the field used for the related product) does not show "Node" as an option.
The SQL error mentioned in the tutorial appeared when selecting "Aggregate" in the view.

The bottom line is I couldn't get this to work of Commerce Kickstart.
Has anyone had any success in getting this to work for Kickstart, or an alternative approach?
Thanks in advance for any insight into this.
Answer: If you want to be able to reference nodes, your view must be taxonomy-based and utilise product categories. The category must be on the display node, not on the product and this is a good starting-point to understanding what's required. To see if this idea is relevant to your use-case, go here: http://www.bookfish.co.za/catalogue/gorongosa-joao-augusto-silva  Bear in mind that I'm not using Commerce Kickstart but various Commerce modules on that site but it should work with CK.
To display my products, I added the following relationships & what I selected there to get it to work I have put in square brackets [ ]:

Content: product [required]
(Products referenced by field_product)Commerce Product: Referencing Content [required]
(Content referencing products from field_product) Content: Taxonomy terms on node [required, select the vocabulary you want, identifier: term]
(term)Taxonomy term: Content using Category [required, identifier: field_category]
(field_category) Content: Category (field_category) [required, relationship: field_category, identifier: term from field_category]
Content: product [required, relationship: field_category, products referenced by field_product]

for contextual filters:

(field_category) Content: Nid [Relationship: field_category,

When the filter value is NOT available:
select "provide default value",
"type": Taxonomy term ID from URL
select  "Load default filter from node page, that's good for related taxonomy blocks" and "Limit terms by vocabulary"
select your relevant category
"Multiple-value handling" select "Filter to items that share all terms" or whatever is relevant to your use case
under "More" select "Exclude"]
Aggregation settings: [Group results together]

Content: Nid [Relationship: do not use a relationship,

When the filter value is NOT available:
select "provide default value",
"type": Content ID from URL
When the filter value IS available or a default is provided:
select "Specify validation criteria"
Validator: "Content"
Content types: select the relevant product display
Filter value format: "Node ID"]
Aggregation settings: [Group results together]
I then selected a view format of fields showing title, image, price and hidden fields of "add to cart form" and "stock" so that I could filter to relevant products that are in stock. For aggregation, I used "Group results together" and "entity ID"


Passagem de parâmetros de uma Activity para outra

Question: Preciso passar o nome de um produto selecionado numa ListView para ser apresentado em um EditText.
Atualmente estou na tela que o usuário informa o cliente e em seguida abre a tela de novo pedido, nessa tela tenho um botão para selecionar um produto dessa ListView.
Problema: Quando entro na Activity da lista e seleciono o produto, ele da start em uma nova tela de novo pedido reiniciando as informações do cliente e mostrando apenas o nome do produto no EditText.
Como eu evito a nova carregar atualizo apenas o EditText?
Comment: Esta um bocado confusa, não percebi bem o que pretendes.
Answer: Boa tarde, talvez eu tenha ficado um pouco confuso com sua descrição, mas tentarei responder pelo que entendi, para passar as informações de uma activity para outra basta reutilizar o bundle e ir passando adiante de activity em activity.
exemplo:
//código para obter o bundle da activity anterior
Bundle bundle = getIntent.getExtras();

//obter alguma informação do bundle
String nome = bundle.getString("nome");

//adiciona alguma informação no bundle
bundle.putInt("idCliente", idCliente);
bundle.putFloat("valorProduto", valorProduto);

//passa o bundle para a próxima activity
startActivity(suaIntent.putExtras(bundle));

e quanto a iniciar uma nova tela experimente utilizar o método startActivityForResult ao invés de apenas startActivity para iniciar a lista. Com isso você retorna um resultado para a activity anterior.
Aqui tem um tutorial sobre como retornar um resultado de uma activity.
Comment: Então eu tinha testado assim, só que quando eu dou um startActivity ou até pelo For result, ele pega a minha activity de novoPedido que contem os dados do cliente e apaga.
Comment: Olha o meu código que tenho no momento.

' Intent intent = new Intent(ListaProdutosBD.this,
    NovoPedidoActivity.class);
  // Usadao para a passagem de parâmetro no Android melhor do que ficar
  // copiando.
  Bundle parametro = new Bundle();
  parametro.putString("nmProd", produtoSel = ((TextView) view).getText()
    .toString());
  // produtoSel = ((TextView) view).getText().toString();
  intent.putExtra("produto", produtoSel.toString());

  //startActivityForResult(intent, SELECIONAR_PRODUTO);
  finish();'
Comment: faça a activity for result na tela de pedido, ela vai chamar a lista de produtos e assim que ela terminar, vai retornar com o resultado como no exemplo que tem nessa pergunta do SOen [aqui](http://stackoverflow.com/questions/10407159/android-how-to-manage-start-activity-for-result)
Answer: Quando você chama o método finish(); o Android remove a activity da pilha e não tem como retornar para ela. Se não for isso poste as classes para maior entendimento.


How to load a sandbox project via composer and enable other devs on project to commit to the sandbox project

Question: I'm working on an install profile right now in Drupal (https://www.drupal.org/sandbox/jnicola/3277854). I want to while developing the next project we're on also build this out during the initial part of building our site out.
I can load the sandbox project via composer no problem, and it's checked out via git, but when I run git status I get "HEAD detached at 56eaaa5"
I'd like the sandbox repo to be checked out on the active development branch, and I want to be able to work inside of that project inside of Drupal in general.
It is fairly important that this is brought in via composer as well, since I will be adding modules requirements into the sandboxes composer.json file for the overall project, so I believe bringing in the repo as a "submodule" wouldn't work, even though that is the desired functionality.
Comment: My answer below is the way. Avoid Git submodules.
Comment: Yes, git submodules are needlessly complex for this line of work usually.
Answer: Reference this project version in composer.json as 1.0.x-dev. This is documented by Composer. Composer checks out a commit, so cd into the project working copy and type git checkout 1.0.x.
In detail, composer.json should contain this in the repositories section:
        {
            "type": "vcs",
            "url": "https://git.drupalcode.org/sandbox/jnicola-3277854.git"
        }

Then you type:
composer require 'drupal/simple_grouped_content:1.0.x-dev'
cd profiles/contrib/simple_group_content
git checkout 1.0.x

This is a Composer question rather than a Drupal question.
Comment: Yes, they commit and push to that sandbox, every time you composer update (module) it will pull changes.
Comment: Use `1.0.x-dev@dev` if there is a conflict with the minimum-stability set in this project.
Comment: Is there a way to make this work where the branch is checked out by default and not starting in a detatched state?

It's minor, I know, but my teammates will use any excuse to complain about this methodology, no matter how minor.
Comment: That's a Composer question. I am not sure there is a way. See also https://drupal.stackexchange.com/questions/291875/how-can-i-prevent-composer-from-detaching-a-modules-head
Comment: Here is the same question again, ten years ago: https://stackoverflow.com/questions/12284090/no-branch-when-installing-with-composer-json It as answered by the Composer team lead. But the OP actually opened the feature request as asked, and according to the feature they did change the behavior but were concerned about side effects: https://github.com/composer/composer/issues/1164  Maybe they reverted it.


Oracle SQL Developer accessing SYS packages with a different schema

Question: Using Oracle SQL Developer I'm trying to access a given package that has been created by SYS and in which the, say, FOO schema has EXECUTE and DEBUG permissions, in fact executing a desc will produce the following output:
desc SYS.PKG_MY_PACKAGE

PROCEDURE      Argument Name Type     IN/OUT Default
-------------- ------------- -------- ------ -------
PRC_MY_PROCESS P_MY_ARGUMENT VARCHAR2 IN     unknown

The problem is such package is not visible under Connections > My Connection > Packages.
Any feedback will be sincerely appreciated. Thanks much in advance.
Answer: The only way I've found to do this is to select "Other Users" under My Connection, expand the SYS user, and go to Packages in there.
IOW,
Connections > MyConnection > Other Users > SYS > Packages

Comment: thanks much for your reply. This definitely solves my problem. I really appreciate your contribution given that I was being pressed to install a different product just to accomplish such task.
Answer: Well you could start by creating an alias to the package your are trying to access under the schema you are using, but you will need to have all permissions on all objects this package is accessing/modifying and on the execute permission on package itself for everything to work correctly
Answer: Is this is a genuine example?  That is, have you created a package called PKG_MY_PACKAGE in the SYS schema?
This is very bad practice.  The SYS schema is key to the successful running of the database.  Building objects in that schema can make exports, etc difficult.  Even worse is when we use CREATE OR REPLACE to apply our code and overwrite an existing PL/SQL package.
So, please, create new schemas for all your code.  If the schema needs additional powerful privileges like SYS then grant them.  But don't contaminate SYS.  This also applies to SYSTEM and indeed any of the other schemas which Oracle installs.
Changing the SYS schema from the Oracle-supplied state is bad practice.


How to install Hive Metastore in Kubernetes?

Question: I am working on a project on Kubernetes where I use Spark SQL to create tables and I would like to add partitions and schemas to an Hive Metastore. However, I did not found any proper documentation to install Hive Metastore on Kubernetes. Is it something possible knowing that I have already a PostGreSQL database installed ? If yes, could you please help me with any official documentation ?
Thanks in advance.
Answer: Hive on MR3 allows the user to run Metastore in a Pod on Kubernetes. The instruction may look complicated, but once the Pod is properly configured, it's easy to start Metastore on Kubernetes. You can also find the pre-built Docker image at Docker Hub. Helm chart is also provided.
https://mr3docs.datamonad.com/docs/k8s/guide/run-metastore/
https://mr3docs.datamonad.com/docs/k8s/helm/run-metastore/
The documentation assumes MySQL, but we have tested it with PostgreSQL as well.


SEM - Direct and Indirect effect contribution

Question: I'm trying to understand how the direct and indirect impact on a SEM using the plspm package.
The structure path of the model is the following :

After estimating I get the following results :
  relationships    direct indirect     total
   IMAG -> SAT 0.3757397 0.000000 0.3757397
   IMAG -> LOY 0.1228504 0.225799 0.3486493
   SAT -> LOY 0.6009453 0.000000 0.6009453

My question comes when trying to decompose LOY how the effect of IMAG should be measured, by using direct and indirect or total?
For example the following are true:
LOY_fitted = Intercept + 0.6009453*SAT + 0.1228504*IMAG
SAT_fitted = Intercept + 0.3757397*IMAG

However when I try to include the indirect contribution of IMAG the result is different from the Fitted values
LOY_fitted ≠ Intercept + 0.6009453*SAT + 0.1228504*IMAG + 0.225799 *IMAG

which one would be the correct way to measure the impact of total impact of IMAG to LOY?
Code to reproduce :
library(plspm)
data(satisfaction)
IMAG = c(0,0,0)
SAT = c(1,0,0)
LOY = c(1,1,0)
sat_path = rbind(IMAG, SAT, LOY)
sat_blocks = list(1,20,24)
sat_mod = rep("A", 3)
satpls = plspm(Data = satisfaction, path_matrix = sat_path, blocks = sat_blocks,
               modes = sat_mod,scaled = FALSE)
satpls$inner_model
satpls$effects

Answer: Your expansion of LOY is incorrect. The indirect effect of IMG on LOY is the effect that goes through SAT. Hence it should be included by substituting SAT by its expression in terms of IMG.
Here I have shortened the variable names to I, S, and L; and I have rounded the coefficients a bit:
$$
S = b + 0.38I,
$$
and so
$$
\begin{align*}
L &= a + 0.6S + 0.12I \\
&= a + 0.6(b + 0.38I) + 0.12I \\
&= (a + 0.6b) + 0.6\cdot 0.38I + 0.12 I \\
&= c + 0.228I + 0.12I \\
&= c + 0.348 I,
\end{align*}
$$
which is what's reported as the total effect of IMG on LOY. Note that your expansion would be correct if you dropped the LOY term as you see from the second to last line above.
We see that to get the indirect effect we simply multiply coefficients along the path from IMG to LOY via SAT: $0.6\cdot 0.38$ is the product of SAT's coefficient in the one expression and IMG's coefficient in the other.
NB that the package plspm seems to be no longer supported and has been removed from CRAN. Hence your reproducible example is hard to reproduce and I haven't tried to do so.


How to update a feature

Question: I have a feature which contains fields for the user profile page. This is currently working in PROD.
In the dev site, I've updated the feature to include a new field, updated the version, and download a new TAR file.
In PROD, when I go to Update Module, and try to update the feature, an error message appears saying the feature is already installed.
Am I missing something here? Are features only expected to be installed once? Or do I need to manually remove the feature before updating?
Would it be better practice to create a brand new feature containing the one field?
Answer: when it's structure only, you will have to upload your dev feature, replace it with the production one and revert the production feature.
Comment: I can't upload the feature because Drupal says the module is already installed. And won't reverting the current feature remove the existing fields from the database, so I lose data?
Comment: you will have to overwrite the existing feature with the new one. as long as the state of the feature is still default (not overridden) the fields are defined by code. replacing the feature wont change anything but adding the new field than. if you have unstaged changes in your production database, you will want to clear those conflicts in the updated feature and feature revert it. http://drupal.org/node/582680 you will probably lose data if you delete a field that was present before. As always: do a backup
Comment: So are you suggesting - Update the feature on dev to add  updates to the existing feature, push it to production and then revert it?
Comment: yes, that should cover most of it, some stuff might be done using custom hook_update_n functions though..
Answer: Drush is invaluable for managing features.

Install drush - drush manual page.
Copy files over existing feature.
Run "drush fr myfeature" on the command line.

That is put a feature back (features-revert) to the way it was before you experimented making changes in the user interface.
Drush can also be useful to update the feature (features-update):
drush fu myfeature

Create a "diff" between what has been changed using the user interface and what is stored in the feature:
drush fd myfeature

How to update a feature


Proving that $L_{22}L_{22}^T=S$ is the Schur complement of a Cholesky factorization

Question: Let $A$ be an $(n+m) \times (n+m)$ symmetric positive definite matrix
$$A=\begin{bmatrix}A_{11} & A_{12}\\ A_{12}^T & A_{22}\end{bmatrix}$$
where $A_{11}$ is an $n \times n$ matrix, $A_{12}$ is an $n \times m$ matrix, and $A_{22}$ is an $m \times m$ matrix. We can factor $A$ into $LL^T$, as follows:
$$A=\begin{bmatrix}L_{11} & 0\\L_{21} & L_{22} \end{bmatrix}\begin{bmatrix}L_{11} & 0\\L_{21} & L_{22} \end{bmatrix}^T \text{,}$$
where $L_{11}$ is an $n \times n$, $L_{21}$ is $n \times m$, and $L_{22}$ is $m \times m$. I want to show that $S=L_{22}L_{22}^T$ where $S=A_{22}-A_{12}^TA_{11}^{-1}A_{12}$ is the Schur complement of $A_{11}$.
I'm stuck trying to unravel how to apply this to block matrices.  I'm having a bit of a conceptual hurdle translating my definitions to this problem.
Answer: We know that
$$
A=\left[\matrix{A_{11} & A_{12}\\ A_{12}^T & A_{22}}\right]=\begin{bmatrix}L_{11} & 0\\L_{21} & L_{22} \end{bmatrix}\begin{bmatrix}L_{11}^T & L_{21}^T\\0 & L_{22}^T \end{bmatrix}=
\left[\matrix{L_{11}L_{11}^T & L_{11}L_{21}^T\\ L_{21}L_{11}^T & L_{21}L_{21}^T+L_{22}L_{22}^T}\right].
$$
Since we assume that $A_{11}=L_{11}L_{11}^T$ is invertible then
$$
\color{red}{A_{11}^{-1}}=(L_{11}L_{11}^T)^{-1}=\color{red}{(L_{11}^T)^{-1}L_{11}^{-1}}.
$$
Now let's see what $S$ is
$$
S=\color{blue}{A_{22}}-A_{12}^T\color{red}{A_{11}^{-1}}A_{12}=\color{blue}{L_{21}L_{21}^T+L_{22}L_{22}^T}-L_{21}\underbrace{L_{11}^T\color{red}{(L_{11}^T)^{-1}L_{11}^{-1}}L_{11}}_{=I}L_{21}^T=L_{22}L_{22}^T.
$$


How to replace certain character in php

Question: I need someone who can make the following output which is a single string
[{"mobile":"XXX-XXX-XXXX","permaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}","tempaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}"}]1

to
{"mobile":"XXX-XXX-XXXX",
"permaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}",
"tempaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}"}
Help me removing first '[' and last ']1' in the above string. Thanks in advance
Comment: Please check this https://stackoverflow.com/questions/7045618/delete-first-character-and-last-character-from-string-php
Answer: This should work for you.
$final_str =  rtrim(ltrim($your_str, '['), ']1');

Answer: This will remove first and last character from your string
$result = substr($string, 1, -2);

Here is the link if you want to explore more:
https://www.w3schools.com/php/func_string_substr.asp
Answer: Try ltrim() and rtrim()
$str = '[{"mobile":"XXX-XXX-XXXX","permaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}","tempaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}"}]1';
$getTrim = ltrim($str, '[');
$getTrim =  rtrim($getTrim, ']1');
echo $getTrim;

OR
$getTrim =  rtrim(ltrim($str, '['), ']1');

Answer: Try below code,
<?php
$str = '[{"mobile":"XXX-XXX-XXXX","permaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}","tempaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}"}]1';
$temp_str = preg_replace('/\[/',"",$str);
$new_str = str_replace("]1","",$temp_str);
echo $new_str;
?>

Output,
{"mobile":"XXX-XXX-XXXX","permaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}","tempaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}"}

Answer: you can use str_replace or preg_replace replace your keyword with empty string.

How to replace certain character in php


Trying to populate the JSON data into listview

Question: I am trying to learn how to populate JSON data into android ListView
My JSON URL:: http://126.96.36.199:7000/

I am trying to parse the data from a server and fetch the JSON and
parse it to populate the data to listView.
Having difficulty in completing the required task

ANY IDEAS

ListAdapter.java
public class ListAdapter extends ArrayAdapter<Item> {
    private List<Item> items;
    public ListAdapter(Context context, int resource, List<Item> items) {
        super(context, resource, items);
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        TextView tt = null;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.itemlistrow, null);
            tt = (TextView) v.findViewById(R.id.RestaurantNameID);
        }

        Item p = items.get(position);
        if (p != null) {
            if (tt != null) {
                tt.setText(""+p.getName());
            }

        }
        return v;
    }
}

JSONParser.java
public class JSONParser {

    static InputStream is = null;
    static JSONArray jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Item.java
public class Item{
    private String Name;

    public Item(String name){
        this.Name = name;
    }
    public String getName(){
        return Name;
    }
}

AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {

    // url to make request
    private static String url = "http://126.96.36.199:7000/";
    List<Item> yourData = new ArrayList<Item>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONArray json = jParser.getJSONFromUrl(url);

        try {
            for (int i = 0; i < json.length(); i++) {
                JSONObject c = json.getJSONObject(i);

                // Storing each json item in variable
                String NAME=c.getString("restaurantNAME");

                yourData.add(new Item(NAME));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ListView yourListView = (ListView) findViewById(R.id.listViewID);
        ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);
        yourListView.setAdapter(customAdapter);
        yourListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // When clicked, show a toast with the TextView text
                if(position == 0)
                {
                    //code specific to first list item
                    Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee1.class);
                    startActivity(myIntent);
                }else if(position == 1)
                {
                    Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee2.class);
                    startActivity(myIntent);
                }

            }
        });
    }
}

MANIFEST
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".AndroidJSONParsingActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".Employee1"
            android:label="@string/app_name" >
        </activity>

        <activity
            android:name=".Employee2"
            android:label="@string/app_name" >
        </activity>

    </application>

Employee1.java
public class Employee1 extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.employee1);

        Button btn1=(Button) findViewById(R.id.button1);

        btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent emp1=new Intent(Employee1.this,AndroidJSONParsingActivity.class);
                startActivity(emp1);
            }
        });
    }
}

itemlistrow.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_height="wrap_content" android:orientation="vertical"
             android:layout_width="fill_parent">

    <TableRow android:layout_width="fill_parent"
              android:id="@+id/TableRow01"
              android:layout_height="wrap_content">

        <TextView
                android:id="@+id/RestaurantNameID"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="age" android:textStyle="bold"
                android:gravity="left"
                android:layout_weight="1"
                android:typeface="monospace"
                android:height="40sp"/>
    </TableRow>
</TableLayout>

android_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/listViewID"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center">
    </ListView>

</LinearLayout>

LogCat-Output
08-05 10:49:33.429: D/AndroidRuntime(449): Shutting down VM
08-05 10:49:33.429: W/dalvikvm(449): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-05 10:49:33.471: E/AndroidRuntime(449): FATAL EXCEPTION: main
08-05 10:49:33.471: E/AndroidRuntime(449): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.coolnet2/com.example.coolnet2.MainActivity}: java.lang.ClassNotFoundException: com.example.coolnet2.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.coolnet2-2.apk]
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.os.Looper.loop(Looper.java:123)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread.main(ActivityThread.java:3683)
08-05 10:49:33.471: E/AndroidRuntime(449):  at java.lang.reflect.Method.invokeNative(Native Method)
08-05 10:49:33.471: E/AndroidRuntime(449):  at java.lang.reflect.Method.invoke(Method.java:507)
08-05 10:49:33.471: E/AndroidRuntime(449):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-05 10:49:33.471: E/AndroidRuntime(449):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-05 10:49:33.471: E/AndroidRuntime(449):  at dalvik.system.NativeStart.main(Native Method)
08-05 10:49:33.471: E/AndroidRuntime(449): Caused by: java.lang.ClassNotFoundException: com.example.coolnet2.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.coolnet2-2.apk]
08-05 10:49:33.471: E/AndroidRuntime(449):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
08-05 10:49:33.471: E/AndroidRuntime(449):  at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
08-05 10:49:33.471: E/AndroidRuntime(449):  at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
08-05 10:49:33.471: E/AndroidRuntime(449):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
08-05 10:49:33.471: E/AndroidRuntime(449):  ... 11 more

Thanks,
Comment: Check the all activity classes have in same package. That is the package name declare in manifest
Comment: @ sunil & @ Hemant ........... Please look at the Updated manifest file and log cat ... i still have some issues
Comment: xml file means please put your res/layout file then i will check what is actually error.
Comment: @ Hemant .... I have added the XML file
Answer: Do you have MainActivity.java class file in your project that you have declared as the launcher activity in your manifest file?
Comment: Please look at the Updated manifest file and log cat ... i still have some issues
Comment: @sky Try cleaning your project and build it again and then run. Do you have any MainActivity class in your project now?
Comment: I have cleaned the project ...... AndroidJSONParsingActivity.java is the main class in this project where Oncreate method is there
Comment: @Sky you may send it today, but I will be able to give it back to you tomorrow morning
Comment: Please can you give me your mail ID
Comment: Thanks, Please check your mail !
Comment: @ Mohit Verma ....... Thanks a Lot mohit .... your Solution works like a charm :)
Answer: It seems there are many issues:

1) You haven't declared all activities properly in AndroidManifest.xml
  file.

=> If AndroidJSONParsingActivity is your main/launcher activity then declare it as Launcher activity inside AndroidManifest.xml file.

2) You are calling web API directly on Main UI Thread, that will give
  you NetworkOnMainThreadException.

=> To resolve this issue, cover Web API and long running task inside AsyncTask.
// getting JSON string from URL
 JSONArray json = jParser.getJSONFromUrl(url);

Write this code inside doInBackground() method of AsyncTask
Comment: @Sky It seems you are launching `AndroidJSONParsingActivity` activity from `Employee1` so `Employee1` should be your launcher activity I think.
Comment: Please look at the Updated manifest file and log cat ... i still have some issues
Comment: senario ... is like this :: There is list ( List of Restaurant names ) ..... onclick of it I need to launch a activity (employee1 etc) .... Hey can i send you the project file through ... if u dont mind .... I am scratching my head on this simple task ......
Comment: If you could give me your mail ID .... I can share my file ... it will be a great help to me Paresh
Comment: @Sky sorry for it. but I have a great **[e-book](http://d.android.com/)** for you to learn any topics of Android development.
Comment: http://www.techrepublic.com/blog/android-app-builder/androids-indeterminate-progressdialog-tutorial/              ............. Have a look at the tutorial regarding doing Async tasks in background


Android: changing density for game performance?

Question: I currently have a note 4 which has a high resolution screen (2560x1440) that, when playing in the native resolution, doesn't perform well somtimes.
I have found apps on the play store that will allow resolution changes but all require root (at&t version is currently unrootable).
I can however change the density of the screen without root.
I'm curious if I would receive the same performance boost changing density as I would changing resolution?
Answer: Highly unlikely.
The resolution defines number of pixels displayed on the screen. When you change the resolution, the system changes the size of all image buffers used for rendering. It means that there is different numer of pixels to shade and draw.
On the other hand there's the density, which define, how much pixels you can fit on one inch of the physical screen. The density changes an internal matrix used for scaling images. The operation is always same. In apps with native Android UI you may gain a small boost, because by changing the density value you can change the density type of your screen (medium, high, xhigh, etc.). This will change the drawable folder used by the app to the (potentially) smaller one, which will result in faster image loading and messed up UI.
This trick won't work for the games, because in most cases games don't care about the drawable folders.


TradingView alerts: how to setup a delay?

Question: I'm reading a lot about it but can't find a way.
I have a strategy doing like
strategy.close("SELL", alert_message=closeShort_msg)
strategy.entry("BUY", etc.

And I wish to delay the second signal, so to be sure the first one gets executed.
Can someone tell me why this method doesn't produce any trades? Strategy says "nothing to display".
 t1 = time
 strategy.close("SELL", alert_message=closeShort_msg)
 if time >= (t1+2000)
     strategy.entry("BUY", etc.

I also tried with
timenow

but nothing changed.
Answer: I think your order of execution is good and should function correctly within Tradingview backtester. However, if you want to add a delay because your API is not executing the second signal because it happens to receive the second signal before the first one then what you can do is add a delay to second signal that Tradingview sends to the API.
e.g.
strategy.close("SELL", alert_message=closeShort_msg)

strategy.entry("BUY", etc).

alert('{  "message_type": "bot",  "bot_id": xxxxxxx,  "email_token": "xxxxxx",  "delay_seconds": 10}', alert.freq_all)

This should add a 10 seconds delay for the API to execute the strategy.entry signal.
Hope this helps.


Cucumber/Capybara not finding simple_form field

Question: When I view source the id of the text field matches what I am calling for in the test.
Here is the form field:
<fieldset class="fsStyle">
        <legend class="legendStyle">*** Summarize Your Edits for History/Timeline ***</legend>
        <%= f.input :latest_update, input_html: { id: 'blurb' } %>
        <%= f.input :send_update %>
    </fieldset>

here is the cuke feature:
```
<code>Feature: Edit article with blurbs
  In order to send a clear update
  As an editor
  I want to add a summary of my edits

Scenario: Article Edit With Blurb
  Given I am on the show page
  And I follow "Edit"
  When I fill in "blurb" with "This is my edit summary"
  And I press "Update Article"
  And visit the history page
  Then I should see "This is my edit summary"
</code>
```
the step definition:

Given(/^I follow "(.*?)"$/) do |link_name|
  click_link link_name
end

the view source:
```
<code><fieldset class="fsStyle">
        <legend class="legendStyle">*** Summarize Your Edits for History/Timeline ***</legend>
        <div class="form-group text optional article_latest_update"><label class="text optional control-label" for="blurb">Latest update</label><textarea id="blurb" class="text optional form-control" name="article[latest_update]">
a test update to check boolean</textarea></div>
        <div class="form-group boolean optional article_send_update"><div class="checkbox"><input value="0" type="hidden" name="article[send_update]" /><label class="boolean optional" for="article_send_update"><input class="boolean optional" type="checkbox" value="1" checked="checked" name="article[send_update]" id="article_send_update" />Send update</label></div></div>
    </fieldset>
</code>
```
Here is the test output including the error:
```
<code>Using the default profile...
Feature: Edit article with blurbs
  In order to send a clear update
  As an editor
  I want to add a summary of my edits

  Scenario: Article Edit With Blurb                       # features/edit_with_blurbs.feature:6
    Given I am on the show page                           # features/step_definitions/path_steps.rb:4
    And I follow "Edit"                                   # features/step_definitions/general_steps.rb:4
    When I fill in "blurb" with "This is my edit summary" # features/step_definitions/general_steps.rb:8
      Unable to find field "blurb" (Capybara::ElementNotFound)
      ./features/step_definitions/general_steps.rb:9:in `/^I fill in "(.*?)" with "(.*?)"$/'
      features/edit_with_blurbs.feature:9:in `When I fill in "blurb" with "This is my edit summary"'
    And I press "Update Article"                          # features/step_definitions/general_steps.rb:12
    And visit the history page                            # features/step_definitions/path_steps.rb:10
    Then I should see "This is my edit summary"           # features/step_definitions/general_steps.rb:16

Failing Scenarios:
cucumber features/edit_with_blurbs.feature:6 # Scenario: Article Edit With Blurb

1 scenario (1 failed)
6 steps (1 failed, 3 skipped, 2 passed)
0m1.739s
</code>
```
...
Comment: Is there unique text that would be on the edit page?  If so add a check for that before the "fill in" step.  One other thing to verify is that the field is actually visible on the page, this is often an issue when using JavaScript widgets that hide the real field and display a different field instead, or use overlayed elements to polyfill placeholder behavior, etc.
Comment: Are you sure the "Edit" link is actually being correctly followed?  Also is whatever you have Capybara.default_max_wait_time (default_wait_time if using Capybara < 2.5.0)  long enough for the edit page to complete loading?
Comment: I edited the question to include the full test output.  It seems to show the Edit page being visited, but I am not sure how to verify that.
Answer: If you are sure that the page is open then you can set the field by:
find(:id, "blurb").set("This is my edit summary")


Eloquent Laravel - Coluna user_id

Question: Olá, estou aprendendo laravel e não achei isso em nenhum fórum. Tenho algumas tabelas que tem uma chave estrangeira chamada 'user_id', porém quando vou salvar um objeto no banco sempre tenho que preencher essa coluna. Tem como eu 'ensinar' o laravel que sempre que vou criar um objeto a coluna user id se refere à auth()->user()->id?
Eis como estou fazendo:
$data = $request->all();
$data['user_id'] = auth()->user()->id;
UmObjetoQualquer::create($data)

Comment: Não deu certo a resposta?
Answer: Precisa ser criado um observador onde no método antes de criar um novo registro (creating) pode configurar um valor para esse model, um exemplo minimo:
Criado um model dentro da pasta App com o nome de Test:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
    protected $fillable = ['name','user_id'];
    protected $primaryKey = 'id';
}

Crie dentro da pasta App uma outra pasta com o nome de Observers e dentro dessa pasta um TestObserver.php com o seguinte código:
<?php namespace App\Observers;

use App\Test;

class TestObserver
{
    public function creating(Test $model)
    {
        $model->user_id = auth()->user()->id;
    }
}

e para que esse observe seja executado no momento antes de salvar os dados na base na pasta app\Providers abra o arquivo AppServiceProvider e dentro do método boot adicione a seguinte linha:
Test::observe(TestObserver::class);

Atenção: não esqueça de colocar os uses, exemplo completo do AppServiceProvider.php:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Observers\TestObserver;
use App\Test;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Test::observe(TestObserver::class);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

com essas devidas configurações todas as vezes que tentar criar um novo registro para um determinado model configurado automaticamente o valor do usuário logado será passado para o model e logo após serão salvos com os outros dados que já foram passados.
Nota que além do método creating que refere-se ao modelo antes de salvar os dados existe outros como:

retrieved
creating
created
updating
updated
saving
saved
deleting
deleted
restoring
restored

que podem ser configurados, mas, o exemplo dado é referente a sua pergunta.
Referencia:

Observers
Laravel: Model Observers
Using Laravel Model Observers
Model events and Observers in Laravel 5.0
Comment: Não deixe de aceitar se for útil @JhonnyIzidoro
Comment: Obrigado pela atenção, não é tão difícil. Eu leio a documentação mas a do Laravel eu não consigo entender tão fácil igual a do bootstrap, sou novo nisso. Obrigado (:
Comment: Funcionou (:...
Answer: É só você colocar no model User o campo "user_id" nos fillables.
class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;

    protected $fillable = [
        'id','name', 'email', 'password','user_id'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

}

Dessa forma você não irá precisar especificar para salvar, assim como os demais campos.
Comment: Vou testar, assim é bem simples, obrigado!

Eloquent Laravel - Coluna user_id


Fazer um javascript funcionar dentro de uma URL

Question: O código javascript abaixo funciona perfeitamente no HTML do meu site. Ele é um servidor geo-target que mostra a cidade baseado no IP do usuário.

O que estou querendo fazer e não consigo é fazê-lo funcionar dentro de um link que pretendo que seja gerado de acordo com a cidade da pessoa. Tipo:
Belo Horizonte

Eu tentei fazer funcionar da maneira abaixo mas a resposta ao final da URL, após ?q= é o próprio código. Tentei desta forma:
Belo Horizonte

Eu sou um pouco leigo nesse assunto portanto qualquer solução seja ela em PHP ou javascript seria bem vinda. Desde já agradeço!
Comment: Podes explicar melhor o que queres fazer, ou melhor: o que deve acontecer quando o usuário clica no link? Essa deteção está a ser feita em PHP?, podes colocar esse código de geo-target aqui?
Answer: Se percebi o que queres fazer, tens que fazer algo do género:


Problem Sending data send to a block

Question: after form submit in a page its return some value,I want to prnt this value in a block .how can I do this?
and I want the form and the block are in the same page.
Answer: Use hook_block_info and hook_block_view. Something like this:
function MYMODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'my_block':

      $blockContent = '
Nothing to show
';

      // assuming we're getting it from POST but the source can be whatever you want
      if (isset($_POST['key']) && null != $_POST['key']) {
          $blockContent = '
' . $_POST['key'] . '
';
      }

      $block['subject'] = t('My Block Title');
      $block['content'] = array(
          '#markup' => $blockContent
      );
      break;
  }

  return $block;
}

Problem Sending data send to a block


What are the steps to simplify the following equation (with simplified version included)

Question: This is part of a question asking to find the differential of a polynomial fraction. I have already taken the derivative using quotient and chain rule, and this is where I am up to.
Rather than go through the entire question (I have been told this is too confusing for readers in previous questions), I will simply show the area where I am stuck.
I need to know how to simplify :
$$\frac{\sqrt{2x-x^2}-\frac{-x+1}{\sqrt{2x-x^2}}x}{(\sqrt{2x-x^2})^2}$$
to :
$$\frac{x}{(2x-x^2)^{3/2}}$$
Any help with this would be very much appreciated , exam is tomorrow .
P.S. If users would prefer me to write out the full question, just ask and I will. I am still learning to write the perfect question.
Comment: not clear what you mean by $2x^{\_2}$
Comment: Thanks for pointing that out, it has been corrected .
Comment: This has nothing whatsoever to do with [division-algebras](http://math.stackexchange.com/tags/division-algebras/info). Please read tag wikis before using a tag you are unfamiliar with.
Answer: $$\frac{\sqrt{2x-x^2}-\frac{-x+1}{\sqrt{2x-x^2}}x}{(\sqrt{2x-x^2})^2}=\frac{\frac{2x-x^2}{\sqrt{2x-x^2}}-\frac{-x+1}{\sqrt{2x-x^2}}x}{(\sqrt{2x-x^2})^2}=\frac{\frac{2x-x^2+x^2-x}{\sqrt{2x-x^2}}}{(\sqrt{2x-x^2})^2}$$
Can you continue from here?
Comment: I am currently working through this part, During the transition from the 1st part to the 2nd part I would expect the right numerator to be multiplied by the left denominator, why is this not so ?
Comment: I am only expanding the first expression with the denominator from the second to have a common denominator.
Comment: Okay im really sorry to sound like an idiot, I thought that the process was 1. multiply denominators to get common denominator, 2. left numerator x right denominator, 3. right numerator x left denominator. I see that you have done step 1 and 2, but it looks as if you have skipped 3 and starting simplifying the top without multiplying the right numerator by the left denominator. Could you please explain what I am missing here ?
Comment: left denominator is 1.
Comment: Hasn't the left denominator already been converted to sqrt(2x-x^2) after step 1?
Comment: After step 1 you allready have the same denominators. The x belongs to the (-x+1).
Answer: Look at it as $(\sqrt A-(-x+1)x/\sqrt A)/(\sqrt A)^2$ with $A=2 x-x^2.$
Assuming $A> 0$ we have $(\sqrt A)^2=A=2 x-x^2,$ which,so far,is a simpler denominator. (Actually the notation $\sqrt A$ should only be used when $A\geq 0.$ And we must have $A\ne 0$ else we have a denominator $0$.)
Now get rid of that pesky minus-sign between the two terms of the numerator by re-writing the numerator as $\sqrt A+(x-1)x/\sqrt A$ and re-write this as $\sqrt A+(x^2-x)/\sqrt A .$
The big step now is to multiply both the numerator and denominator by $\sqrt A$ to remove the occurrence of a denominator $\sqrt A$  within the numerator of the whole expression. This gives us $((\sqrt A)^2+\;x^2-x)/ (A\sqrt A).$
Once again we have $(\sqrt A)^2=A$ so we can write the numerator as $A+(x^2-x).$ But what is $A$? It's $2 x-x^2.$ So the numerator is $(2 x-x^2)+(x^2-x).$ Now look for a re-grouping or for terms that cancel out: $2 x-x^2+x^2-x=2 x-x=x $ is  now the numerator.
So we obtain $x/(A\sqrt A)=$ $x/(A^{3/2})=$ $x/(2 x-x^2)^{3/2}.$
We can also at this point divide both the numerator and denominator by $\sqrt x$ to obtain $\sqrt x/(2-x)^{3/2}$ and, if we like, write this as $(x/(2-x)^3)^{1/2}$.


How to install Docker on AWS EC2 instance with AMI (CE/EE Update)

Question: What is the current way of installing Docker on an AWS EC2 instance running the AMI?
There has been an announcement of Docker Enterprise Edition and now I want to know if anything has changed.
Until now, I have been using yum install docker and do get a Docker versioned at 1.12.6, build 7392c3b/1.12.6 right now (3/3/2017). However, the Docker repository on GitHub tells me that there are already newer releases.
I remember the official Docker (package) repository having a package named docker-engine replacing docker some time ago and now they seem to split the package up into docker-ce and docker-ee, where e.g. "Docker Community Edition (Docker CE) is not supported on Red Hat Enterprise Linux." [Source]
So is or will it still be correct to use the above to get the latest stable Docker version on EC2 instances running the AMI or do I need to pull the package from somewhere else (and if so which one, CE or EE)?
Comment: Did you read the AWS documentation on how to install Docker standard? If so what part of it didn't work, or what issues didn't it address? http://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html
Comment: I suppose Amazon will update it when they get around to it. Though you know of course that nobody should be using Amazon Linux for anything.
Comment: The question is whether I can continue to do it like this. As already mentioned it'll install me Docker versioned at 1.12 which is already one if not more minor version updates behind the latest stable release (1.13, before CE/EE) and I wonder if this is due to the usual repository update delay or because the guide and package simply being outdated which requires some replacement work done by me (e.g. somehow getting Docker from their own repository?). Also concerning the latest EE announcement which might change something...
Comment: Running what AMI?
Comment: @MichaelHampton the latest one for HVM, Amazon Linux AMI 2016.09.1.
Comment: If that is the real solution to this problem this does make me a little sad. However thanks for the hint, I haven't had too much experience with EC2 yet to get to this conclusion by myself. I always thought it's the best to use AMI because it (should be) is the most updated and adapted image concerning the EC2 virtualization.
Comment: The packages are all updated, the kernel. However I do find Ubuntu much easier for software installation and general support, there are few Amazon Linux resources so difficult things are made even more difficult.
Comment: @MichaelHampton Amazon Linux is fine for ECS usage. It's pre-configured for ECS usage, and the underlying OS doesn't matter much in that case.
Comment: @MichaelHampton, `nobody should be using Amazon Linux for anything` so what AMI do you propose then, sir?
Answer: To get Docker running on the AWS AMI you should follow the steps below (these are all assuming you have ssh'd on to the EC2 instance).

Update the packages on your instance
[ec2-user ~]$ sudo yum update -y
Install Docker
[ec2-user ~]$ sudo yum install docker -y
Start the Docker Service
[ec2-user ~]$ sudo service docker start
Add the ec2-user to the docker group so you can execute Docker commands without using sudo.
[ec2-user ~]$ sudo usermod -a -G docker ec2-user

You should then be able to run all of the docker commands without requiring sudo. After running the 4th command I did need to logout and log back in for the change to take effect.
Comment: Like I already mentioned in the question, this indeed works, but installs an outdated version of Docker (still version 1.12.6 on 05/28/2017). While I myself have switched to the Ubuntu image for my EC2 instances, the real thing I wanted to know is how to install one of the current versions of Docker on an AMI image. Because there (at least at the time of the question) was no obvious way to either get an up-to-date Docker CE or a Docker EE installation. That is what this question was about in the first place and that's the reason why I cannot accept it without hesitation. Thank you anyways!
Comment: Did not work for me. So I needed to do this.
sudo yum install yum-utils  ,
and then sudo yum-config-manager --enable rhui-REGION-rhel-server-extras
  , and then sudo yum install docker
Comment: Today yum install installs 17.03.1ce-1.50.amzn1
Comment: @mxscho yes that's also what I'm looking for, so please wait until an answer that addresses the question is posted.
Comment: Note, on RHEL 8 and up, installing Docker will give you Podman: https://stackoverflow.com/questions/59359793/installed-docker-and-i-got-podman
Answer: The hardest part to figure all of this out was the container-selinux requirement.  Just find the latest version in http://mirror.centos.org/centos/7/extras/x86_64/Packages/ and install that first.  In addition EC2 instances may not have a proper entropy generator so haveged may need to be installed.
The rest is taken from https://docs.docker.com/install/linux/docker-ce/centos/ with the addition of haveged and firewalld.  All these have to be done as root so sudo appropriately.
yum install -q -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.42-1.gitad8f0f7.el7.noarch.rpm
yum install -q -y http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/h/haveged-1.9.1-1.el7.x86_64.rpm
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
yum install -q -y firewalld docker-ce
systemctl enable firewalld
systemctl start firewalld
firewall-cmd --add-port=2377/tcp --permanent
firewall-cmd --add-port=2376/tcp --permanent
firewall-cmd --add-port=7946/tcp --permanent
firewall-cmd --add-port=7946/udp --permanent
firewall-cmd --add-port=4789/udp --permanent
firewall-cmd --zone=public --permanent --add-masquerade
firewall-cmd --reload
systemctl enable haveged
systemctl start haveged
systemctl enable docker
systemctl start docker
setenforce 1

Enable SELinux by modifying  /etc/sysconfig/selinux to be
SELINUX=enforcing
SELINUXTYPE=targeted

Then reboot your instance by issuing shutdown -r now
Executing sudo docker version should yield as of the time of this posting...

Client:
 Version:       18.03.0-ce
 API version:   1.37
 Go version:    go1.9.4
 Git commit:    0520e24
 Built: Wed Mar 21 23:09:15 2018
 OS/Arch:       linux/amd64
 Experimental:  false
 Orchestrator:  swarm

Server:
 Engine:
  Version:      18.03.0-ce
  API version:  1.37 (minimum version 1.12)
  Go version:   go1.9.4
  Git commit:   0520e24
  Built:        Wed Mar 21 23:13:03 2018
  OS/Arch:      linux/amd64
  Experimental: false
Comment: Have you tried running Docker on any other AMIs except CentOS? Can you share your expriences?
Comment: I didn't use the centos Ami I used the AMI Linux 2.  The Linux 1 is too old.
Comment: OK, got it. Are CentOS repos you used fully compatible with Amazon AMI?
Comment: Simple paranoia
Comment: Right I use Centos VMs for development using Vagrant, I just had to adapt my scripts so that it works with missing packages.
Comment: In the first comment you said you used AMI Linux 2, and now you says about CentOS VMs :) So do above commands work for Amazon AMI or not?
Comment: I user ami2 in ec2 and centos on my vagrant setup on windows.
Comment: Interesting, your commands worked brilliantly on Amazon 2 AMI, but why to enable SELinux if it's disabled by default in AL? Is it essential for Docker?
Answer: Per https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-optimized_AMI.html

The current Amazon ECS-optimized AMI
  (amzn-ami-2017.09.j-amazon-ecs-optimized) consists of:

The latest minimal version of the Amazon Linux AMI
The latest version of the Amazon ECS container agent (1.17.2)
The recommended version of Docker for the latest Amazon ECS container     agent (17.12.0-ce)
The latest version of the ecs-init package to run and monitor the    Amazon ECS agent (1.17.2-1)

You can see the history at https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-ami-versions.html
Answer: In addition to my previous answer.  If you use Terraform, I have also created a Terraform module that can be used to create a Docker Swarm
https://registry.terraform.io/modules/trajano/swarm-aws/docker
The difference between the approach I had done previously vs the approach I am presently doing with the terraform module is to utilize the AWS provided Docker packages.  This does not include the full docker-compose and what not, but you don't require those packages normally in a server.
Because I am using the one Amazon had provided, it is no longer the latest 18.09 version but the 18.06 version.  However, the set up is simpler and I don't have to play catch up to container-selinux.
The only external dependency I use is EPEL to get haveged because you still need a good random source for some applications.
I also relied on the AWS security groups rather than explicitly setting up firewalld and used the SELinux setting that is defaulted in the AMI image.


File server - going beyond 2TB

Question: Our current main filer server is a Windows 2003 R2 cluster with 3 2TB disks connected to a backend SAN.
Our main issue right now is 1 of the 2TB disk is getting full.
What options do I have?

Mount another disk to a folder within the 2TB volume
Use GPT disks to go beyond the 2TB limit

I'm just looking for feedback to see if there are other options or gotchas with these 2 options from people that have implemented either ones.
Option 1 would be the simplest solution to implement.  I'm just concerned about any ill effects with the volume being at the 2TB limit already.
Thank you.
Answer: I'd go GPT-Dynamic and span the disks (I'm assuming these 2TB volumes are on a RAID Array).
Comment: 2003 cluster doesn't support dynamic disks.  Would have to clone the data to a new GPT disk.
Comment: @ErikA, going after Strunk & White?
Comment: Hehe, I guess I am. :)
Answer: GPT will allow you to create disks larger than 2TB, so long as everything in the storage path is 64bit. One of our storage arrays won't make LUNs that large, so the fact that our 64-bit Win2008 hosts can use them is irrelevant. Our newer array can do so, and we currently are. If you have the option, I'd say go with GPT.
If you're stuck with 2TB LUNs because of a 32bit problem somewhere, spanning the volume over multiple LUNs is your only real choice.
Since you're on a cluster, and Cluster doesn't support dynamic disks (at least not without Veritas Storage Essentials or whatever it's called), you have even fewer options. I'm facing this exact problem right now, and we're contemplating breaking the volume up into multiple LUNs and changing how our users access storage.
Comment: Ultimately, DFS is the way to go but I can't get buy in from management so I'm stuck where I am.
Have to look in to Spanned volumes to see how they behave in a cluster.
So if you can serve up a volume of 3TB either through GPT or volume spanning, are there any issues with clients (XP, W2K, etc.) accessing the volume (shared) at all?
Comment: Clutering can only use basic disks.
Basic disks' maximum volume size is 2TB.
Spanning isn't an option then it looks like.
Comment: Not that I've found. I was doing 3TB volumes with NetWare and our XP clients never blinked. I can't imagine Windows/Windows would be worse.
Comment: @rtek I feel your pain. Really. I'm facing the exact same issue right now. Also, 2TB+ volumes take a really long time to back up.

File server - going beyond 2TB