Error at compiled time in Chrome driver code

Question: I have used this code in MyEclipse for Chrome driver..
System.setProperty("webdriver.chrome.driver","D:\selenium\chromedriver_win_26.0.1383.0.zip\chromedriver.exe");

But found compiled time error that:
'Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )
But path that I have given is correct.
How can I sort this error?
Answer: Try this:
D:\\selenium\\chromedriver_win_26.0.1383.0.zip\\chromedriver.exe

instead of
D:\selenium\chromedriver_win_26.0.1383.0.zip\chromedriver.exe

Answer: Instead of setting this property, you can set the PATH env variable pointing to the directory of the Chrome Driver, so that you don't require code changes once you move code on to other machine


CSS selector * + * definition?

Question: What does the css selector * + * actually mean? You can see it it in google chrome's console when you do an inspect element. According to me it seems like applying a style to "Every second child" , but still want to be sure. Can anyone help me out?
Example:
*+* {
   margin-top:1em;
}

Comment: possible duplicate of [What is the logic behind sibling selectors * + * and * ~ *?](http://stackoverflow.com/questions/16695556/what-is-the-logic-behind-sibling-selectors-and)
Answer: * + * means 'any element that has a previous sibling' - in other words, is not a first child.
Answer: plus sign (+) means, if the second selectors directly is a sibling to the first selector:
h1+h2 {margin: 1em;}

h2 {margin: 2em;}

all h2 have 2em margin, except the one that directly follows a h1, that one has 1em margin.
hopes that will make it clear for you
Answer: As Specified in W3C documentation it represents the "Adjacent Sibling Combinator".
div + p
Selects all
 elements that are placed immediately after
 elements
Answer: Same as *:not(:first-child) but is shorter. I would prefer to write it out the long way as I think it's more readable, but I can see why a minifier would prefer *+*

CSS selector * + * definition?


Qual a quantidade apropriada de alterações para um commit?

Question: Tenho percebido que, em muitos projetos públicos no GitHub, os commits costumam conter alterações muito pequenas. Há vários casos de commits com alterações em uma única linha de código. Em outros, há alterações apenas em comentários, não em código.
Eu não costumo trabalhar assim. Uso o Git localmente e evito fazer commits de alterações mínimas, normalmente são alterações substanciais. Em alguns casos, meus commits contém alterações em mais de 10 arquivos. Tenho me perguntado se isso é o ideal.
Qual é a quantidade apropriada de alterações para um único commit?
Comment: Várias perguntas boas geram algum grau de opinião com base na experiência de especialistas, mas as respostas a esta pergunta tenderão a ser quase que completamente baseadas em opiniões e não em fatos, referências ou experiência específica.
Answer: Não é ideal medir um commit pela quantidade de arquivo ou por sua percepção do tamanho das alterações.
No mundo ideal, um commit deveria conter uma, e somente uma, nova funcionalidade ou então uma única correção. Isso possibilita a rastreabilidade de impacto de cada alteração e um possível rollback desse commit no caso dele quebrar alguma coisa.
Por outro lado, se você unir as funcionalidades X, Y e Z num mesmo commit e a funcionalidade Z não for aprovada para a release, não seria possível reverter a alteração pela própria ferramenta. Seria necessário criar uma nova versão do sistema a partir da versão final e remover Z. Ou então criar uma nova branch e aplicar as mesmas alterações feitas em X e Y.
Para esse esquema ter um efeito ainda melhor, é interessante usar um branch diferente para cada funcionalidade. Após a implementação, o commit é feito na branch e a versão final do sistema é o merge de todas as funcionalidades selecionadas.
Eu não sei até que ponto levar isso, pois de forma pragmática você até pode juntar funcionalidades que são interdependentes, mas algo que os usuários mais experientes de GIT sempre dizem é para não ter medo de criar branches.
Um princípio importante e prático, é usar a ferramenta como for melhor para você e sua equipe organizarem o código. Em outras palavras: use a ferramenta para ajudar o seu trabalho, não trabalhe em função da ferramenta.
Answer: A resposta simples é: Você escolhe.
A resposta completa seria: depende do sistema de versionamento que pretende usar.
O sistema mais usado é o SemVer que usa 3 parametros separados por pontos. Os parametros correspondem Major, Minor, Patch

MAJOR nova versão quando a nova API é incompatível com a anterior,
MINOR quando se adicionam novos métodos que respeitam, e são compatíveis, com métodos anteriores
PATCH todos os remendos, correções que são exclusivamente para corrigir erros ou bugs no código sem adicionar novas features/métodos.

Assim se estiver a usar SEMVER, ou seja Semantic Versioning todos os patchs por menores que sejam devem incrementar o parametro patch e ter uma nova tag no git.
Tem outro aspecto que está ligado à facilidade de perceber e analizar os commits. Um commit deve ter mudanças relacionadas apenas com um assunto. Commits que mexem em n ficheiros e mudam muitos comportamentos são confusos e indesejáveis.
Comment: Interessante. Onde marco essa versão? Na mensagem do *commit*? `git commit -m "1.2.3"`?
Comment: @Andrey eu não costumo ligar mensagens de commits com tags, mas teste `$ git push  tag ` ou somente `git push --follow-tags`
Answer:
TL / DR: Não existem regras. Porém projetos open source -> presença de  pull requests e patches -> tendência de commits menores, que possam ser facilmente revisados por outros desenvolvedores. Projetos comerciais -> Tendência de commits maiores implementando todos os aspectos de determinada feature (mesmo que o desenvolvedor localmente faça vários commits). Novamente, não existem regras, mas pude observar esse diferença de comportamento na prática entre os dois tipos de projetos.

Enquanto não existem regras definidas, projetos open source maduros com vários colaboradores costumam trabalhar com uma granularidade mais fina de commits. Isso ocorre devido a própria natureza do projeto. Em projetos open source diversos desenvolvedores externos fazem pull requests e/ou submetem pequenos patches para arrumar pequenos bugs ou adicionar pequenas funcionalidades ao projeto. A ideia aqui é que os commits não só sejam representativos, mais autocontidos e facilmente revisáveis por um desenvolvedor do projeto. Commits menores são mais rápidos de revisar e dão menos dor de cabeça para quem vai integrar o seu código ao repositório principal (possivelmente muito tempo depois que você submeteu o patch).
Mesmo o time "central" de um projeto, com permissão para fazer push no repositório principal, costuma trabalhar com uma granularidade mais fina de commits. Grandes unidades de trabalho são geralmente bem subdivididas entre os diversos módulos, e posteriormente subdividas em tarefas menores. O resultado é que existem mais tarefas, cada qual mais "pontual"; logo são feitos mais commits, cada um com menos código.
Já em projetos comerciais é igualmente comum que um desenvolvedor faça vários pequenos commits locais (digamos, em um branch de feature), mas antes do push para o repositório principal, é prática comum fazer um de squash desses commits, dando a impressão de um único grande commit que resolveu determinada tarefa / problema. O ponto principal aqui é que a granularidade das tarefas são maiores, e há um esforço para tornar o repositório mais "limpo".
Cada estratégia possuiu suas vantagens. Commits frequentes e pequenos representam melhor o fluxo real de desenvolvimento, porém, granularidade mais grossa e reescrita de histórico tornam a árvore de commit mais "limpa". Existem bons argumentos da escola "Faça commit rápido, faça commit sempre, nunca reescreva o histórico", bem como da escola "Mantenha seu repositório central limpo". A escolha é inteiramente sua.


Trocar valor de uma varivel de outro componente Angular

Question: Ola, eu tenho um component que se chama errorLog, dentro dele tem um metodo chamada LogOut, que e chamada quando eu clico em 1 botão de logOut, porem apos deslogar você e redirecionado a pagina de login, porem eu queria exibir um texto nessa tela de login que so e exibido apos ser deslogado, então, no meu templateHTML do meu component de login criei esse seguinte codigo:

          Você foi deslogado

então so ira aparecer essa div quando a variavel 'deslogado' for TRUE, então como eu faço para dizer no meu component que a variavel 'deslogar' do component login e true? para quando ser redirecionado o *ngIf dar true?
Comment: Editei seu código e pergunta e deixei mais intuitivo para que respostas mais elaboradas apareçam.
Answer: Para compartilhar variáveis entre componentes o Angular recomenda a utilização de serviços.
Serviço são singletons, ou seja, somente uma instância existe durante o ciclo de vida da aplicação e devem ser utilizados para manter o estado de informações entre componentes.
Um exemplo clássico na utilização de serviços é justamente manter a informação do usuário logado.
@Injectable()
export class AccountService {
  account?: Account

  login(): void {
    account = { id: 1111, name: 'Marcelo' }
  }

  isLoggedIn(): boolean {
    return !!account
  }

  loggout(): void {
    account = undefined
  }
}

No serviço acima utilizamos a membro de classe account para armazenar a informação do usuário logado.
O método login deve executar seu processo de login e armazenar o resultado na variável account.
O método isLoggedIn valida a informação da variável account e retorna true caso ela tenha sido preenchida, ou seja o usuário esteja logado.
O método loggout apenas configura a variável account como undefined ou seja removendo a informação do usuário logado.
Após definido o serviço, é preciso injeta-lo no seu component para exibir a informação, portanto conforme entendi faça o seguinte
@Component({
  selector: 'page-login'
  ...
})
export class PaginaLoginComponent {

  constructor(
    private accountService: AccountService
  ) { }

  isLoggedIn() {
    return this.accountService.isLoggedIn()
  }

}

e no template do component PaginaLoginComponent

  Você foi deslogado

Pronto, espero ter ajudado, lembre-se para compartilhar informações que dizer respeito ao estado global da aplicação utilizamos serviços do Angular.
[]s
Answer: Você pode também passar uma flag na url
import { ActivatedRoute } from '@angular/core';

@Component(...)
export class SeuComponent {
    public justLogout = false;

    constructor(
        private route: ActivatedRoute
    ) {
        this.route.queryParams.subscribe(
            (params: any) => {
                if (params['logout'] === 'true') {
                    this.justLogout = true;
                }
            }
        );
    }
}

No seu template

    Você foi deslogado

Daí é so redirecionar assim
http://sua-url/login?logout=true

Ou no template usando o routerLink
link

ou ainda por navegação imperativa
import { Router } from '@angular/core';

constructor(
        private route: ActivatedRoute
    ) {}

goToLogin() {
    this.route.navigate(['/login'], {queryParams: {'logout': 'true'}});

}

Referência:
https://www.youtube.com/watch?v=B7mc184O4x0


Unable to convert pathvariable to object

Question: I want to have an object as a path variable but I get the below exception when testing. How can I fix this
@Validated
@RestController
@RequestMapping("/test/api")
public class MyRestController {

    @GetMapping("/data/{id}")
    public Data getData(@PathVariable @Valid IdData id) {
        return new Data();
    }
}

@Data
public class IdData {

    private Integer id;

    public IdData(Integer id) {
        this.id = id;
    }

}

Exception:

org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException:
Failed to convert value of type 'java.lang.String' to required type
'com.test.IdData'; nested exception is
java.lang.IllegalStateException: Cannot convert value of type
'java.lang.String' to required type 'com.test.IdData': no matching
editors or conversion strategy found
Comment: The error tells you exactly what is wrong. In short how should Spring know how to convert a `String` to your `IdData` object? You need to write a converter for that.
Comment: Why are you using `@Valid` but then have no validation whatsoever in `IdData`?
Answer: From "/data/{id}" you will get an id which is an integer but the method parameter is trying to get IdData value which is incompatible.
@Validated
@RestController
@RequestMapping("/test/api")
public class MyRestController {

    @GetMapping("/data/{id}")
    public Data getData(@Valid @PathVariable int id) {
        return new Data();
    }
}

Output:-
{
   "repository": {
      "metricName": "spring.data.repository.invocations",
      "autotime": {
         "enabled": true,
         "percentilesHistogram": false,
         "percentiles": null
      }
   }
}

Answer: you could change your @PathVariable Data Type from IdData to an Integer. Just add some logic to get the IdData by the id in path, which can be done by using JPA's findById() method. It might also be easier to pass in an integer in the path rather than an entire object.


Determining the center of the p-Sylow subgroup of $S_p $

Question: My Algebra book says without proof that the center of the p-Sylow subgroup (we will call it P) of $S_p$ is the subgroup itself.
Now I can understand that P will be a subset of its center as it is of prime order, and hence cyclic. However, I can't understand why no other element outside of P can be part of its center. Any help understanding this would be great.
Comment: You are confusing center with centralizer. The center $Z(P)$ is a subset of $P$ by definition. The centralizer $C_{S_p}(P)$ however is in fact strictly bigger than $P$, because there are elements outside of $P$ that commute with every element of $P$.
Comment: Also BTW there is more than one $p$-Sylow subgroup of $S_p$.
Comment: Basically, all that is being said here is that a Sylow $p$-subgroup of $S_p$ is abelian. Note that $p$ is the highest power of $p$ dividing $p!$, so yes, any Sylow $p$-subgroup is cyclic. In general, however, this subgroup is not unique.
Answer: Like anon I assume that the question is about the centralizer of $P$ (with that typo/mistranslation the question makes IMHO more sense).
The highest power of $p$ that divides $p!$ is $p^1$. Therefore the Sylow subgroups $P$ are all cyclic of order $p$. A permutation of prime order $p$ must be a product of disjoint $p$-cycles (ignoring fixed points). In the case of $S_p$ there is room for only one disjoint $p$-cycle, so we know that $P$ is generated by a $p$-cycle, call it $\sigma$. Because $P=\langle\sigma\rangle$ the centralizer of $P$ equals the centralizer of $\sigma$, $C_{S_p}(\sigma)$.
Let's take a detour via conjugacy classes. We know from basic properties of symmetric groups that the conjugates of $\sigma$ are exactly all the $p$-cycles in $S_p$. How many are there? A $p$-cycle in $S_p$ will move all the numbers $1,2,3,\ldots,p$. Recall that in cycle notation we can choose the starting point of the cycle any way we want without changing the cycle, but no other changes are possible. So we can write all $p$-cycles $\alpha$ of $S_p$ uniquely in such a way that they begin with a $1$. We then have $p-1$ choices for the next number $=\alpha(1)$, $p-2$ choices for the next $=\alpha(\alpha(1))$ et cetera. Therefore there are exactly $(p-1)!$ different $p$-cycles in $S_p$. In other words, the conjugacy class $[\sigma]$ of $\sigma$ has size $(p-1)!$.
But the orbit-stabilizer theorem (often
introduced at about the same time as the class equation) tells us that
$$
(p-1)!=|[\sigma]|=\frac{|S_p|}{|C_{S_p}(\sigma)|}=\frac{p!}{|C_{S_p}(\sigma)|}.
$$
This implies that the centralizer $C_{S_p}(\sigma)$ has order $p$. Clearly $P\subseteq C_{S_p}(\sigma)$, so this means that we must have equality
$$
P=\langle\sigma\rangle=C_{S_p}(\sigma)=C_{S_p}(P).
$$
Comment: I did miss that center of $p$-group part. And I think the next part is correct, we only get a $C_p$ component for each power of $p$: The center of $G\wr C_p\cong G^p\rtimes C_p$ is the diagonal of $Z(G)^p$.
Comment: Observe that it is crucial here that we are working inside $S_p$. If the symmetric group is $S_n$, $n>p+1$, then the centralizer can be strictly larger (this fits, and is one of the reasons why I think the question really is about centralizers). For example in $S_9$ the 2-cycle $(89)$ clearly commutes with the $7$-cycle $\sigma=(1234567)$, so the centralizer will have an even order. The exact order of the centralizer of a Sylow $p$-subgroup can be calculated along the lines of my answer when $n<2p$ (the bound coming from the fact that after that point Sylow subgroup is no longer cyclic).
Comment: It looks like the exact order of the centralizer of a $p$-Sylow subgroup of $S_n$ is $(n\,\mathrm{mod}\,p)!$.
Comment: @QuangHoang: We get a factor of that form, but the centralizer is bigger. The center of $P$ is surely contained in the centralizer, and a $p$-group always has a non-trivial center. For example in $S_{2p}$, a Sylow $p$-subgroup is abelian, isomorphic to $C_p\times C_p$. Similarly up to $S_{p(p-1)}$. With $S_{p^2}$ it gets more complicated, I haven't checked, but I think the center of that Sylow $p$-subgroup has order $p$ only. A Sylow $p$ of $S_{p^2+p}$ is a direct product of those of $S_{p^2}$ and $S_p$ et cetera.


my website is not mobile friendly, only the slider is the one that is not responsive and l want to make the slider responsive,

Question: my website is responsive except the slider which is not working, l tried a couple of solutions but still it is not responsive and none of the solutions provided to the previous similar questions helped
l tried using the html tags viewport .... and a couple of css for different devices but the slider is still not responsive
enter code here

slider
{
  max-width: 100%;
  max-height: 100%;
  position: relative;
  margin: auto;
}

l expect the slider images to be responsive and fit in the whole page of mobile devices and tabletsenter code here
Comment: website  address->     https://tavermcon.co.za
Comment: It looks fine as is, do you want the images to be full height on mobile?
Comment: yes l want the images to be full height on mobile
Comment: Possible duplicate of [Bootstrap Carousel Full Screen](https://stackoverflow.com/questions/16350902/bootstrap-carousel-full-screen)
Comment: thanks l used the solution the duplication it worked but kinder stretched the image resolution but it does not look that bad
Answer: I cant see your slider on the site? Your best bet is to either use something like bootstrap or use a media query


foreign key doesn't work in activeadmin in rails project

Question: I got a weird problem in activeadmin in rails project.
I have created new rails project and two tables as followings.
rails g model category title:text

rails g model subcategory category:references title:text

subcategory belongs to category with the foreign key "category_id" by reference keyword.
I have changed the category and subcategory models as the following.
class Category < ActiveRecord::Base
    has_many :subcategories, dependent: :destroy
end

and
class Subcategory < ActiveRecord::Base
  belongs_to :category
  default_scope -> { order(created_at: :desc) }
end

I added the activeadmin gem in the Gemfile and installed.
ActiveAdmin.register Category do

    permit_params :title

end

ActiveAdmin.register Subcategory do

    permit_params :category_id, :title

end

I logged in successfully.
I added new category. If I click the subcategory in order to create new subcagegory, category item brings errors like the image.

I want to show the categories added by me.
Best Regards.
Answer: That's no error.
Those are category objects. It's now left for you to decide which attribute of the category object you want shown. Name?, Description?
You can have a form like so:
ActiveAdmin.register Subcategory do
  permit_params :name, :description, :category_id

  form do |f|
    f.semantic_errors *f.object.errors.keys

    f.inputs "Details" do
      f.input :name
      f.input :description
      f.input :category_id, :as => :select, :collection => Category.all.collect {|category| [category.name, category.id] }
    end
    f.actions
  end
end

Note the line: f.input :category_id, :as => :select, :collection => Category.all.collect {|category| [category.name, category.id] }
I'm saying to populate the subcategory field with all existing categories, display their names, and use their IDs.
Hope this helps.
Comment: Thanks for your quick message. where should i put the code?
Comment: Inside the block for `ActiveAdmin.register Category do`
Comment: Something like the above.
Comment: done. But I got errors "undefined method `new_record?' for nil:NilClass" It says there's error in 29th and 30th lines. 29th line is """f.inputs "Subcategories for category" do"""
Comment: I just finished updating the post.


Covariance of Random Vector with seemingly-dependent coordinates?

Question: Let $f_1, f_2, f_3, g_1, g_2, g_3$ be i.i.d. centered Gaussians of variance $\sigma^2$.
I am interested in the random variable
$$
\begin{pmatrix}
h_1\\
h_2\\
h_3
\end{pmatrix} = \begin{pmatrix}
f_1g_1+f_2g_2+f_3g_3\\
f_1g_2+f_2g_3+f_3g_1\\
f_1g_3+f_2g_1+f_3g_2
\end{pmatrix}.
$$
It is straighforward to see that this is mean zero.
I'm trying to compute its covariance matrix now, but getting results that I doubt.
The diagonal entries are simple to compute as $3\sigma^4$.
I am mostly interested in the off-diagonal entries.
Here,I compute
\begin{align}
\mathsf{Cov}(h_1,h_2) = \mathbb{E}[h_1h_2] = \mathbb{E}[f_1^2g_1g_2+f_2^2g_2g_3+f^3g_3g_1 + g_1^2f_1f_3+g_2^2f_1f_2+g_3^2f_2f_3] = 0
\end{align}
Here, I discarded all terms that do not contain $f_i^2$ or $g_i^2$, as they will clearly be zero.
But all of the above terms seem to be zero as well, e.g. the covariance matrix seems to be $3\sigma^4 I_3$.
Is this the case? It is counterintuitive to me, as one would expect via inspection of $h_i$ that $h_i$ and $h_j$ are correlated, but this appears to not be the case by my computation.
Comment: the $h$'s are not gaussian, so the covariance is not enough to determine independence.
Answer: Let $K = \begin{pmatrix}
0 & 1 & 0\\
0 & 0 & 1\\
1 & 0 & 0
\end{pmatrix}$ and $J = \sum_{i=1}^3f_iK^{i-1}$ then $h = J g$
\begin{align}
\texttt{Cov}\left[h\right] &= \mathbb E\left[hh^{\intercal}\right]\\
&= \mathbb E\left[Jgg^{\intercal}J^{\intercal}\right]\\
&= \mathbb E\left[J \texttt{Cov}[g]J^{\intercal}\right]\\
&= \sigma^2\mathbb E\left[JJ^{\intercal}\right]\\
&= \sigma^2\sum_{i=1}^{3}\sum_{j=1}^{3} K^{i-1}\left(K^{\intercal}\right)^{j-1}\mathbb E\left[f_if_j\right]\\
&= \sigma^4 \sum_{i=1}^{3} \mathbf I\\
&= 3\sigma^4\mathbf I
\end{align}
Comment: Could OP please explain why they consider this to answer their question? I was under the impression that the issue was with the interpretation of the diagonal covariance, not the computation itself (although this is an elgant method).


Prove there exists $\mathbf \xi$ such that $||\nabla F(\mathbf \xi)||\leq2$.

Question:
Suppose $B\subseteq\mathbb R^d,\;\Omega=\{\mathbf x\,\big|\,||\mathbf x||\leq1\}$, $\Omega\subseteq B$ and $|F(\mathbf x)|\leq1$. Prove there exists $\mathbf \xi$ such that $||\nabla F(\mathbf \xi)||\leq2$.

Suppse $\mathbf x,\,\mathbf y\in \Omega$, then by mean value theorem, we have
$$
F(\mathbf x)-F(\mathbf y)=F_1'(\mathbf\xi)(x_1-y_1)+\cdots+F_d'(\mathbf\xi)(x_d-y_d).
$$
I have though about Cauchy-Schwarz inequality, but I get an inequality of converse direction. So I need some help.
Comment: Not "of course"! It could have been defined on $B$ or could have mapped to $\mathbb R^m$.
Comment: $F$ maps from where to where? Note that the mean value thm can only be applied to functions defined on $\mathbb R$.
Comment: $F$ is a real-valued function defined on $B$ of course.
Answer: Suppose $||\nabla F(\xi)|| > 2$ for all $\xi \in \Omega$, and define the function $g : \Omega \to \mathbb{R}$ given by
$$g(\xi) = F(\xi) - 2||\xi||.$$
Now, since $F$ is continuous on $\Omega$, $g$ is also continuous on $\Omega$, and thus by compactness of $\Omega$, $g$ attains its maximum at some $\xi \in \Omega$. Suppose $||\xi|| < 1$. Note that near $\xi$ we have
$$F(\xi') = F(\xi) + \nabla F(\xi) \cdot (\xi' - \xi) + o(||\xi' - \xi||).$$
By assumption, $||\nabla F(\xi)|| = 2 + \varepsilon$ for some $\varepsilon > 0$, so letting $v$ be the unit vector in the direction of $\nabla F(\xi)$, this gives $F(\xi + xv) = F(\xi) + (2 + \varepsilon)x + o(|x|)$, hence for sufficiently small $x > 0$, $F(\xi + xv) > F(\xi) + 2x$. But since $||\xi|| < 1$, for sufficiently small $x$ we have $||\xi + xv|| < 1$, so there is some $x$ satisfying both of these conditions, which satisfies
\begin{align*}
g(\xi + xv)
&= F(\xi + xv) - 2||\xi + xv|| \\
&> (F(\xi) + 2x) - 2(||\xi|| + x) \\
&= g(\xi)
\end{align*}
contradicting maximality of $\xi$. Thus any maximizer $\xi$ has $||\xi|| = 1$. Since $g(0) = F(0)$, and $0$ is not a maximizer, this means that any maximizer $\xi$ has $g(\xi) = F(\xi) - 2||\xi|| = F(\xi) - 2 > F(0)$, hence $F(\xi) - F(0) > 2$. But since $|F| \leq 1$, we must have $|F(\xi) - F(0)| \leq 2$, a contradiction.
Update:
It's been bugging me that the bound is $2$ and not $1$, which is the bound you get from the MVT in the one-dimensional case. Here's a way to modify the proof to show that there must be some $\xi \in \Omega$ with $||\nabla F(\xi)|| \leq 1$.
Similar to before, suppose $||\nabla F|| > 1$ on $\Omega$. Repeat the analysis above to maximize the function $g_+(\xi) = F(\xi) - ||\xi||$. At the end you find some $\xi_+$ with $||\xi_+|| = 1$ and $F(\xi_+) - 1 > F(0)$. Repeating this last part with $-F$ instead of $F$ (maximizing $g_-(\xi) = -F(\xi) - ||\xi||$) gives some $\xi_-$ with $||\xi_-|| = 1$ and $-F(\xi_-) - 1 > -F(0)$. Adding the two inequalities we've found gives $F(\xi_+) - F(\xi_-) - 2 > 0$, which is again impossible since we must have $|F(\xi_+) - F(\xi_-)| \leq 2$. It follows that $||\nabla F(\xi)|| \leq 1$ somewhere (and this is the best possible).
Comment: Wow! Congrats! Really nice answer!
Comment: corrected, thanks


How to load a node title of different language?

Question: In my case the noads are stored in three different languages. How can add a condition, where I specify the language for the title that need to be loaded?
foreach($references as $reference){
    if($node = Node::load($reference->nid)){
      $url = Url::fromRoute('entity.node.canonical', array('node' => $node->id()))->toString();
      $link = ''.$this->t($node->getTitle()).'';
      $render .= '
'.$link.'
';
    }

Where $references is an array of nids.
Comment: In general, *never* use t() with user input (only as placeholders) as that could lead to security issues. Entities also have a toLink() method, wihch returns a Link object that has a toString(), so you can simplify your two lines to `$node->getTranslation()->toLink()->toString()`. There is also a `links` template, but it unfortunately doesn't work with Link objects, instead it expects a list of arrays with the keys title and url, which is an Url object that you can get with $node->toUrl().
Comment: And last, your $reference->nid object looks suspicously like a database query result. In case you are querying the node table, you should use an entity query instead.
Answer: You can load the translation separately with ContentEntityBase::getTranslation, e.g.:
if ($node->hasTranslation('es')) {
  $translation = $node->getTranslation('es');
  $translated_title = $translation->label();
}


WYSIWYG not appearing for custom content type

Question: I am working on a re-work of Drupalerp (D6), as I found so many problems with it...but have run into an odd issue. As drupalerp creates it's extra content types programatically, I am unsure if it is doing it correctly. For content types created in the GUI, the Drupal way, I can get the Wysiwyg to appear.
In the node_type table the drupal nodes that work have 'node' in the module column, and has_body = 1. The erp ones have their individual module names instead of 'node'. If I switch the module to node for those ones, I get wysiwyg, but of course lose the custom programmed handling of those types.
So my question is, does that have to be 'node' in the module column of node_type in order to get wysiwyg, or is there another element missing from the programming of those custom types?
Comment: What kind of wysiwyg module are you using? wysiwyg.module depends on the input type but others allow to configure it based on the textarea name/id.
Comment: Yes, was using the Wysiwyg.module...it obviously needs to be running through the node module. I have ditched Wysiwyg/tinyMCE, and gone to straight CKEDITOR which works!
Answer: I know that wysiwyg is related to input filters, are these available on the body (if there is one) of the custom nodes?
Comment: yeah, good call...but yes they are all set to use Full HTML. I put the Better Formats module in to make sure that was the case, too. I'm thinking I probably need to start picking apart an existing 3rd-party module that does let the wysiwyg work, to see what is different architecturally.
Answer: Using the CKeditor module, you can apply the editor to any textarea on the site. However, it doesn't apply this by default. You have to set up the settings to either appear on ALL textareas or selected ones only.
Underneath every textarea, it gives you an element ID which you can use to isolate specific ones and get the editor to appear.
Assuming you're using CKeditor of course. :o)
Comment: I have ditched Wysiwyg/tinyMCE, and gone to straight CKEDITOR which works!
Comment: Good stuff... I really like the Wysiwyg module, but tinyMCE is rubbish!


rachmaninov fast or furious

Question: Why is the very start of Rachmaninov piano concerto #3 so fast? If I explain this any more I risk being as misunderstood as I understand 10 seconds of Rachmaninov.
Answer: It's actually not! The beginning of the first movement is actually labeled Allegro ma non tanto, meaning "fast but not too fast." You may be thinking of the beginning of the third movement of the concerto, which is fast.
Either way, concertos typically follow a particular brand of sonata form developed over decades and decades, and the opening and final movements of concertos are typically fast; Rachmaninoff was simply working within these normative conventions. (If you want to be fancy, you can call this "dialogic form," where the form is "in dialogue" with prior practice by acknowledging/challenging/responding to it.)
Furthermore, in 1967 Edward T. Cone, an absolutely brilliant musical thinker (and one of my favorites), published an article called "Beyond Analysis." In it, he basically claimed that some musical questions can't be answered by analysis; they just are because at some point the composer has to make decisions that seem arbitrary. Although in Rachmaninoff's case there were stylistic conventions within the sonata/concerto form that likely compelled him to use a fast tempo, anything more specific than that, without concrete biographical information from Rachmaninoff himself, is likely "beyond analysis."

rachmaninov fast or furious


transforming input string into an integer

Question: for the below code, when I run it, and input a float as the capacity_engine input, I get an error msg: invalid literal for int base 10. Can someone explain why and the fix?
<code>fuel_type = input("Please enter your fuel type, P for Petrol and D for Diesel: ")
capacity_engine = int(input("What is the capacity of your engine?: "))
distance_travelled = int(input("Please enter distance travelled in your car in km: "))

if fuel_type == "P":
    if capacity_engine <= 2:
        print("Your emission value per tonne is 0.208")
    else:
        print("Your emission value per tonne is 0.176")
elif fuel_type == "D":
    if capacity_engine <= 2:
        print("Your emission value per tonne is 0.296")
    else:
        print("Your emission value per tonne is 0.236")
</code>
Answer: You've answered your question yourself. You're inputting a float, but trying to convert it to int on line 2.
The fix should be changing int(...) to float(...) on line 2.


How to create a User Feed using the modules Message and Flag?

Question: What I'm trying to do is in theory easy : **User** flagged **Article**. But I'm having hard time figuring out how to build a user feed like this with Message and Flag modules.
I looked a little bit at the Message UI to create a message type, but can't seem to find a "Flagging user" token. The only related flag token I've found is Users who flagged the entity with flag flag which prints all users that liked an article like this:
User A, User B, User C flagged Article
What I really need is to print a message for every flag, like this:

User A flagged Article
User B flagged Article

And finally show everything in a view to the Article author.
Any suggestions?
Answer: If you'd add the Rules module (on top of the Message and Flag module you're already using), you can get this to work by using the "Replacement tokens" as part of your "Message type" configuration.
If you're not familiar with these Replacement tokens, you can learn about it the answer to What's the purpose of "Replacement tokens" of a Message type? This answer also includes a sample rule which is similar to what you'll need: it makes the value of token flagging-user available to the Message type.
Some more details to resolve this specific question here:

Add a Replacement token in your Message type, and call it (say) @user_who_flagged (or %user_who_flagged if you prefer).
Use that @user_who_flagged (or %user_who_flagged) token anywhere you want in the message you're trying to produce.
Have Rules create your message (of the message type you're using), which you can do like so:

Rules Event "Article gets flagged".
Rules Action "Create an entity" (corresponding to your Message type, and use a variable like (say) entity_created for that).

Add an appropriate Rules Action to pass the value of the "Replacement token" (which is used in the Message type as detailed above):

which looks like entity-created:arguments:user-who-flagged, and
in which you pass the value flagging-user (that's the clue to make it work ...).

Should you want to include additional info in your message about the actual Article (like nid, content type, title, author, whatever), then just create an additional Replacement token for each of them, and a similar Rules Action for each of them also.

With the above approach you'll have your messages created with the custom content you want. Those messages are Drupal entities, so creating an appropriate view from it is straight forward.
For anybody not familiar with the (great) Message module yet (which is poorly dcumented ...), here is your chance to get a first impression about it ... Below is an export of "a" message type that you could use to get started (by simply importing it in your own site). It actually works together with the example rule in the related question. This message type has machine name user_following, and uses a replacement token like @following_user (adapt both to fit your needs, eg change @following_user to @user_who_flagged to use what I suggested above):
{
  "name" : "user_following",
  "description" : "User following",
  "argument_keys" : [ "@following_user" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@following_user started following [message:user:name]",
        "format" : "plain_text",
        "safe_value" : "\u003Cp\u003E@following_user started following [message:user:name]\u003C\/p\u003E\n"
      }
    ]
  },
  "rdf_mapping" : []
}

Notes:

(to avoid confusion) [message:user:name] in the message type sample above is the user to which the message is targeted, not the flagging user!
(if you still don't get the clue of all this) using Rules it's possible to make data originating from any module (such as the Flag module) available as tokens to the Message module.
Comment: This was the solution and the right approach.. and yes Message is poorly documented for a great module.
Comment: I still don't have the required 50pts to comment. After reading the question and the answers seems that those who downvoted the solution don't know much about Message. When i get the 50 pts i'll try to not forget to post a comment there.

Merci beaucoup encore.
Answer: If I understand your question correctly, this is how you need to set things up:

Create message and flag types you want to use.
Create a new rule that will be triggered when "A node/user/whatever has been flagged, under '[your flag]'".
Add action: Create new entity, select message and fill in the details.
To target the "flagging user" just use [site:current-user] token. This is invoked when the flagging action is taking place, meaning that the current user is the one you need.

Hope this helps.
Comment: I've edited my question, hope you can help me find a solution.
Comment: @Aram : I don't think the solution in your answer will work ... Have a look at my answer to understand why I think so. The key issue is that you need a mechanism to pass that "flagging user"-token from "Flag" to "Message", which is what you do using those Replacement Tokens within a "Message Type". Get it?


unable to select from drop-down with firefox (works in Chrome)

Question: What I want to do is be able to select from the drop-down menu without the accordion changing. This works in Chrome. However, when I was trying it in Firefox, it no longer worked.
Here is my jsfiddle.
Why does this not work in Firefox?
I believe that it is this code that is causing the problem (dropdowns without the selectOne class work fine):
<code>$(function () {
  $('.selectOne').click(function(){
    return false;
  });
});
</code>
Comment: It works, just have to scroll way over to see the other sections.
Comment: Just me or I can't get your fiddle's slider/accordion to work on Chrome nor Firefox..?
Comment: slider? You shouldn't see a slider. That was just placeholder text.
Comment: Horizontal accordion should work on both though.
Comment: Ohh I knew I was missing something. Just spend 5 minutes desperately clicking the left-most one and nothing happened, now I see that it was just the already open one.
Comment: I've tried the fiddle on FF Nightly and it worked fine, when removing the `.selectOne` click handler it bugs the second `select`. I'll downgrade to FF stable to check again.
Comment: The `select`s don't work even if you remove the return false from the handler, interesting. It looks like a bug in the plugin honestly. Even though it is not reproduce-able on my non-stable release which makes it even more weird.
Comment: The dropdowns don't seem to like the CSS transform/rotate that is being applied. Ex: [link](http://jsfiddle.net/pratie/G9vGN/)  I pulled in all CSS from the external file, the accordion content is overlapping but you can see that the dropdowns work. Try to re-structure your code and apply the transform to the `H2` text only, move `select`s out of the H2.
Answer: Try to upload the linked libraries.  Have you linked the plugin.  Accordian is a jQuery Plugin, not just jQuery.


valor de input com 'find' não funciona

Question: Tenho uma lista que incrementada dinamicamente com o append do jquery, a lista é mais ou menos assim:
    $("#questoes").append(
        '
'+
            '
'+
                '
'+
                '<input type="number" class="form-input questao_numero" style="max-width: 160px" placeholder="Nº da questão" data-chave="numero_questao">' +
                '
'+
                '
'+
                '' +
                '
'+
            '
'+
            '
' +
            '
' +
            '
Enunciado da questão:
' +
                '<textarea name="enunciado" class="form-control questao_enunciado" data-chave="questao_enunciado">Enunciado da questão</textarea>' +
                '

' +
                '
Alternativas da questão:
' +
                '

'+
                '<button type="button" class="btn btn-secondary btn-sm nova_alternativa">+ Add nova alternativa</button>' +
                '

' +
            '
' +
        '
'
);

Estou usando o seguinte código para percorrer os elementos da lista e pegar o valor dos inputs contidos em cada item da lista e colocar em um array:
    $("#salvar_alteracoes").click(function(){

    var questoes = new Array();
    $("#questoes").each(function(i, e){
        $(this).find('li').each(function (j) {
            var questao = {
                "questao_numero" : $(this).find('.questao_numero').val(),
                "questao_enunciado" : $(this).find('.questao_enunciado').val(),
            };

            questoes.push(questao);
        });
    });
});

Mas usando "$(this).find('.questao_numero').val()" não está pegando o valor do input porque?
Comment: porque está `` para que funcione ``
Comment: @WéllingthonM.deSouza No código original está com id, é que ao passar aqui eu acabei colocando errado. E não funciona mesmo assim
Answer: Seu código possui um problema: não existem as class .questao_numero e .questao_enunciado. Ou você coloca as referidas class nos respectivos elementos ou pegue os valores pelo nome da tag, já que só existem essas duas, input e textarea (coloquei um value="123" no input apenas para exemplificar):

questao = 1;
$("#questoes").append(
  '
'+
      '
'+
          '
'+
          '<input value="123" type="number" class="form-input numero_questao" style="max-width: 160px" placeholder="Nº da questão" data-chave="numero_questao">' +
          '
'+
          '
'+
          '' +
          '
'+
      '
'+
      '
' +
      '
' +
      '
Enunciado da questão:
' +
          '<textarea name="enunciado" class="form-control enunciado_questao" data-chave="enunciado_questao">Enunciado da questão</textarea>' +
          '

' +
          '
Alternativas da questão:
' +
          '

'+
          '<button type="button" class="btn btn-secondary btn-sm nova_alternativa">+ Add nova alternativa</button>' +
          '

' +
      '
' +
  '
'
);

var questoes = new Array();
$("#questoes").each(function(i, e){
    $(this).find('li').each(function (j) {
        var questao = {
            "questao_numero" : $(this).find('input').val(),
            "questao_enunciado" : $(this).find('textarea').val(),
        };
        questoes.push(questao);
        console.log(questoes); // para mostrar os valores
    });
});

Comment: é que eu copiei um trecho antigo, me desculpe.
Comment: e sobre isso: id="'+questao+'" , é porque a lista é incrementada com o append do jquery e esse trecho estava dentro do append
Comment: @LeandroSilvaCampos Entendi, e já atualizei a resposta de acordo com a pergunta.
Comment: funcionou, mas eu precisava que ele selecionasse através da classe ou outro seletor especifico, pois dentro de cada item da lista das questões terão também inputs referentes as alternativas e fazendo assim ele vai pegar o valor das alternativas também e adicionar no indice "numero_questao". Não tem como fazer por um seletor em especifico?
Comment: @LeandroSilvaCampos Dentro de cada  terá mais de 1 input?
Comment: @LeandroSilvaCampos Vc vai colocar 1 classe diferente pra cada input?
Comment: já descobri o erro, o nome das classes realmente estavam errados. eu estava usando o find('questao_numero') e a classe está com nome 'numero_questao' kkkk perdi bom tempo com isso e não vi essa burrice minha. Mas vou marcar sua reposta como correta porque no fim das era esse o problema
Answer: O problema é que você esta tentando acessar um elemento por um seletor que não foi  definido, veja:

Você esta tentando acessar como .numero_questao sendo que você não atribuiu esse valor ao campo, pelo contrário você apenas colocou como .num_quest
<input type="number" name="numero_questao" class="form-input num_quest" style="max-width: 160px" placeholder="Nº da questão" data-chave="numero_questao" value="225">

Você esta tentando acessar como .questao_enunciado sendo que você não atribuiu esse valor ao campo, pelo contrário você apenas colocou como .enunciado
<textarea name="enunciado" class="form-control enunciado" data-chave="enunciado">Enunciado da questão</textarea>

Agora se o que você quer é acessar o elemento pelo atributo data-chave você deve fazer a seguintes alterações:
var questao = {
    "questao_numero" : $(this).find('[data-chave="numero_questao"]').val(),
    "questao_enunciado" : $(this).find('[data-chave="enunciado"]').val(),
};

Veja funcionando:

var questoes = new Array();
$("#questoes").each(function(i, e){
    $(this).find('li').each(function (j) {
        var questao = {
            "questao_numero" : $(this).find('[data-chave="numero_questao"]').val(),
            "questao_enunciado" : $(this).find('[data-chave="enunciado"]').val(),
        };

        questoes.push(questao);
    });
});

console.log(questoes);

                <input type="number" name="numero_questao" class="form-input num_quest" style="max-width: 160px" placeholder="Nº da questão" data-chave="numero_questao" value="225">

Enunciado da questão:

                <textarea name="enunciado" class="form-control enunciado" data-chave="enunciado">Enunciado da questão</textarea>

Comment: Primeiramente obrigado e me desculpem a burrice mas na verdade o código está correto, eu copiei um trecho antigo do código e por isso está diferente. Eu editei o post lá em cima, está tudo conforme deve ser e mesmo assim não pega o valor
Comment: quando você esta executando o código para pegar os valores ? Quando clica em algum botão ? Seria melhor colocar mais detalhes de como funciona seu código.
Comment: editei o post de novo.

valor de input com 'find' não funciona


How to use varargs as parameters of newInstance() to call a constructor and create an instance?

Question: I'm an autodidact and I'm trying to do this homework, but I didn't find any solution yet.
I don't know how to use varargs.I can't pass them to the newInstance() method to invoke the constructor that I need.
But the main problem is that I would like to write them from the command line using "args" but I don't know how to do.
Please any advice? Thanks a lot!
import java.lang.reflect.*;
import java.io.*;

public class VarargsTest{
    public static void main(String[] args)throws IOException{
        Class theClass = null;
        BufferedReader br = null;
        br = new BufferedReader(new InputStreamReader(System.in));
        try{
            theClass = Class.forName(args[0]); // what class I want to use ?
        }
        catch(ClassNotFoundException e){
            e.printStackTrace();
            System.exit(1);
        }
        System.out.println(theClass);
        Object obj = null;
        System.out.print("number of constructor's parameters :");
        String buf = null;
        try{
            buf = br.readLine(); //Waiting the number of parameters for the constructor
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
        Constructor[] constructors = theClass.getConstructors(); // constructor of that class
        for(Constructor constructor : constructors) {
            if(constructor.getParameterCount() == Integer.parseInt(buf)) {//checking that the number of parameters are matching
                if(constructor.getParameterTypes()[0] == VarargsC.class){// IL PRIMO PARAMETRO DEL COSTRUTTORE DEVE ESSERE DEL TIPO DELLA CLASSE

                    try{

                        obj = constructor.newInstance(new Object[]{"first", "second"," more"}); // trying some elements, but I would like use args[1]
                    }
                    catch(InstantiationException | IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                        System.exit(1);
                    }
                }
            }
        }
        System.out.println();
        System.out.println("There isn't a constructor with " + buf + " parameters");
        System.out.println();
        if(obj != null) {
            System.out.println("I have instantiate an object!");
            System.out.println(obj);
        }else{
            System.out.println("I'm not able to instantiate an object'");
        }
    }
}

class VarargsC{
    String str1;
    String str2;
    String str3;
        public VarargsC(String str1, String str2, String str3){
            this.str1 = str1;
            this.str2 = str2;
            this.str3 = str3;
        }
        public String toString(){
            return "VarargsC{" +
                    "str1=" + str1 +"\n" +
                    "str2=" + str2 +"\n" +
                    "str3=" + str3 + "\n" + '\'' +
                    '}';
        }
}

/*class VarargsC{

    String[] data;
        public VarargsC(String... str){
            data = new String[5];
            for(int i= 0; i< str.length; i++)
                                for(String a: str)
                this.data[i] = a;
        }

        public void toString(String... str){
            for(String a: str)
                System.out.println(a + "\n");
        }
}*/

Comment: Is the problem that you want to pass an array as a single argument but each element is passed individually, or vice versa? Or is the problem something else?
Comment: If your constructor's parameter is varargs (which is just syntactic sugar for an array) then using either `newInstance(new Object[]{array})` or `newInstance((Object) array)` should work for you. If you're having an issue, please [edit] your question to provide a [mre] and the exact error(s) you're getting.
Comment: If you could create a [mre] (← read the linked help page) demonstrating the problem I may be able to help more. Your current code seems to contain unnecessary code with regards to your specific question (i.e. it's not _minimal_) which makes it more difficult to understand what should be happening or what exactly is the problem. If you could also provide some sample inputs and expected outputs that would be helpful.
Comment: @Slaw Yes, for example I would like pass a string of 3 word's like this : "first, second, third" on "args[1]" and then passed each word individually as a parameter on newInstance()
Comment: @Slaw Thanks for your reply, but I didn't solve the problem yet.Your solution was helpful, but it doesn't solve my problem. I don't really understand what's wrong with my code. I made some changes but the situation has not improved much, I show you!
Comment: @Slaw ok I will do, thank. It's almost one week that I'm here this is the way that I'm so lazy. But I will do it until tomorrow morning. Thanks a lot
Answer: The varargs feature of the Java programming language allows to call a method, which supports a variable number of arguments, like an ordinary method with n arguments in source code. It is unrelated to your intent to allow an arbitrary number of arguments on the command line.
In fact, this source code feature is not even needed for your operation. You receive the command line arguments in an array whose length reflects their number. You can check the array length using args.length.
public class Test {
    public static void main(String[] args) {
      if(args.length == 0) {
          System.err.println("specify <className> args...");
          System.exit(1);
      }

      String className = args[0];
      // remove the first element
      args = Arrays.copyOfRange(args, 1, args.length);

      Class<?> theClass;// don't initialize with null
      try {
          theClass = Class.forName(className);
      }
      catch(ClassNotFoundException e) {
          e.printStackTrace();
          System.exit(1);
          throw new AssertionError(); // unreachable point
      }

      // constructor accepting n strings
      Class<?>[] argTypes = new Class[args.length];
      Arrays.fill(argTypes, String.class);

      try {
          Constructor<?> c = theClass.getConstructor(argTypes);
          Object o = c.newInstance((Object[])args);
          System.out.println("created " + o);
      } catch(ReflectiveOperationException e) {
          e.printStackTrace();
          System.exit(1);
      }
    }
}

The call to newInstance doesn't use the varargs feature, as on the source code level, we have an already existing array. In fact, the (Object[]) cast exists to make it explicit that we don't want to use the varargs feature, i.e. we don't want to call a constructor take a single array argument, but a constructor taking as many string arguments as the array contains.
Note that your example code's newInstance(new Object[]{"first", "second"," more"}) wasn't using varargs either, as it constructs an array explicitly, calling newInstance(Object[]) the same way as the solution of this answer. A varargs call would be newInstance("first", "second"," more"), which only works if we know at compile-time that the constructor expects three string arguments.


Installing cURL 7.19 on ubuntu

Question: I am transferring from a server with Ubuntu on to one with CentOS and I am encountering a problem regarding cURL.
Our current site runs cURL 7.19 but Centos yum only finds 7.15.  I get an error with
CURLPROTO_HTTPS saying it's undefined as the version I have is too low.
I tried a manual install and it installed but when I tried to remove the yum-installed cURL it decided to remove any package that had dependencies on it, which is every package incuding PHP and mysql.
I found this tutorial on how to manually install 7.19 as there isn't (or I can't find) an RPM of cURL higher than 7.15.
Does anyone know how to get around this without re installing 20+ modules we use or to make the manual install the primary one?
If worst comes to worst the cURL code still works, I just have to comment out
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);

I'm just not sure if that's an "ok" solution security wise, I have an SSL setup so I would hope it would be secure, but I'm not sure.
Answer: The official cURL site has pre-compiled RPMs for 7.21:
http://curl.haxx.se/download.html
CentOS is RedHat, so find the RHEL corresponding to what you're running (I suppose you'll have either CentOS 5 or 6).  Get the RPM appropriate for your architecture.
Once you have the file, you should be able to do something like "rpm -Fhv curl-7.21.7-3.0.cf.rhel6.i686.rpm" and update your default 7.15 to 7.21.
Answer: I would probably go with one of three possibilities:

Get curl 7.21 RPMs from curl.haxx.se
Get curl 7.19 RPMs for CentOS 6 and recompile
Get curl 7.15 RPMs for CentOS 5 and replace 7.15 source with 7.19 source

If 7.19 was absolutely required, I'd recompile the CentOS curl 7.19 RPMs (#2) otherwise I'd get RPMs directly from the original developers (#3).
Rebuilding a source RPM is quite easy; use a command like this:
rpmbuild --rebuild source.rpm

That should do it.

Installing cURL 7.19 on ubuntu


PowerBI show month as number

Question: In Power BI I need a solution for how I can see/show the "Month" from a Date hierarchy as a number in any filter or visualization.
That's my simple date hierarchy with Year/Month/Day. I only use the month as I work with periods in my report.

Now, if I use "Month" from the hierarchy it is shown by filters and visualizations as the name of the month.:

I would like to see the months as a number. Also, it is important to use the "Month" from the hierarchy as many DAX use it for calculations (YTD, next, previous month total DAXs).
Could you please help?
Thanks,
András
Comment: One of the thumb rules of Power BI is to use flattened Date Table where you can assign the month numbers in a separate column and utilize information from there.
Comment: You don't need date hierarchy at all - DAX does not use it. You only need a proper date table with continuous dates.
Answer: A simple 'switch' calc should do the job, something like this should work for you. This is helpful as some orgs work with fiscal years instead of calendar years, and the 1 doesn't always start on January.
<code>> `MonthNo = SWITCH('Year - Month'[Month],
>         "Jan", 1,
>         "Feb",2,
>         "Mar",3,
>         "Apr",4,
>         "May",5,
>         "Jun",6,
>         "Jul",7,
>         "Aug",8,
>         "Sep",9,
>         "Oct",10,
>         "Nov",11,
>         "Dec",12
>                 )`
</code>
Comment: Thanks, you mean I should add that as an additional column? How, where to add the above? Otherwise, yes this is exactly the situation. We work with fiscal years starts at July 1, there is a half-year phasing. Due to that name of the month is misleading, but the number of the month (considering as periods in a fiscal year) would be fine in my reports.
Comment: Yep, go into the data view (left hand side of Power BI desktop), and then on the ribbon bar there's a 'New Column' button that you should be able to click and drop in that statement.

PowerBI show month as number


IOS removes allocated memory in native library

Question: Strange behavior in IOS while integrating with a c/c++ library.
In AppDelegate i call
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0), ^{
    [[ABCService sharedInstance] abcInitialize];
});

abcInitialize is defined in c++ library
struct abc *top;
top = calloc(TYPE_SERV,size_of(struct abc));
top->us = server_alloc (...certain_params...);

inside server alloc i do alloc of structures struct1 and struct2
And then in Initialize function i try to access
top->us = calloc(TYPE_US, size_of(struct us));
if(top->us->struct1) //do something

I noticed that my struct1 is always null
When i debugged, i can see that the structure was allocated fine and values are set appropriately, but before returning from the function, the memory is automatically deallocated.
This is totally confusing and annoying.
Could any one help me understand what is going on?
I tried by turning off ARC too, still no change
Comment: You need to show how struct1 is allocated and how it is declared.
Comment: stuct1 is being allocated as calloc (1, stuct1_size);
Comment: I guess you need to show how abcInitialize: is looks like. Because in your current code you don't allocate memory for `top` pointer but assign something to `us` member (top->us = ...).
Comment: You never allocated `top`.
Comment: (You need to show some actual code.)
Comment: Edited the code. The native code is completely working on linux and android. So nothing to be changed in the native code. I woud like to know the memory configuration for IOS in such situations
Comment: Is abcInitialize code objc? Also c code is unmanaged. Most probably the allocations are valid only in the scope of the dispatch block. Could it be a weak refernence causing that?
Comment: @blganesh101 please provide more code
Answer:
top->us = calloc(TYPE_US, size_of(struct us));
if(top->us->struct1) //do something

I noticed that my struct1 is always null

If that's your real code, then yes, struct1 will always be null. calloc allocates memory and initializes it to zero. Hence, all of the members of top->us will be zero, and since struct1 is a member of top->us, it's going to be zero, i.e. NULL.
Comment: struct1 is allocated. This is not the real code. The real code works on all platforms and no changes done for IOS
Answer: First of all, ARC has nothing to do with memory management of C or C++ codes, so, you can rule out ARC for causing this.
According to http://www.cplusplus.com/reference/cstdlib/calloc/, calloc always initialize all the bits of the allocated memory to 0, naturally, top->us->struct1 will be NULL.

but before returning from the function, the memory is automatically
  deallocated

How do you come to the conclusion that the memory is automatically deallocated? As mentioned above, ARC will not automatically release your C++ structure/object.
As a conclusion. The result you saw was indeed as expected.
Comment: When i debugged, the memory is allocated fine and i could see the structure values intact., Upon function return the same structure is de-allocated. I am wondering why is this strange behavior.
Answer: I found the issue and it was due to linking the same file twice from different library. I have corrected my libraries and that had fixed my issue. So no source code was updated. Just the libs were corrected with the right sources.
Thanks a lot of for your support.


How much time is needed to "get back to shape" after a long period of time without singing?

Question: For example, if one goes without cycling for 5 years or even decades, he can get back to speed pretty much within an hour, maybe two.
For drum and piano, it may be longer, maybe a month or two.
What about singing?
How much time on average (coarse estimate) will an established singer take to "pick up the skills again" after a long time without practicing?
Comment: What? A competitive cyclist will not be back anywhere near their previous levels of performance if they don't cycle for several years without significant practice.
Answer: It's very much an individual thing - two people with the same amount of experience and the same length of hiatus will take different amounts of time to get back into the swing of things.
With the voice in particular it depends what they've been up to in the mean time. If they've been singing a little at home, doing occasional vocal exercises, and keeping fairly fit, they'll probably be able to reach their previous level fairly quickly. If, on the other hand, they haven't been looking after their voice at all, been smoking & drinking heavily for example, it may take their voice longer to reach peak condition.
As with anything, there are always exceptions to these rules of thumb - but by and large I think  most vocalists would be back on form after a couple of weeks of practising.


What does a linear map induce on cohomology rings of associated projective spaces?

Question: Suppose $f:\mathbb{R}^n\setminus\{0\}\to \mathbb{R}^m\setminus\{0\}$  is a linear map inducing a map $g:\mathbb{R}P^{n-1}\to \mathbb{R}P^{m-1}$ and hence a homomorphism
$$
g^*:\mathbb{Z}/2\mathbb{Z}[x]/(x^m)\to \mathbb{Z}/2\mathbb{Z}[y]/(y^n)
$$
on cohomology rings with $\mathbb{Z}/2\mathbb{Z}$-coefficients. Since this is a graded ring map, we have $x\mapsto \lambda y$.
Why does linearity imply that $\lambda=1$? Is there an argument without going into the calculation of the cohomology of the projective space?
Comment: Notice that taking lambda equal to 1 does not necessarily give a ring morphism.
Comment: I don't really see why...
Comment: @MarianoSuárez-Álvarez Could you please say a little bit more on your comment? Do you mean if $m<n$?
Answer: First of all notice that $g: \mathbb{R}P^n \to \mathbb{R}P^m$ is well defined provided that $f$ is injective. Consequently $m=n+k$ for some $k \geq 0$.
Since the cohomology ring $H^*(\mathbb{R}P^n)=\mathbb{Z}/2\mathbb{Z}[x]/(x^{n+1})$ is generated by the Poincaré dual of (the homology class of) an hyperplane, we have that
$$g^*(x)= g^*PD[\text{hyperplane}]=PD[g^{-1}(\text{generic hyperplane})]=y,$$
where the last identity is because the image of $g$ intersects the generic hyperplane in a $n-1$ dimensional subspace.
Another possibility is to prove that $g$ is isotopic to the inclusion $\mathbb{R}P^n \subset \mathbb{R}P^m$.
Comment: ...and... ${}{}$
Comment: I edited, hope it is more clear now
Comment: Sorry I changed notation here $n=n-1$ and $m=m-1$
Comment: Thank you for the answer. Do you know what the concern ''does not necessarily give a ring morphism'' from the comment above is referring to? I am worried that I understand something incorrectly.
Comment: Well, I don't know. I think he didn't notice that $m\geq n$.


Aplicação de contraste na página por meio de cookies

Question: Tenho um botão em uma barra de acessibilidade, que quando clicado chama a seguinte função:

function contraste2 ()
 {
  var css = document.querySelector('#css');
  var contraste = Cookies.get("contraste");
  if (contraste == "contrasteinativo" || contraste =="undefined")
  {
   Cookies.set("contraste","contrasteativo", { expires: 365 });
   css.setAttribute('href', 'estiloscontraste.css');
  }

  if (contraste == "contrasteativo")
  {
   css.setAttribute('href', 'estilos.css');
   Cookies.set("contraste","contrasteinativo", { expires: 365 });
  }

 }

A aplicação do css de contraste se dá por meio de um css alternativo, chamado na função.
Só que esse código tá errado, eu sei.
Se o contraste ainda não foi aplicado (cookie = undefined), então ele ativa o contraste e define o cookie como ativo.
Só que logo em seguida, ele verifica se o cookie está ativo, e se tiver ele desativa o contraste. Dessa forma, acaba que não há alteração nenhuma na página (pois o cookie sempre estará com valor de inativo).
Não estou conseguindo criar uma lógica pra isso, pensei em fazer uma espécie de contadora pra verificar se o botão já foi clicado, uma contadora por meio de um outro cookie.
Comment: De onde vem essa api "Cookies.set" "Cookies.get"
Comment: Estou incluindo dessa forma  Segui as orientações daqui: https://github.com/js-cookie/js-cookie
Answer: Troque o segundo if para apenas ser executado quando a primeira condição não é atingida.
No seu código o segundo if era sempre avaliado nesta versão apenas é avaliado se a primeira condição for atingida.
O undefined não é uma string portanto não deve estar entre aspas.
 function contraste2 ()
    {
        var css = document.querySelector('#css');
        var contraste = Cookies.get("contraste");
        if (contraste == "contrasteinativo" || contraste == undefined)
        {
            Cookies.set("contraste","contrasteativo", { expires: 365 });
            css.setAttribute('href', 'estiloscontraste.css');
        } else if (contraste == "contrasteativo")
        {
            css.setAttribute('href', 'estilos.css');
            Cookies.set("contraste","contrasteinativo", { expires: 365 });
        }

    }

Comment: Muito obrigada, funcionou!
Answer: Já que não tenho ciência de onde vem o objeto Cookies, irei criar um exemplo usando a API nativa sessionStorage:

const button = document.querySelector('#change-contrast');
const link = document.querySelector('#css');

function getContrastState (toggleValue) {
  const state = sessionStorage.getItem('contrast-state');

  if (! state) sessionStorage.setItem('contrast-state', '0');
  if (toggleValue) sessionStorage.setItem('contrast-state', state === '1' ? '0' : '1');

  return sessionStorage.getItem('contrast-state') === '1';
}

function toggleContrast (toggleValue = true) {
  const contrastState = getContrastState(toggleValue);

  if (contrastState) return link.setAttribute('href', 'contraste-ativo');
  link.setAttribute('href', 'contraste-inativo');
}

// Inicializa:
toggleContrast(false);

// Reinicializa ao clicar no botão:
button.addEventListener('click', toggleContrast);
<button id="change-contrast">Alterar Contraste</button>
...

Você terá que testar o código em outra página, já que o StackOverflow não permite que os trechos de código acessem o conteúdo de localStorage ou sessionStorage.
Criei um CodePen para demonstrar.

Referência:

sessionStorage.


Parse Data From WebView into my fragment android

Question: I want to parse json data using web view into my fragment to identify my web page login status.
My Containing Data:
{"loginID":0}
Here 0 means I am currently not logged in my web page using web view,
1 means I am logged in.
Answer: Are you using some web services? You can use JavaScript interfaces for WebView to jump from JS code into Android code and then send response to the specified Fragment.
Take a look here: addJavascriptInteface.
Send some source code or describe more what has to be done.


swift nsoutlineview open always one root element

Question: I work with swift 3 and Xcode 8 for macOS.
I use an nsoutlineview (without TreeController and in ViewBased Mode)
i would like to realize, that always one root element with their child element(s) can be open. if i open another one, the actual open root element should close and the new one will open.
for that i have  try it with the following code:
@IBAction func outlineViewClickedRow(_ sender: NSOutlineView) {

for x in (0..<outlineView.numberOfRows) {
outlineViewn.collapseItem(outlineView.item(atRow: x), collapseChildren: true)
}
outlineView.expandItem(outlineView.item(atRow: outlineView.selectedRow))

}

this IBAction is assign to my outlineView.
basically it works good.
but the problem is:

if I click on a root element, which is actual open, my function will open it again. this looks not professional...
and this "Click" Function will work also for elements, which are not expandable - this is not so good, too

i tried this code to solve the first point:
if (outlineView.isItemExpanded(outlineView.selectedRow) == true) {
  print("isExpanded")
}

but the print result will never shown.
itItemExpanded is always false ...
same problem for second point:
if (outlineView.isExpandable(outlineView.selectedRow) == true) {
  print("isExpandable")
}

is Expandable always "false"
Comment: nobody an idea?
Answer: Since your loop collapses all items, once it is done, the selectedRow item will always be collapsed at the end of the loop.  This will inevitably close and reopen the selected item if it happens to already be expanded.  (BTW you can collapse all nodes by passing a nil item to that function instead of using a loop)
If you check outlineView.isItemExpanded(outlineView.selectedRow) at the start of the function an just exit if it is already expanded, that should solve your first issue.
For the second point, you have to set the "isExpandable" property of the items somewhere (which you either did not do or did not show us).
I don't know which event your outlineViewClickedRow function is linked to but you have to make sure that outlineView.selectedItem contains what you expect.  Depending on which event it is, the row selection states may not get updated before outlineViewClickedRow is called (which could cause some inconsistant results).
One more thing, did you somehow disable or hide the native expansion icons (triangles) from your outline view ? If not, the user will be able to expand multiple top nodes without  going through your automatic collapsing logic.
[EDIT] I had time to test the event behaviour and the outline's selection seems to be updated before the call to the IBAction.  The following function should perform the automatic expansion and collapsing correctly:
@IBAction func outlineClicked(_ sender: Any)
{
  autoExpandAndCollapse()
}

func autoExpandAndCollapse()
{
   guard let selectedItem = outline.item(atRow:outline.selectedRow),
             outline.parent(forItem: selectedItem) == nil
   else  { return }

   for level1Index in (0..<outline.numberOfChildren(ofItem: nil)).reversed()
   {
      if let topLevelItem = outline.child(level1Index, ofItem: nil),
         outline.isExpandable(topLevelItem)
      {
         if outline.selectedRow == outline.row(forItem: topLevelItem)
         && !outline.isItemExpanded(topLevelItem)
         { outline.expandItem(topLevelItem)   }
         else
         { outline.collapseItem(topLevelItem) }
      }
   }
}

BTW, I assumed that you only wanted this to apply to the top level nodes.  If not, you can probably adjust the logic to your requirements.
[EDIT2] adjusted to fix bug that closed parent when child with same sibling index was clicked, simplified code a bit.
Comment: hey Alain T. thanks for your answer. can you show me your explanation as a code example ? that is better for me to learn :)
Comment: now i use outlineView.collapseItem(nil) instead of the loop to collapse all items. thanks for this tip. i only link my outline view like this `@IBAction func outlineViewClicked(_ sender: NSOutlineView) { }`as click event.
Comment: if I only put this code in to my function `print(outlineView.isItemExpanded(outlineView.selectedRow))` it always print "False" if i expand an item
Comment: It is likely that the OutlineView's item expansion is only performed after the outlineViewClicked() event is called so at that point the item is not yet expanded.
Comment: yeah, it is very close, but there have to be a litte bug. some child elements collapse the root element on click. an idea? :)
Comment: Yea, that was my bad. I used the child index as if it was a row number.  I updated the code.


Gatling not picking up actions once on portal

Question: Not sure why this is happening but when using the recorder it stops recording immediately after typing in the target address.  Once inside the portal it no longer records any actions.  Does this have to do with the web address being on https?  What actions should I take in order to utilize the recording tool?
Comment: You'd have to provide more information, or a way to reproduce.
Answer: To answer my own question I had to access the 1.5.6 documentation.  It talked about how to properly setup firefox network connections for interacting within https environment.
This is how it should look.  This affects working within any HTTPS environment
Comment: Everything's in there in the current documentation. From quickstart: "... and configure your browser to use Gatling Recorder's proxy. For more information regarding Recorder and browser configuration, please check out Recorder reference page." Then: http://gatling.io/docs/2.1.4/http/recorder.html#recorder
Comment: Its in the 1.5.6 documentation.  Not the current.  The images do not line up with what the downloadable file is and what the documentation says.
Comment: Stop referring to old dropped 1.5.6 and properly read the doc!!! You'll find the same kind of image in there: http://gatling.io/docs/2.1.4/http/recorder.html#listening-proxy-port
Comment: Hey now don't get mad.  The documentation isn't the same.   I'm sorry 2.1.4 does not reflect  the same interface for the recorder that 1.5.6 documentation does.  Even through the download link is supposedly for the 2.1.4.


What is the best method to access main data from child's components?

Question: I have an application where validation requires referring to the app controller. My App controller looks like this:
export class AppComponent {
  objectName: ObjectName;

  constructor(public dialog: MatDialog) {
    this.objectName= new ObjectName();
    this.objectName.objects1 = this.getObjects1();
    this.objectName.objects2 = this.getObjects2();
  }

What is the best method to access this data from child's components?
Comment: Move this to a service ?
Comment: Hi @user3302358, did an answer help you ? If so, can you please mark it as accepted ? Thanks
Answer: If it is a direct child you can simply use an Input parameter. If it is a grandchild or a sibling then the best practice is to use a shared service and communicate vs a behaviorSubject.
Read this, it is te official guide and will answer all your questions
Comment: Ok, I know this method but when you need to use data from app controller in child child child component only for validation I don't think it is best method
Answer: If you want to access any of the following inside the Parent Component, use @ViewChild decorator of Angular.

Child Component
Directive
DOM Element

to retrieve value We need to do the following tasks:

Import ViewChild and AfterViewInit from @angular/core
Implement AfterViewInit life cycle hook to component class
Create a variable with decorator @ViewChild
Access that inside ngAfterViewInit life cycle hook
Answer: I'm used to do that with an EventEmitter as follow :
emitter.helper.ts

// Angular modules
import { Injectable }   from '@angular/core';
import { EventEmitter } from '@angular/core';

// Models
import { ObjectName }   from '...';

@Injectable()
export class EmitterHelper
{

  public static emitObjectName : EventEmitter<ObjectName> = new EventEmitter();

  public static sendObjectName(objectName : ObjectName) : void
  {
    this.emitObjectName.emit(objectName);
  }
}

Don't forget to share this helper by adding it to the providers of app.module.ts.
Now you can import and use the EmitterHelper between components :
Component A
EmitterHelper.sendObjectName(this.objectName);

Component B
EmitterHelper.emitObjectName.subscribe((objectName : ObjectName) =>
{
  console.log(objectName);
});


Fail to create Android virtual Device, "No system image installed for this Target"

Question: Unable to create Android Virtual Device
i follwed this link.
I installed all ARM images for each Android more than 4.0.
I installed intel & MIPs as well.
But, still my AVD Manager is saying "NO System images installed for this target".
why, so?
Comment: In SDK manager, do you see Android Wear ARM EAB system image, and is that installed?
Comment: Yea I have installed them
Comment: Are you sure you don't have two different installations of SDK? Can you do the following from command line: (a) go to your SDK root directory (b) change directory to "tools" directory (c) run ./android sdk, then make sure that SDK platform  (API level 19) and Wearable image (Android Wear ARM EAB...), along other required ones mentioned in the documentation are all installed, (d) run "./android avd" and see if it works now or not. In AVD manager, make sure target is set to API level 19, then see if under CPU/ABI you can find the wearable option.
Comment: Also make sure to restart eclipse if you just downloaded them
Answer: In order to create an Android Wear emulator you need to follow the instructions below:

If your version of Android SDK Tools is lower than 22.6, you must update
Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.
Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.

Below is the snapshot of what it should look like:

Then you must check the following in order to create a Wearable AVD:

For the Device, select Android Wear Square or Android Wear Round.
For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).
For the CPU/ABI, select Android Wear ARM (armeabi-v7a).
For the Skin, select AndroidWearSquare or AndroidWearRound.
Leave all other options set to their defaults and click OK.

Then you are good to go. For more information you can always refer to the developer site.
Comment: "Google APIs (Google Inc.) - API Level 19" may be easier to locate in the Target drop down... That is not the correct one which was where I ran into problems when trying to create an AVD. The one mentioned in this answer is located higher up in the selection list and may be harder to find right away. So just be careful, there are multiple options with API Level 19 and only the one mentioned above is the correct one.
Comment: Is there any reason for NOT installing all these components? Can it make the virtual device slower? Or can I just check all boxes and space used is the only drawback ?
Comment: @adrianTNT: Which components you asking ?
Comment: I meant the ones with check boxes shown in above image, but since then I found that checking all these components can use around 15GB of space, compared to around 500MB default space used by Android Studio install. So that kind of answered my question.
Answer: As a workaround, go to sdk installation directory and perform the following steps:

Navigate to system-images/android-19/default
Move everything in there to system-images/android-19/

The directory structure should look like this:

And it should work!
Comment: In system-images I have android-22, 23 and 24, but avd manager shows only API 23 and no CPU/ABI for it (eventho I tried moving files from 23's default folder to the parent folder). Any hints what to do? In Android Studios SDK Manager I have everything installed, and it finds everything, but I'm trying to use AVD for nativescript, so I need 'android avd' from terminal to find working avd.
Answer: If you use Android Studio .Open the SDK-Manager, checked "Show Package Details"  you will find out "Android Wear ARM EABI v7a System Image" download it , success !
Answer: I had android sdk and android studio installed separately in my system. Android studio had installed its own sdk. After I deleted the stand-alone android sdk, the issue of ""No system image installed for this Target" was gone.


QoS for Firebird database connections - how?

Question: Our Firebird database connection goes through a network connection that seems to imply a high latency for normal TCP connections. However, I am quite sure that the network connection supports quality-of-service on network traffic. Is there any way to specify QoS parameters to a Firebird connection?
Comment: From my point of view, this question does not belong to StackOverflow, but to ServerFault.
Comment: I would prefer to see a gds32.dll api call or OS api call as a solution, that is why it is on stackoverflow.com, too - but I don't consider this likely. I think that a tcp tunnel solution or server configuration solution is most likely to be found first.
Answer: The solution is going to be dependent on the configuration capabilities of your network hardware.
One thought, if the server hosting the database is primarily just for hosting the database, or the other services on it are also important, see if you can configure traffic to/from that server to a higher priority than standard traffic.
Answer: May be you can try to use compressed "tunnel" for TCP/IP like Zebedee
Comment: Compressing is not the issue here.


KeyedProcessFunction implementation throwing null pointer exception?

Question: First Example: code from "https://ci.apache.org/projects/flink/flink-docs-stable/dev/stream/operators/process_function.html"
I am trying to override processElement() of KeyedProcessFunction class. ProcessElement has 3 parameters and one of a parameter is context object. When I tried to retrieve timestamp from context object, it throws null pointer exception.
A line which throws null pointer exception in First example code is
current.lastModified = ctx.timestamp();
Second Example: Example 6.5 of "Stream Processing with Apache Flink" book.
I have two ValueState variables declared in a class which extends KeyedProcessFunction class. When I tried to retrieve the last value updated in the state, it returns a null value.
A line which throws null pointer exception in First example code is
Double prevTemp = lastTemp.value();
if(prevTemp==0.0 || r.temperature < prevTemp) {}
First Example code
public class KeyedProcessFunctionExample {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment=
                StreamExecutionEnvironment.getExecutionEnvironment();

        environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        DataStream<Tuple2<String, String>> stream =
                environment.socketTextStream("localhost",9090)
                        .map(new MapFunction<String, Tuple2<String, String>>() {
                            @Override
                            public Tuple2<String, String> map(String s) throws Exception {
                                String[] words= s.split(",");

                                return new Tuple2<>(words[0],words[1]);
                            }
                        });

        DataStream<Tuple2<String, Long>> result = stream
                .keyBy(0)
                .process(new CountWithTimeoutFunction());

        result.print();

        environment.execute("Keyed Process Function Example");

    }
    public static class CountWithTimeoutFunction extends KeyedProcessFunction<Tuple, Tuple2<String, String>, Tuple2<String, Long>> {
        private ValueState<CountWithTimestamp> state;

        @Override
        public void open(Configuration parameters) throws Exception {
            state = getRuntimeContext().getState(new ValueStateDescriptor<>("myState", CountWithTimestamp.class));
        }

        @Override
        public void processElement(
                Tuple2<String, String> value,
                Context ctx,
                Collector<Tuple2<String, Long>> out) throws Exception {

            // retrieve the current count
            CountWithTimestamp current = state.value();
            if (current == null) {
                current = new CountWithTimestamp();
                current.key = value.f0;
            }

            // update the state's count
            current.count++;

            // set the state's timestamp to the record's assigned event time timestamp
            current.lastModified = ctx.timestamp();

            // write the state back
            state.update(current);

            // schedule the next timer 60 seconds from the current event time
            ctx.timerService().registerEventTimeTimer(current.lastModified + 60000);
        }

        @Override
        public void onTimer(
                long timestamp,
                OnTimerContext ctx,
                Collector<Tuple2<String, Long>> out) throws Exception {

            // get the state for the key that scheduled the timer
            CountWithTimestamp result = state.value();

            // check if this is an outdated timer or the latest timer
            if (timestamp == result.lastModified + 60000) {
                // emit the state on timeout
                out.collect(new Tuple2<String, Long>(result.key, result.count));
            }
        }
    }
}

class CountWithTimestamp {

    public String key;
    public long count;
    public long lastModified;
}

Second Example
public class KeyedProcessFunctionTimerExample {
    public static void main(String[] args) throws Exception{
        // set up the streaming execution environment
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // use event time for the application
        env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);

        DataStream<String> sensorData=
                env.addSource(new SensorSource())
                .keyBy(r -> r.id)
                .process(new TempIncreaseAlertFunction());

        sensorData.print();
        env.execute("Keyed Process Function execution");
    }

    public static class TempIncreaseAlertFunction extends KeyedProcessFunction<String, SensorReading, String> {

        private ValueState<Double> lastTemp;
        private ValueState<Long> currentTimer;

        @Override
        public void open(Configuration parameters) throws Exception {
            lastTemp = getRuntimeContext().getState(new ValueStateDescriptor<Double>("lastTemp", Types.DOUBLE));
            currentTimer = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timer", org.apache.flink.api.common.typeinfo.Types.LONG));
        }

        @Override
        public void processElement(
                SensorReading r,
                Context ctx,
                Collector<String> out) throws Exception {

            // get previous Temp
            Double prevTemp = lastTemp.value();

            // update last temp
            lastTemp.update(r.temperature);

            Long curTimerTimestamp = currentTimer.value();

            if(prevTemp==0.0 || r.temperature < prevTemp) {
                ctx.timerService().deleteProcessingTimeTimer(curTimerTimestamp);
                currentTimer.clear();
            }
            else if(r.temperature > prevTemp && curTimerTimestamp == 0) {
                Long timerTs = ctx.timerService().currentProcessingTime() + 1000;
                ctx.timerService().registerProcessingTimeTimer(timerTs);
                currentTimer.update(timerTs);

            }
        }

        @Override
        public void onTimer(
                long ts,
                OnTimerContext ctx,
                Collector<String> out) throws Exception {

            out.collect("Temperature of sensor ' " + ctx.getCurrentKey() + " ' monotonically increased for 1 second.");
            currentTimer.clear();

        }
    }

}

It should not throw null pointer exception. Your help will be appreciated. Thanks!
Answer: When working with event time in Flink you must arrange for the events to have timestamps, and for the streams to have watermarks. You do this by implementing a timestamp extractor and watermark generator, as described here and here.
See also the tutorial.


how to setup blocks that differentiate 'node edit' case from 'node add' case in MULTISTEP forms

Question: Im using Drupal 6 and the multistep module :
I need to display informations in a block apart when my users wether add or edit some of the available multistep forms :
. there's a block that shows up with an EDIT title when EDITING an existing node with information within it for this case :
only shows up when :
node/*/edit* page

. there's a block that shows up with a CREATE title when ADDING a node :
only shows up when :
node/add/multistep-content-A*
node/add/multistep-content-B*
node/*/edit*

node//edit is necessary for ADDING since when the user finishes the first step of the form, the node is saved and the link which was node/add/m-c-A turns into node/nid/edit.
in both block I use a bit of php ( url arg(), $node) to check content type, to retrieve node info if exists, to decide wether show info for ADDING cases or for EDITING cases. (as there's nothing to show, the entire block DIV does not show up)
I would need to recognize the ADDING case after step 2 of the form...
when the node is created but when the progress bar is lesser than 100%.
in other words, to retrieve the 'completion status' argument from the multistep module, the one that tells the progress bar if the form is completed or not.
it appears it's not in the $node array.. ?
EDIT : found a trick, see comment 2.
Comment: there's a _multistep_is_complete(&$form_state) function in the mstep module, what is $form_state..
Comment: well ok, I found a way using $node->status and tells multistep to only publish at node completion :) still, I dont know how to retrieve the form status.
Comment: If you found an answer yourself, it's good to post the answer below, and mark it as accepted so that everyone knows the issue is resolved. Btw, welcome.
Comment: Awesome, now you just need to accept it, which is done with the check/tick below the points voting in the top left hand corner of the answer. After that, all is good, and it will help other people with the same pronlem to find an answer more easily. Thanks!
Answer: I dont know how to retrieve the multistep completion state from a block but there's a simple way, by testing the published status (not published ? not complete ADD/PENDING - published ? complete EDIT)
in admin/settings/multistep :
select Publishing > at node completion
in the ADD block that must be displayed when adding a multistep node :
only display block on the pages below :
node/add/multistep-content-A*
node/add/multistep-content-B*
node/*/edit*

in the ADD block body :
Title : add
<?php
$show = FALSE ;
if ( arg(0) == 'node' && arg(1) == 'add' ) {
  if (in_array(arg(2), array( "multistep-content-A", "multistep-content-B" ))) {
    $show = TRUE ;
    $node = False ;
  }
}
elseif ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
  if (in_array($node->type, array( "multistep-content-A", "multistep-content-B" )) && $node->status == 0) {
    $show = TRUE ;
  }
}
if ($show) {
  if ($node) print 'id : '.$node->nid . '' ;
  print "

some info about creating this node.

be sure to complete every step blah blah the italic ones

" ;
}
?>

in the EDIT block :
Title : modify
node/*/edit*

body :
<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
  if (in_array($node->type, array( "multistep-content-A", "multistep-content-B" )) && $node->status == 1) {
    print 'id fiche : '.$node->nid . '' ;
    print "

some info about editing an existing node.

browse directly to the steps you need to modify by using the link below.

" ;
  }
}
?>

there might be a way to only have one block, that could change its title itself, I didn't investigate.


How do I print a blank line whenever the first letter of the state differs from the previous state's first letter

Question: I am given a list of states as a .txt file. I was able to read each line, stripping off newline character and append data to states_list, but I also need to print a blank line whenever the first letter of the current state differs from the previous state's first letter.
Here is what I have tried:
states_list = []
n = 0

with open('states.txt', 'r') as f:
    for line in f:
        state = line.strip('\n')
        states_list.append(state)

for each in states_list:
    if states_list[n][0] != states_list[n+1][0]:
        print("\n")
    print(each)

Comment: I don't see a question here...
Comment: The OP signed up today and this is the OPs first post. WHY SO MANY DOWN-VOTES???
Comment: Why downvotes? Because it's a code dump with no actual question. Such "questions" show no research effort and are neither clear nor useful, which describes the criteria for a downvote.
Comment: And the OP clearly did not read "[How do I ask a good question?](https://stackoverflow.com/help/how-to-ask)" before asking his/her question.
Answer: If you need to compare with other members, don't use the for-each loop.
for i in range(len(states_list)):
     if i > 0:
         if states_list[i][0] != states_list[i-1][0]:
             print('\n')
     print(states_list[i])

Comment: Using this method, first element won't be printed.
Comment: Good catch, fixed now.
Answer: Another way of going about this is to use zip():
with open('states.txt', 'r') as f:
    states = [line.strip('\n') for line in f]

for a, b in zip(states, states[1:]):
    if a[0] != b[0]:
        print("\n")
    print(a)
print(states[-1])

In the end, it produces the same result as jeff carey's answer, but perhaps in a more Pythonic/elegant way.
Comment: Thank you! And I learned about zip( ) for the first time, as well!


Download file using angular js by calling spring rest api

Question: I have a Spring Controller which send file in response
@RequestMapping(value = "/downloadData", method = RequestMethod.GET)
public void downloadData(HttpServletResponse response) throws IOException
{
    File dataJSONFile = dataDownloadService.createAndWriteFile();
    response.setContentType("application/text");
    response.setContentLength(new Long(dataJSONFile.length()).intValue());
    response.setHeader("Content-Disposition", "attachment; filename="data.json");
    FileCopyUtils.copy(new FileInputStream(dataJSONFile),
    response.getOutputStream());
}

If I write in browser url, //localhost:8080/myproject/rest/downloadData It downloads the file.
Now, want to download the file when click on button in using angular js.
I have written following code in angular js to download file
angular
    .module('myApp.services')
    .factory(
            'DataDownloadService',
            function($resource) {
                "use strict";
                return {
                    "query" : function() {
                        var ret, restResource;
                        restResource = $resource(
                                '/sand-pp/api/rest/downloadData',
                                {}, {
                                    "query" : {
                                        "method" : "GET",
                                        "isArray" : true,
                                        headers:
                                        {
                                            'Content-Type': 'application/text',
                                            'Content-Disposition': 'attachment; filename=data.json'

                                        }
                                    }
                                });
                        ret = restResource.query();
                        return ret;
                    }
                };
            });

When I call above service nothing is happening but if I print data in callback function is printing data in console.
How to download file in angular js by calling Spring REST api?
Answer: I would use a service for the rest call. Try this following:
window.location.href = DataDownloadService.query();
It should prompt the browser to download the file (because of Content-Disposition header).


Aegir Installation - how to get the sender email correct to allow install to pass

Question: During the Aegir installation procedure, the
sudo apt-get install -y aegir3 aegir-archive-keyring

step runs through a series of installation commands that eventually try to send an email from the aegir user to the aegir user.
Depending on my build environment this may work or not depending on whether the the aegir user is set up as a valid email sender.  I already have the sending email squared away with MSMTP and can send email from my command line but the installer seems to always be assuming the sending is aegir@hostname.
It would be very nice if I could figure out how to 1) override the sender in the installation script or 2) set the email address of the aegir user manually via CLI.
You'd think that 2 would be very easy to find on the internet but, believe it has been anything but easy.
Does anyone know how to alter the apt-get install of Aegir to pick up the sender email address from some environment variable?
Thanks
Answer: Found the answer in section 7.1 at https://docs.aegirproject.org/install/#7-install-aegir
sudo apt install debconf-utils
mkdir -p ~/projects/aegir/core
git clone https://git.drupal.org/project/provision.git ~/projects/aegir/core/provision
echo "aegir3-hostmaster aegir/email string email@example.com" | sudo debconf-set-selections
sudo apt install aegir3