Non trivial element in the second homotopy group of a manifold

Question: Let $M$ be a closed orientable $n$-dimensional manifold and $\Sigma$ be a $2$-dimensional sphere embedded in $M$ such that there is a map $f:\Sigma\rightarrow \mathbb{S}^2$ with non zero degree, i.e., $deg (f)\not=0$. Is it true that the embedding of $\Sigma$ in $M$ represent a non trivial element of $\pi_2(M)$? if so, how can I prove it?
Comment: Please say "second homotopy group" rather than "second fundamental group".
Answer: I'm guess you mean that there is a map $f:M\to S^2$ whose restriction to $\Sigma$ has non-zero degree. In that case it is true: otherwise there is a homotopy $F:\Sigma \times [0, 1] \to M$ contarcting $\Sigma$ to a point, and composing $F$ with $f$ gives a contracting homotopy from  $f|_{\Sigma}=f\cdot F_0: \Sigma \to S^2$ to the constant map $f\cdot F_1: \Sigma \to S^2$
Answer: Let $M$ be $S^3$, The stereotgraphic projection allows to identify $S^3-\{point\}$ to $\mathbb{R}^3$, there are spheres imbedded in $\mathbb{R}^3$ but $\pi_2(S^3)=1$.


TextWatcher not serving its purpose

Question: The following code snippet is used for a text Watcher...it doesnt work...everything works fine,untill the last line of code...
private TextWatcher mobileTextWatcher = new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        String number = s.toString();
        number = AppConstants.convertToOnlyDigits(number);
        Editable temp = new SpannableStringBuilder(
                AppConstants.formatPhoneNumber(number));
        s = temp;
    }
};

After that the new doesn't get assigned to s.. Or in otherwords,I cannot see a change in the text in the Edit Text.
Answer: As s is function argument you cannot reassign it and save new value beyond the scope of function.
If I understood your goal right - you should assign temp value to EditText by setText() method
Comment: But that would result in an infinite loop...Will s.replace() serve the purpose?
Answer: The parameter are not passed as reference, so s =   temp; will not change the text in edittext.
Try like this
private TextWatcher mobileTextWatcher       =   new TextWatcher() {
        boolean inWatcher = false;
        @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,int after) {
    }
    @Override
    public void afterTextChanged(Editable s) {
        if(inWatcher) { inWatcher = false; return; }
        String number   =   s.toString();
        number          =   AppConstants.convertToOnlyDigits(number);
        Editable temp   =   new SpannableStringBuilder(AppConstants.formatPhoneNumber(number));
        inWatcher = true;
        your_edit_text.setText(temp);
    }
};

Answer: You gotta actually set your EditText's text again with the setText() method.
Before you do this, you might want to add a simple boolean check as 'mFormatting', to make sure you do not get into an infinite loop of the textWatcher calling itself, after making changes.
Answer: You are not changing the object in s, you are instead replacing the variable s with another object.
Try something like this:
boolean recurseProtection = false;
@Override
public void afterTextChanged(Editable s) {
    if(!recurseProtection) {
        String number = s.toString();
        number = AppConstants.convertToOnlyDigits(number);
        recurseProtection = true;
        s.clear();
        s.append(AppConstants.formatPhoneNumber(number));
        recurseProtection = false;
    }
}

Note I've added some protection to stop afterTextChanged being called when you change s object (which I assume has a DataObserver placed on it). Recursion protection is off the top of my head so might need tweaking.
Hope this helps.
Comment: It works fine...My bad...Please edit your answer so that I can upvote

TextWatcher not serving its purpose


Conditional Probability Uniform Bivariate Transformation Distribution

Question: I'm reviewing probability theory from years ago and am a bit rusty. I'm not sure how to calculate the conditional probability for a uniform distribution after a bivariate transformation.
Suppose X and Y both follow a Uniform$(0,2)$ distribution. For the transformation $U=X+Y$ and $V=X$, I'll then have the following joint PDF:
\begin{cases}
    \frac{1}{4}, & \text{if $0<V<U<4$}.\\
    0, & \text{otherwise}.
  \end{cases}
How would I calculate the conditional probability $P(V<.2|U=1.5)$? I'm likely missing something very intuitive. I've had someone say that U follows a $U(0,1.5)$ distribution and thus $P(V<.2) =\frac{1}{1.5} * .2$ but that doesn't seem right to me. I'd have to multiply by $\frac{1}{4}$ at some point, right?
Edit:
Conditional. on $f(V|U)$
First found the marginal of $U$ as follows:
\begin{cases}
    \frac{u}{4}, & \text{if $0<U<2$}\\
    \frac{1}{2}-\frac{u-2}{4}, & \text{if $2<U<4$}\\
    \ 0, & \text{otherwise}
\end{cases}
Since $U=1.5$, the conditional $f(V|U=1.5)=\frac{f(U,V)}{f(U=1.5)}=\frac{\frac{1}{4}}{\frac{u}{4}}=\frac{1}{1.5}$
So the probability $(V<.2|U=1.5)=$
$$\int_{0}^{.2} \frac{1}{1.5} dv = .2*\frac{1}{1.5} - 0*\frac{1}{1.5}=.133$$
Comment: You are missing the independence of $X$ and $Y$. The distribution of $U$ is not uniform. Find the conditional density of $V$ given $U$ and hence the probability.
Comment: @StubbornAtom I added the conditional to my post. My process was correct, right? Sorry I know this is simple stuff, just been so long.
Comment: Why in the joint PDF you have $0<V<4$? Shouldn't it be $0<V<2$ since $V=X$?
Comment: I think you can find everything you need here https://www.youtube.com/watch?v=qUBlhsJpf1g
Comment: @ping Oh, yes. It should be 0<V<2 and 0<V<U<V+2 right?
Comment: Please have a look at my answer. I've tried to draw the domain of the joint pdf of U and V
Comment: @ping Doesn't your drawing confirm that it's 0<V<2 and 0<V<U<4?
Comment: Yes both conditions together
Answer: This follows my comment (using the approach shown in the Youtube video). Once you have the joint you can calculate the conditional.
Sorry for the typo. Of course, $g_2(X,Y)=X$, and not $Y$.


Get the "href" attribute of an image

Question: I created a new content type in Drupal 7, and added an image field named "field_photo." Can anyone tell me how I can extract the "href" attribute of that photo? Is there a short code I can use?
Answer: When you access the field on your node you will get the file id. This can be passed to file_load which will return the file object. One of the properties is filepath which holds the path to the actual file. I'm guessing that's what you are after - images doesn't use href  tags do.
Comment: Yes,  tags. I just assumed we were already on the same page. Will give it a try.

Get the "href" attribute of an image


get the texts with xpath query

Question: i want to get the main texts of this page :
[this link][1]
i used this code to find the main text :
NSString *tutorialsXpathQueryString = @"//div[@id='middlepane']/table[2]/tr/td/div[1]/font";

but it is not working!
it is the saved page of that link
http://www.mediafire.com/?0t9de2f0b0928nk
@Ryan Kohn : no error happened
 and just returns empty or NULL value
that file is complex and large and i cant write in this page !
Comment: Instead of linking to the external site from here, please include a sample of the page's HTML that you wish to retrieve.
Comment: Also, are there any specific errors you're getting?
Comment: @coder4xc: Can you please provide the HTML code so that it might be easier to answer
Answer: Try this XPath:
string pageContentXPath = "//div[contains(@align, 'justify')]";

Note that this may be a bit unstable because it's using the 'align' property of the div.  If this changes, the XPath will not work anymore.
Comment: this does not work !  i want to get the texts of the font tag

get the texts with xpath query


Matlab figure as png

Question: I am saving a matlab figure as png. I want to set the print size tight to the screen size, so I used:
set(gca(),'LooseInset',get(gca(),'TightInset')); %set print size tight to the screen size

However my image is not being saved tight to the screen size nor at the centre of the screen...
Here is my code with everything I already tried:
function []=FilledCircle1(x0,y0,Radius,N,col1)

if(N<=1)
    error('N must be greater than 1');
end

hold on
axis equal
% axis off
hold on

t=(0:N)*2*pi/N; %t=-pi:0.01:pi
x=Radius*cos(t)+x0;
y=Radius*sin(t)+y0;

c1=fill(x,y,col1);

set (c1, 'edgecolor','k')

set(gcf,'PaperUnits','inches','PaperSize',[0.8666,0.8666],'PaperPosition',[0 0 0.8666 0.8666])%setting size (130/150, 130/150, 150pixels per inch being the default size of img), paper position is imporrtant as otherwise i will have extra border

% % set(gcf,'Position', [0 0 4.4466 3.5733], 'units','inches')
% % iptsetpref('ImshowBorder','tight');

set(gca(),'LooseInset',get(gca(),'TightInset')); %set print size tight to the screen size

% set(gcf, 'Position', get(0,'screensize'));

set(gcf,'color','none'); %set backgroound color to transparent
fig = gcf;
fig.InvertHardcopy = 'off'; %saves the fig with the set background color

I would like my png file to look like this:

However it's looking like this:

Can someone help me understand what am I doing wrong?
Thank you!
Comment: It's not at all clear how the first image relates to the second. Regardless, insets apply to the *axes*, not what's plotted in it. If you want the plotted object to be centered and zoomed then you have to change the axes limits before you save it.
Comment: The first image is just to show that I want the filled circle I ploted to be centered and filling the all screen. @excaza
Answer: The issue is because the labels of the x and y ticks are displacing your graph.

Rather than messing with TightInset, I would just set the Position property of the axes to make the inside of the axes take up the entire figure
hfig = figure();
hax = axes();

t = (0:N)*2*pi/N; %t=-pi:0.01:pi
x = Radius*cos(t)+x0;
y = Radius*sin(t)+y0;

c1 = fill(x,y,col1);

set(c1, 'edgecolor','k')

set(hfig, 'PaperUnits', 'inches', ...
          'PaperSize', [0.8666,0.8666], ...
          'PaperPosition', [0 0 0.8666 0.8666], ...
          'InvertHardCopy', 'off')

axis(hax, 'equal')
axis(hax, 'off')

set(hax, 'Position', [0 0 1 1]);
set(hfig, 'Color', 'none');

print(hfig, '-dpng', 'output.png')

You should also consider using export_fig as it more faithfully reproduces the graphics shown on the screen.
Comment: export_fig saved my mental health multiple times, I also strongly advise its use.
Comment: Thank you @Suever!

Matlab figure as png


How to change name of jrxml file?

Question: I want to change the name of my JasperReports's report from "Test Report  Detail " to  "Test Reagent Detail"
Answer:
right click on the report from left panel and click "properties"
the first column is your report name, you can click on the icon "..." and it will open your report name that can easily be edited.
use the "save as" option to save the renamed report if necessary.
Comment: > thanks  it's working But need to Rename the  .jrxml file
Comment: like i already mentioned in point 3, you can use "save as" option and mentioned the name "Test Reagent Detail" while saving and simply delete the old file.

How to change name of jrxml file?


Loop autoincrementando data

Question: Como posso fazer um auto increment de data por mês e mostrando o ultimo dia do mes
Exemplo:

2017-01-31
2017-02-28
2017-03-31

$parcelas  = 12;
$data_inicial = 2017-01-31
for ($i = 1; $i <= $parcelas; $i++){
    // abaixo o auto increment
    echo $data_inicial.........??????
}

Comment: http://pt.stackoverflow.com/a/38633/91
Comment: Tente algo assim dentro do seu `for`: `echo date('Y-m-t', strtotime("2017-" . ($i < 10 ? "0$i" : $i) . "-01")) . "\n";`
Comment: Ok interessante o 't'.... mais i como fazer ele em sequencia
Answer: Para pegar sempre as última data do mês use date com mktime():

date('t', mktime());

Gerar parcelas pelo último dia do mês de acordo com a informação do ano:
function gerar_parcelas($y = 2017)
{
    $parc = array();
    for($i = 1; $i < 13;$i++){
        $parc[] = date('Y-m-t', mktime(0,0,0,$i,1,(int)$y));
    }
    return $parc;
}

var_dump(gerar_parcelas(2017));

Exemplo

Nesse outro código é gerado como se fosse parcelas de pagamento, ou seja, se informou 13/12/2005 e a quantidade de parcelas o algoritmo gerar a partir dessa data só alterando o mês e ano se for pra o próximo. Esse código também se encaixa a sua duvida se for informado a última data do mês com 12 parcelas.
Gerar parcelas por uma data:
<?php

function parcelas($data, $numero = 12)
{
    $parc = array();
    $parc[] = $data;
    list($ano, $mes, $dia) = explode("-", $data);
    for($i = 1; $i < $numero;$i++)
    {
        $mes++;
        if ((int)$mes == 13)
        {
            $ano++;
            $mes = 1;
        }
        $tira = $dia;
        while (!checkdate($mes, $tira, $ano))
        {
            $tira--;
        }
        $parc[] = sprintf("%02d-%02d-%02d", $ano, $mes, $tira);
    }
    return $parc;
}

$data = "2017-01-31";

var_dump(parcelas($data, 12));

Exemplo
Nesse segundo exemplo é gerado pela data então para funcionar igual está na pergunta sempre tem que passar o último dia do primeiro mês do ano, porque, esse código gera para qualquer dia do mês diferente do primeiro que pega o ano e gera as últimas data do mês daquele ano.
Referencias:

date
mktime
checkdate
Answer: Você pode fazer assim
<?php
$parcelas = 12;
$data_inicial = '2017-01-31';
for ($i = 1; $i <= $parcelas; $i++){
    echo $data_inicial."
";
    $d = new DateTime( $data_inicial );
    $d->modify( 'last day of next month' );
    $data_inicial = $d->format( 'Y-m-d' );
}

Answer: Matar uma mosca com uma bala de canhão?! Pois bem, pensei em uma maneira bem simples de resolver seu problema que seria você usar strtotime(). Veja o código abaixo:
<?php
function returnDates($parcelas, $ultima_data){
    for ($i = 1; $i <= $parcelas; $i++){
       $date = strtotime("+$i month", strtotime($ultima_data));
       echo date("Y-m-t", $date)."\n";
    }
}

echo returnDates(20,"2007-02-12");

No exemplo acima eu chamo a função colocando o numero de parcelas e a data inicial.
Veja o exemplo funcionando no ideone.
Comment: @fabio-henrique Depois tenta desta forma aqui e me fala o que acha! Abs.
Answer:          $m=0;
         for($i=1;$i <= $nparcelas; $i++){
            $a1 = new DateTime($data_inicial);
            $a2 = new DateInterval('P'.$m.'M');
            $a1->add($a2);
            $a1->format("Y-m-d") -> formatação datetime para inserir no banco
            $m++;
         }

Comment: você testou o código ? no teste que eu fiz a variavel `$m` não existe, alterando ela para `$i` tem um problema do mês 1 para 2 por ter apenas 28(ou 29) dias.
Comment: cria ela antes $m=0; e no fim do for $m++; assim o loop começa com o mês atual e tem o auto incremento de 1 a 1
Comment: Entendi, mas o problema de se perder das datas continua, execute seu código para ver o resultado.
Comment: eu uso ele.. ele vai auto incrementar na medida que você quiser que $m seja incremento seja ++ (de 1 em 1) ou $m = $m +2 ;  e por ae vai...
Comment: Quanto tiver tempo faz o teste simulando que está no dia 29, 30 ou 31. Nos demais dias funciona normalmente.
Comment: estranho aqui funcionou normal, gerei 3 parcelas a partir do dia 29/11 e ele gerou as 3 consecutivas normal.. não vejo o que pode estar fazendo essa perca da sequencia
Comment: Faz com 4 parcelas, ai vai cair no mês de fevereiro que tem 28 dias, e ele vai pular para o mês seguinte.
Comment: a sim, mais ai precisa tratar essas exceções dentro do for, pra toda a regra existe uma exceção, alem disso caso tenha essa necessidade de precisão talvez tenha interesse em tratar feriados e por ai vai....

Loop autoincrementando data


M. Ross problem 12 chapter 5 - Exponential distribution

Question: I have a question regarding problem 12(b) and (c) of chapter 5 of M.Ross "Introduction to probability models".
The question is as follows:
If $X_1, X_2, X_3$ are independent exponential random variables with rates $\lambda_i$, $i = 1,2,3$, find
(b) $P(X_1 < X_2 \mid \max(X_1,X_2,X_3) = X_3)$;
(c) $E[\max X_i \mid X_1 < X_2 < X_3]$.
For (b), my first thought was that $P(X_1 < X_2 \mid \max(X_1,X_2,X_3) = X_3) = P(X_1 < X_2)$ since from my point of few, $\max(X_1,X_2,X_3) = X_3$ does not have to influence $X_1 < X_2$.
According to the answer book of Ross:
$P(X_1 < X_2 \mid \max(X_1,X_2,X_3) = X_3) = \frac{P(X_1 < X_2 < X_3)}{P(X_1 < X_2 < X_3) + P(X_2 < X_1 < X_3)}$.
Can anyone explain me what mistake I made with my initial reasoning?
For (c) I have no clue how to reason to get the correct answer.
Answer: (b) The following might help to understand your mistake.
Let $U_{1},U_{2},U_{3}$ be independent random variables where $P\left(U_{1}=1\right)=P\left(U_{1}=3\right)=\frac{1}{2}$
and $P\left(U_{2}=2\right)=1=P\left(U_{3}=2\right)$.
Then it is evident that: $$P\left(U_{1}<U_{2}\mid\max\left(U_{1},U_{2},U_{3}\right)=U_{3}\right)=1\neq\frac{1}{2}=P\left(U_{1}<U_{2}\right)$$
(Almost) degenerated random variables can be very helpful to examine questions like: "is my intuition correct here?"

(c)
Under condition $X_{1}<X_{2}<X_{3}$ you are dealing with the original
PDF divided by probability $P\left(X_{1}<X_{2}<X_{3}\right)$.
To be worked out is the integral:$$\frac{\frac{1}{\lambda_{1}\lambda_{2}\lambda_{3}}\int_{0}^{\infty}\int_{x}^{\infty}\int_{y}^{\infty}ze^{-\lambda_{1}x-\lambda_{2}y-\lambda_{3}z}dzdydx}{\frac{1}{\lambda_{1}\lambda_{2}\lambda_{3}}\int_{0}^{\infty}\int_{x}^{\infty}\int_{y}^{\infty}e^{-\lambda_{1}x-\lambda_{2}y-\lambda_{3}z}dzdydx}$$
Note that the denominator equals $P(X_1<X_2<X_3)$.


Eisenstein series with character

Question: I am currently following this course http://www.few.vu.nl/~sdn249/modularforms16/ from the University of Utrecht, and I am trying to solve problem 5.(a) from the 6th Homework Sheet.
Let $\chi$ be a primitive Dirichlet character modulo $N$, and let $\zeta$ be a $N$-th root of unity in $\mathbf{C}$. I am asked to show that
$$\sum_{j=0}^{N-1}\chi(j)\frac{x+\zeta^j}{x-\zeta^j}=\frac{2N}{\tau(\overline{\chi})(x^N-1)}\sum_{m=0}^{N-1}\overline{\chi}(m)x^m\in\mathbf{C}[[x]].$$
As a hint, it says "compute the residues".
I am guessing it's because my Complex Analysis skills are quite rusty at this point, but I really don't see how to start proving this. Any ideas?
Answer: The LHS is
$$F(x)=\sum_{j=0}^{N-1}\chi(j)\frac{2\zeta^j}{x-\zeta^j}$$
so equals $g(x)/(x^n-1)$ where $g$ is a polynomial of degree $\le nN-1$.
This polynomial will be characterised by
$$2\chi(j)\zeta^j=\lim_{x\to0}\frac{(x-\zeta^j)f(x)}{x^N-1}
=\frac{\zeta f(\zeta^j)}N.$$
Putting $\zeta^j$ into $f(x)=\sum\overline{\chi}(m)x^m$
will give you something that's basically a Gauss sum.

Eisenstein series with character


Prove using Comparison test

Question: Suppose $\sum b_n$ and $\sum a_n$ are series with positive terms and $\sum b_n$ is convergent. Prove that if $\lim_{n \to \infty }\frac{a_n}{b_n}$=0, $a_n$ is also convergent.
Proof at level of Single variable Calc, please.
Comment: Then you can't get the limit of the ratio to be $0$.
Comment: Intuitively the given limit tells you that the $a_n$'s are smaller than then $b_n$'s. This is enough for convergence of the series. **Edit:** You can even drop the hypothesis that $a_n>0$.
Comment: I don't think we can drop the hypothesis, as a_n could go to negative infinity?
Answer: If $\sum b_n$ is convergent, it means $b_n \to 0$, i.e. $\frac{1}{b_n} \to
\infty$. But we know that $\frac{a_n}{b_n} \to 0$, hence $a_n$ is an infinitesimal of higher order, hence $a_n < b_n \ \forall n >N$, hence $\sum_n a_n$ converges. One example would be $b_n = \frac{1}{n^2}$ and $a_n = e^{-n}$

Prove using Comparison test


Leading vs line-height

Question: Estou com o seguinte problema na conversão de um layout, eu tenho uma lista de nomes que possui a seguinte propriedade (na imagem abaixo):

Encontrei algumas fórmulas como essa
Line-height = Font-size + Leading/2, porém na hora de determinar o line-height no css, a distância não fica como está no layout desenhado no meu caso, no Illustrator.
Segue uma imagem que achei útil no entendimento:

Outra dúvida seria onde aplicar o line-height, no caso de uma lista de nomes, eu aplicaria no ul, no li ou no a?
Diferenças:
Comment: Você já deu uma olhada na parte de importação de css do Illustrator? Talvez você nem precise quebrar a cabeça para encontrar o line-height...
Comment: Já testou o espaçamento com paddings ou margins? Geralmente se aplica o line-height no elemento que contenha texto, no caso o link.
Comment: @GuilhermeLopes, setei tudo 0 mesmo, é que o cliente exige o "pixel perfect", então to tentando acertar o line-height
Answer: Em sua última dúvida creio as diferenças na aplicação do line-height vão depender muito do restante de seu layout. Veja esse exemplo:

ul#lista1{
  line-height: 40px;
}
ul#lista2 li{
  line-height: 40px;
}

Nomes

Nomes

Nomes

Nomes

Nomes

Nomes

Você pode perceber que não há diferenças em relação a sua aplicação. E isso repete inclusive quando há quebra de linha.
Já, quando aocrio que não seja necessário aplicação nele, caso ele esteja no modela acima, dentro do li. Caso esteja fora, já poderíamos considerar essa atribuição.
Quando quero centralizar um texto verticalmente, (quando usado o line-height), atribuo a este um valor igual a altura do elemento pai.
Outra fórmula que achei é, quando não temos noção do tamanho do elemento, usamos isto:

Isso mesmo! Multiplica-se o font-size pelo número de ouro, o phi.
Em alguns teste funcionou perfeitamente:

ul,li{
  margin: 5px 0;
  padding: 0;
}
ul#lista1{
  line-height: 40px;
}
ul#lista2 li{
  font-size: 20px;
  line-height: 32.36px;
  background: gold
}

Nomes

Nomes

Nomes

Nomes

Nomes

Nomes

Nomes

No caso da segunda lista, o li recebeu um line-height: 32.36px (20 * 1.618, aproximadamente). E ficou perfeitamente centralizado. Mas este é um caso muito específico, usado para uma boa leiturabilidade, acrescentei porque achei bem interessante.
Pode-se também utilizar margens e paddings, mas como optou por um reset...
Comumente, o CSS usa o que é conhecido como half-leading para setar linhas de texto. Isto é determinado, trabalhando-se a diferença entre o line-height e o font-size, dividindo-se por 2, e, em seguida, colocar a quantidade calculada de espaço acima e abaixo de cada linha de texto. Então, se você tem um font-size de 16px e um line-height de 24px, o half-leading perfeito seria de 4px. Aqui está o processo:
24px − 16px = 8px

8px ÷ 2 = 4px

O exemplo acima é uma visão ampla da sua fórmula.
Esse fiddle mostra a utilização da unidade em. A qual explico um pouco aqui.
Mas, novamente, isso é tudo muito relativo, só espero que tenha ajudado. E concordo com o Gilherme Lopes, dê uma olhada nas exportações de css do Illustrator, pode realmente te ajudar.
Fonte

Leading vs line-height


Unable to find .git folder in my repository

Question: I am creating my first local Git repository in my computer. Here in the Git terminal it is showing (Initialized empty Git repository in C:/Users/iliyas/Desktop/Tuna/.git/) but I am unable to see .git folder in my Tuna folder which I have created.
My Tuna folder is showing empty.
Comment: Hi .git folder will be hidden , Enable the setting to show hidden folder to view the .git folder inside your directory
Answer: .git folder is a hidden folder. Change your folder properties to show hidden files and folders. It would show.
Comment: You can upvote or accept the answer to show appreciation ;)
Answer: From the version git 2.9, the  .git folder remains hidden by default for a purpose. if you can pull or push the data from/to the repo then it means you already have .git in the folder.
If you really want to view it as physical file then you need to enable  hidden and system files and folders in Windows Explorer.


Atualizar dados aplicativo Android

Question: Ainda não tenho o projeto em execução, mas estou desenvolvendo um app que mostre o cardápio de um restaurante universitario. A parte que estou em duvidas é a atualização do cardapio semanalmente.
Ja usei FTP para atualizar um arquivo txt no Android, e pensei em montar um cardapio em um arquivo txt, salvar em um servidor FTP e o app se comunicar com esse servidor e realizar o download do arquivo TXT.
O app tem 5 botões ratio (um para cada semana). No caso pensei em 5 arquivos contendo o cardapio de cada dia, baixo esses arquivos e mostro em um textrView por dia da semana.
Funcionaria? E teria algum jeito mais simples?
Comment: Olá Gustavo Rotondo, bem vindo ao [pt.so]. Percebi que teve várias perguntas fechadas recentemente. Sugiro que para aumentar suas chances de conseguir uma boa resposta leia o guia [ask] e faça um [tour].
Answer: Funcionaria sim, esse aí parece o mais simples e não o mais correto.
O mais correto seria usar um servidor WEB pode ser WCF C# ASP.NET ou algum outro.
E esse servidor WCF pegaria de um banco de dados.
http://www.mobiltec.com.br/blog/index.php/tutorial-de-android-requisicao-de-servicos-de-um-servidor-wcf-parte-1/
Esse modo que falei é um pouco mais "caro e demorado" de se fazer, porém é o mais correto.
De qualquer modo, o que você falou em fazer funcionaria sim.

Atualizar dados aplicativo Android


DataFrame to HDFS in spark scala

Question: I have a spark data frame of the format org.apache.spark.sql.DataFrame = [user_key: string, field1: string]. When I use saveAsTextFile to save the file in hdfs results look like [12345,xxxxx]. I don't want the opening and closing bracket written to output file. if i used .rdd to convert into a RDD still the brackets are present in the RDD.
Thanks
Answer: Just concatenate the values and store strings:
import org.apache.spark.sql.functions.{concat_ws, col}
import org.apache.spark.sql.Row

val expr = concat_ws(",", df.columns.map(col): _*)
df.select(expr).map(_.getString(0)).saveAsTextFile("some_path")

Or even better use spark-csv:
selectedData.write
  .format("com.databricks.spark.csv")
  .option("header", "false")
  .save("some_path")

Another approach is to simply map:
df.rdd.map(_.toSeq.map(_.toString).mkString(","))

and save afterwards.
Comment: Thanks for response. In production we have version 1.4.2 and concat_ws is  not part of this version. But I was able to select the two columns and only one column is accessible. When I use map(p=>p(0),p(1)) get an error. Thanks

DataFrame to HDFS in spark scala


Commerce ogone running on ogone page but not in drupal side

Question: I installed the commerce_ogone module on Drupal 7 with Drupal commerce modules in local environment.
First shop, first case :

I set my payment method to my test account (PSID, sha in, sha out). When I chose Ogone in the cart I was redirected to ogone page. I set test credit card number and I validated.
At this moment, Ogone told me that "Your payment is authorized". Next I was redirected to the review page of the Drupal cart. On this page I have the message "Payment failed at the payment server. Please review your information and try again." but there is nothing in Drupal log.
I also received an email from ingenico test with my order but I can see that sentence : "This transaction must be confirmed manually in the administration module to generate a payment."

But I don't know how and why I need to confirm manually ?
Second shop, second case :

Same as above.
Same as above but there is the following message in error log : "SHA signature doesn't match feedback".
Ogone told me by email that there is a problem with the http request. The error is "Error in HTTP response - http result = -1" but there is nothing about this error inside the list of all error code of Ogone.

Any idea ?
Answer: The problem was in the list of parameters that are used in sha1 in the function commerce_ogone_sha1_out_parameters. I found a patch in this issue https://www.drupal.org/node/2736531 and it solved the problem.
diff --git a/commerce_ogone.sha1.inc b/commerce_ogone.sha1.inc
index dbf7096..9ee45f1 100644
--- a/commerce_ogone.sha1.inc
+++ b/commerce_ogone.sha1.inc
@@ -31,13 +31,16 @@ function commerce_ogone_feedback_valid_sha1($feedback, $sha1out) {
  *   SHA1-OUT security hash.
  */
 function commerce_ogone_sha1_out_parameters() {
-  return array('AAVADDRESS', 'AAVCHECK', 'AAVZIP', 'ACCEPTANCE', 'ALIAS', 'AMOUNT',
-    'BIN', 'BRAND', 'CARDNO', 'CCCTY', 'CN', 'COMPLUS', 'CREATION_STATUS', 'CURRENCY',
-    'CVC', 'CVCCHECK', 'DCC_COMMPERCENTAGE', 'DCC_CONVAMOUNT', 'DCC_CONVCCY',
-    'DCC_EXCHRATE', 'DCC_EXCHRATESOURCE', 'DCC_EXCHRATETS', 'DCC_INDICATOR',
-    'DCC_MARGINPERCENTAGE', 'DCC_VALIDHOURS', 'DIGESTCARDNO', 'ECI', 'ED',
-    'ENCCARDNO', 'IP', 'IPCTY', 'NBREMAILUSAGE', 'NBRIPUSAGE',
-    'NBRIPUSAGE_ALLTX', 'NBRUSAGE', 'NCERROR', 'NCERRORCARDNO', 'NCERRORCN',
-    'NCERRORCVC', 'NCERRORED', 'ORDERID', 'PAYID', 'PM', 'SCO_CATEGORY',
-    'SCORING', 'STATUS', 'SUBBRAND', 'SUBSCRIPTION_ID', 'TRXDATE', 'VC');
+  return array('AAVADDRESS', 'AAVCHECK', 'AAVMAIL', 'AAVNAME', 'AAVPHONE',
+    'AAVZIP', 'ACCEPTANCE', 'ALIAS', 'AMOUNT', 'BIC', 'BIN', 'BRAND', 'CARDNO',
+    'CCCTY', 'CN', 'COLLECTOR_BIC', 'COLLECTOR_IBAN', 'COMPLUS',
+    'CREATION_STATUS', 'CREDITDEBIT', 'CURRENCY', 'CVCCHECK',
+    'DCC_COMMPERCENTAGE', 'DCC_CONVAMOUNT', 'DCC_CONVCCY', 'DCC_EXCHRATE',
+    'DCC_EXCHRATESOURCE', 'DCC_EXCHRATETS', 'DCC_INDICATOR',
+    'DCC_MARGINPERCENTAGE', 'DCC_VALIDHOURS', 'DEVICEID', 'DIGESTCARDNO', 'ECI',
+    'ED', 'EMAIL', 'ENCCARDNO', 'FXAMOUNT', 'FXCURRENCY', 'IP', 'IPCTY',
+    'MANDATEID', 'MOBILEMODE', 'NBREMAILUSAGE', 'NBRIPUSAGE',
+    'NBRIPUSAGE_ALLTX', 'NBRUSAGE', 'NCERROR', 'ORDERID', 'PAYID', 'PAYIDSUB',
+    'PAYMENT_REFERENCE', 'PM', 'SCO_CATEGORY', 'SCORING', 'SEQUENCETYPE',
+    'SIGNDATE', 'STATUS', 'SUBBRAND', 'SUBSCRIPTION_ID', 'TRXDATE', 'VC');
 }


APC install fails due to Missing Dependency?

Question: I'm trying to run the following on a CentOS Linux 5.5 (w/ PHP 5.2.10):
yum install php-pear php-devel httpd-devel
but it fails with this:
php-devel-5.1.6-27.el5_5.3.i386 from updates has depsolving problems
  --> Missing Dependency: php = 5.1.6-27.el5_5.3 is needed by package php-devel-5.1.6-27.el5_5.3.i386 (updates)
php-devel-5.1.6-27.el5_5.3.i386 from updates has depsolving problems
  --> Missing Dependency: php = 5.1.6-27.el5_5.3 is needed by package php-devel-5.1.6-27.el5_5.3.i386 (updates)
Error: Missing Dependency: php = 5.1.6-27.el5_5.3 is needed by package php-devel-5.1.6-27.el5_5.3.i386 (updates)
Any ideas? I cannot find anything on Google which would point me to the right location.
Cheers,
Answer: You need to install the version of php-devel that matches the version of php already installed on the system. Try looking where you originally acquired it from.
Comment: Cheers. Can you please point me in the right direction?
Comment: Nope. I have no clue where you got your current `php` package from. Try checking the output of `rpm -qi php` for clues.
Comment: My provider solved it for me. Here's the solution: yum --enablerepo  install php-pear httpd-devel php-devel


Views Filters Populate + Autocomplete

Question: I want to search in one text field on 2 values. I'm using the Views Filters Populare module for this. This works perfectly. But how can I have an autocomplete on this one text field and show both the fields that are searched for?
This is what I have now in my View:
Answer: with the same views you can use filters in global variables and this module https://www.drupal.org/project/views_autocomplete_filters you can make this

Views Filters Populate + Autocomplete


Escaping quotes: `grep -w "label for=\"id_query"` does not work

Question: I want to match the exact string label for="id_query in a file in the current directory.
However, grep -w "label for=\"id_query" . does not match. Any idea how I can successfully escape that double quote?
Answer: Just use single quotes instead.
grep -w 'label for="id_query'


Using Variable in Remove-Item returns "A drive with the name '"E' does not exist"

Question: I have been writing a script which searches for specific folders within an "Archive" folder and then zips them. Once the folder is successfully zipped I would like it to be deleted.
However, I am running into an issue where the Remove-Item cmdlet is returning the error "A drive with the name '"E' does not exist" when I use the foreach command and a variable.
If I run the Remove-Item command manually with the variable the issue does not occur.
Please let me know why this is happening and what I can do to stop it from happening.
Here is the code:
# Get list of archive folders
$ArchiveFolders = Get-ChildItem \*\*\* |
                  ?{ $_.PSIsContainer } |
                  Where-Object{ $_.Name -eq "_Archived"} | select FullName

# For each archive folder check which subfolders exist within it
foreach ($folder in $ArchiveFolders) {
  (Get-ChildItem $folder.FullName | ?{ $_.PSIsContainer } | select FullName | ConvertTo-Csv -NoTypeInformation) |
    Select-Object -Skip 1 |
    Add-Content -Path e:\scripts\subfolders.csv
}

# Get list of Subfolders
$ArchiveSubFolders = Get-Content e:\scripts\subfolders.csv

# Select each Subfolder
foreach ($subfolder in $ArchiveSubFolders){
  # Move each subfolder to a 7z Archive with the highest compression rate available
  $pinfo = New-Object System.Diagnostics.ProcessStartInfo
  $pinfo.FileName = "7z.exe"
  $pinfo.RedirectStandardError = $true
  $pinfo.RedirectStandardOutput = $true
  $pinfo.UseShellExecute = $false
  $pinfo.Arguments = "a -mx=9 -t7z $subfolder.7z $subfolder"
  $p = New-Object System.Diagnostics.Process
  $p.StartInfo = $pinfo
  $p.Start() | Out-Null
  $p.WaitForExit()

  # Check Archive was created successfully and then delete the subfolder
  if ($p.ExitCode -eq "0") {
    Remove-Item -Path $subfolder -Force -Recurse
  } else {
    Write-Host "$subfolder has not been deleted"
  }
}

Comment: Works as expected, I just had to change the 7z.exe path to literalpath and
`Remove-Item -Path $subfolder -Force -Confirm:$false -Recurse -ErrorAction SilentlyContinue`
Comment: @HiteshDhruna Please pay attention to the `ConvertTo-Csv` part in the OP's code.
Answer: PowerShell CSV export/conversion adds double quotes around the fields. Since you read that CSV output via Get-Content the double quotes are preserved on import, so you get paths "E:\foo" instead of E:\foo. This might work for constructing the external command, but it does not work for PowerShell cmdlets, because there is no drive "E: (with a leading double quote). It's usually a bad idea to make quotes part of the value. You're better off leaving the values without qoutes and adding quotes where they're required.
$ArchiveSubFolders = foreach ($folder in $ArchiveFolders) {
  Get-ChildItem $folder.FullName |
    Where-Object { $_.PSIsContainer } |
    Select-Object -Expand FullName
}

With that said, you don't even need most of your code. You can get the subfolders you want by changing your original path expression to \*\*\*\_Archived\* and run a single Get-ChildItem with that. I'd also recommend dropping the System.Diagnostics.Process approach and use the call operator (&) instead.
Get-ChildItem '\*\*\*\_Archived\*' | Where-Object {
  $_.PSIsContainer
} | Select-Object -Expand FullName | ForEach-Object {
  & 7z.exe a -mx=9 -t7z "$_.7z" "$_"
  if ($LastExitCode -eq 0) {
    Remove-Item -Path $_ -Force -Recurse
  } else {
    Write-Host "$subfolder has not been deleted"
  }
}

Comment: The next part is to move this file to another folder which is stored on cheaper storage. I've tried the below but I'm getting an error "the path is not supported." Can you assist further?

`if ($LastExitCode -eq 0) {
    $folder = (get-item $_).parent.parent.Name
    if (Test-Path "e:\archived\$folder") {
      move-item -path "$_.7z" -Destination "e:\archived\$folder\$_.7z"
  } else {
      new-item "e:\archived\$folder" -type directory
      move-item -path "$_.7z" -Destination "e:\archived\$folder\$_.7z" }
      Remove-Item -Path $_ -Force -Recurse
  } else {}
} `
Comment: @AndrewBeaumont Please do not move the target. If you have a new question: post a new question.
Comment: apologies will do that now


Shallow copy equivalent for a vector in Rust

Question: I am trying to implement an algorithm which requires the use of a second mutable vector (elements are read only) containing a subset of elements of the first vector. That subset is of different order and will be reduced gradually, so slicing is not an option.
Basically I would require a shallow copy of the vector which I can mutate.
The original vector is passed to a function. Neither the original vector nor its elements are mutated. Single threaded.
The orinal vector is points: Vec<Point>, which is ideally passed as &points to the function.
Performance is of the utmost importance.
These solution concepts come to my mind:

new Vector with cloned elements: Vec<Point>
I can create a Vec with all points cloned and use that.
Penalty: High memory usage, time to deep copy all vectors. I also need to maintain a reference to the original point.
Algoritm runtime penalty: 0%

new Vector with reference to original element: Vec<&Point>
I can create a Vec<&Point> and use that.
Penalty: low memory usage, time to copy the references into a new vector
Also: need to provide each sub-function twice: one for &[Point] and one for &[&Point]
Algoritm runtime penalty: 25% (probably because reference now need two deref)

Using Rc for each Point
This requires original function to pass a vector points: Vec<Rc<Point>>.
Penalty: low memory usage, time to create the Rc Vector
Algoritm runtime penalty: 250% (my test function does not even create a second reference, this is just reading the original one)
Also: I have not found a way to create this inside the function without cloning each Point (Rc::new(point.clone()). As such, this does not make any sense, since I can work with a cloned vector much faster.

duration convex_hull                     n = 10000000: 579479 microseconds
duration convex_hull_ref                 n = 10000000: 726892 microseconds
duration convex_hull_ref with prepare    n = 10000000: 781806 microseconds
duration convex_hull_clone               n = 10000000: 576411 microseconds
duration convex_hull_clone with prepare  n = 10000000: 720428 microseconds
duration convex_hull_rc                  n = 10000000: 1402774 microseconds

Interpretation:

Cloning takes longer than creating of a reference vector, but the algorithm runtime is faster on clone, so clone is faster in total.
Rc is a nice concept but the algorithm runtime almost triples (prep time to create the RC vector outside the function and not shown here), so out of the question.

Question: Is there another possibility which I do not see, with or without unsafe rust?
A plain shallow copy which does not move would be ideal for this case. Since I am dropping the shallow copy when the function is left, there would be no dangling pointers. Maybe I am missing another risk.
Relevant pieces of code
pub trait PointLike {
    fn get_id(&self) -> usize;
    fn get_x(&self) -> isize;
    fn get_y(&self) -> isize;
}

fn main() {
    // Random
    let points = random_points(NUM_POINTS, RANDOM_MIN, RANDOM_MAX);
    let _dummy = convex_hull(&points);
    let _dummy = convex_hull_ref(&points);
    let _dummy = convex_hull_clone(&points);

    let mut points_rc = Vec::new();
    for point in &points {
        points_rc.push(Rc::new(point.clone()));
    }
    let _dummy = convex_hull_rc(&points_rc);
}

// this function is implemented multiple times, only change is the used vector type
fn convex_hull<T: PointLike>(points: &[T]) -> Vec<&T> {
    assert!(points.len() >= 50);
    let start = Instant::now();

    let n = points.len();
    let h = 50;
    let step = n / h;
    let mut convex_hull: Vec<&T> = Vec::with_capacity(step);

    // emulate gift wrapping to get some time to measure
    let mut search_id = step;
    for _ in 0..h {
        let mut ch_idx = 0;
        for i in 0..n {
            if points[i].get_id() == search_id {
                ch_idx = i;
            }
        }
        convex_hull.push(&points[ch_idx]);
        search_id += step;
    }

    let duration_micro = start.elapsed().as_micros();
    println!(
        "  duration convex_hull                    for n = {}, convex hull size = {}: {} microseconds",
        points.len(),
        convex_hull.len(),
        duration_micro,
    );

    convex_hull
}

Comment: Is `Point` `Copy`?
Comment: Assume it is, in one version it contains only Id: usize, x, y: isize or f64.
It would be interesting to see if this would make a different solution possible.
On the other more generic version it may contain anything, as long trait PointLike is satisfied. So most likely no copy.
Comment: I asked because if it is, "deep-copy the vectors" is actually pretty cheap (one allocation + memcpy). I doubt you can go faster in the conditions you described. Note however that there may be additional assumptions about the algorithm that we don't know, that can make a more efficient solution.
Answer:
Basically I would require a shallow copy of the vector which I can mutate.

This makes me think about copy-on-write.
I'm not certain this is what you are looking for, but in case it is, here is an example.
The whole set of points stored inside the original vector is not duplicated in the (shallow) copy as long as we just read these points.
But as soon as we need to mutate some of these points in the copy, or to reorder this storage, a new storage is required in order to keep the original points unchanged.
Note that, because all the points are contiguously stored in a dynamic array, we cannot only clone+mutate one point, leaving the others untouched.
For this we would need a vector of pointers to point, but this implies one more indirection at each access (and probably memory fragmentation).
#[derive(Debug, Clone, PartialEq)]
struct Point {
    x: isize,
    y: isize,
}

fn main() {
    let original: Vec<_> =
        (1..=10).map(|i| Point { x: i, y: 10 * i }).collect();
    let mut copy = std::borrow::Cow::from(&original);
    println!(
        "before mutation, same content? ~~> {}",
        original.iter().eq(copy.iter())
    );
    println!(
        "before mutation, same storage? ~~> {}",
        std::ptr::eq(&original[0], &copy[0])
    );
    let half_size = copy.len() / 2;
    copy.to_mut().truncate(half_size);
    println!(
        "after mutation, same content? ~~> {}",
        original.iter().eq(copy.iter())
    );
    println!(
        "after mutation, same storage? ~~> {}",
        std::ptr::eq(&original[0], &copy[0])
    );
}
/*
before mutation, same content? ~~> true
before mutation, same storage? ~~> true
after mutation, same content? ~~> false
after mutation, same storage? ~~> false
*/

Comment: Thanks for taking the time. But I am not sure it solves my issue. I need a vector which I can reorder and remove elements, e.g. vec.truncate(half_size). Looking at Cow, I believe it serves as a fixed container allowing to mutate elements, which then are cloned. I don't need to mutate the elements. Basically I would like to rotate the pointers on the stack (vector pointers) pointing to the elements on the heap (vector content).
Comment: @GunnarBernstein No, with Cow, the vector as a whole can be mutated, not only the elements it contains. The actual copy happens at the first `.to_mut()` call. I changed the example accordingly.
Comment: Great! I was missing to_mut() on an already mut object. Very fast, no extra cost apparently.


Export mailbox on user deletion with Exchange Scripting Agent

Question: I'm attempting to automate a few processes with the Exchange 2010 Scripting Agent, I want to disable several mailbox functions on creation (which works just fine) and automatically export a mailbox on remove request.
<?xml version="1.0" encoding="utf-8" ?>
<Configuration version="1.0">
 <Feature Name="MailboxProvisioning" Cmdlets="new-mailbox">
  <ApiCall Name="OnComplete">
   if($succeeded)    {
    $newmailbox = $provisioningHandler.UserSpecifiedParameters["Name"]
    set-casmailbox $newmailbox -OWAEnabled:$false -ActiveSyncEnabled:$false -ImapEnabled:$false -PopEnabled:$false
   }
  </ApiCall>
 </Feature>

^ This all works
But the second section I'm wondering what ApiCall I need to use to run a command BEFORE the remove-mailbox command processed.
<Feature Name="MailboxProvisioning" Cmdlets="remove-mailbox">
  <ApiCall Name="??????">
   if($succeeded)    {
    $removedmailbox = $provisioningHandler.UserSpecifiedParameters["Name"]
    New-MailboxExportRequest -Mailbox $removedmailbox -FilePath \\exchsrv\PSTFiles
   }
  </ApiCall>
 </Feature>
</Configuration>

Any help would be greatly appreciated!
Answer: The correct ApiCall would be 'validate'. This triggers an event after Exchange determines the used cmdlet is a valid command and has all of the info it needs. After validation succeeded but before the cmdlet is run, the scripting agent is set to work :)


A space where no paths are homotopic

Question: I was just thinking about algebraic topology and was wondering: It is possible to find a Hausdorff space where no paths are homotopic?
Excluding trivial examples.
Comment: What examples do you consider trivial?
Comment: I was thinking this would hold for the totally disconnected spaces, where the only paths would be staying at the singleton points. So trivial in the sense that we are looking at the discrete topology.
Comment: But totally disconnected does not imply discrete, so I am not sure what you mean
Comment: I understand that, but discrete implies totally disconnected, I suppose we can just discuss any examples.
Answer: The answer is no. I presume by excluding trivial examples you are asking for a space $X$ with two distinct points $x,y$ such that there is a path $\gamma$ from $x$ to $y$ (note that $x,y$ being distinct is not so important, if there is a nonconstant loop at $x$ automatically this is true by just picking $y$ to be the midpoint). Given any such space, there is a homotopy of paths from the constant loop at $x$ to $\gamma^{-1} \circ \gamma$. Clearly these paths are unequal, since their images are different.

A space where no paths are homotopic


Adjoint operator and inner product

Question: Let $C\left( a,b \right)$ be the space of differentiable functions on the interval $\left[ a,b \right]$. Let $B(f,g)=\int_{a}^{b}f(t)g(t)w(t)dt$ be a scalar product over $C\left( a,b \right)$, with $w(t)>0$ for all $t\in\left[ a,b \right]$. For p and q fixed functions in $\left[ a,b \right]$ define $$T(f)=\frac{{(p{f}')}'+qf}{w}$$ Show that T is a adjoint operator.
My attemp:
If T is a adjoint operator, T should satisfy $B(T(f),g)=B(f,T^{*}(g))=B(f,T(g)$), i.e.
$$\int_{a}^{b}\left[{(p{f}')}'g+qfg \right]dt=\int_{a}^{b}\left[{(p{g}')}'f+qfg \right]dt$$ I used integration by parts, but it do not helped me. Can you give me a hint? Thanks.
Comment: Integration by parts should work. Don't you have some kind of conditions on $p,q$ or $f,g$ at the endpoints $a,b$?
Comment: There is no condition
Comment: The problem is wrong without such a condition.
Answer: By parts gives
$$ \int_a^b (pf')'g\,\mathrm{d}x \quad = \quad \big[(pf')g\big]_a^b-\int_a^b pf'g'\,\mathrm{d}x $$
and
$$ \int_a^b (pg')'f\,\mathrm{d}x \quad = \quad \big[(pg')f\big]_a^b -\int_a^b pg'f'\mathrm{d}x $$
These should be equal as long as the evaluated terms (in brackets) are zero. I assume this follows from a condition given in the problem (either $f,g$ or $p,q$ ought to vanish at $a,b$).

Adjoint operator and inner product


rJava library not working. Unable to find jvm.dll

Question: I realize this question has been asked before but none of the solutions worked for me.
After a 'successful' install of rJava I try library(rJava) I receive an error that R cannot find jvm.dll. Here are the solutions I've tried:

Setting my PATH to include a direct link to the jvm.dll directory. Also tried one level up
Clearing the JAVA_HOME environmental variable. Also setting JAVA_HOME to the directory of my jvm.dll
Direct install from rforge.net using install.packages('rJava', .libPaths()[1], 'http://www.rforge.net/'). I receive this error:
Find Java...
ERROR: cannot find Java Development Kit.
       Please set JAVA_HOME to specify its location manually
Attempted setting the path of JAVA_HOME using this command: options(java.home="C:\\Program Files (x86)\\Java\\jre1.8.0_121\\bin\\client")

Other potentially useful information:

Going into cmd and running echo %JAVA_HOME% shows the correct directory
I restarted RStudio after every attempt
Running on Windows 7 64 bit.

Any ideas would be greatly appreciated. Getting really frustrated trying to get this library working as it's needed for the xlsx library.
SOLUTION:
Egg on my face, the issue was that I accidentally pointed to environmental variable to an old 32 bit install of Java that I must have accidentally installed at some point in the last few years (thank you @user20650). Pointing everything back at the 64 bit version fixed things. For the record I did have to set JAVA_HOME to point to the correct directory. Also, make sure you have both the java JRE and JDK.
Comment: If you are usnig x64 R, then try installing x64 bit java https://www.java.com/en/download/manual.jsp, as you seem to be setting path for x32
Comment: ps some non jave alts: http://stackoverflow.com/questions/29186040/convert-a-csv-to-excel-without-using-xlsx-package
Answer: Egg on my face, the issue was that I accidentally pointed to environmental variable to an old 32 bit install of Java that I must have accidentally installed at some point in the last few years (thank you @user20650). Pointing everything back at the 64 bit version (ie C:\Program Files\Java\jdk1.8.0_121) fixed things after running install.packages('rJava', .libPaths()[1], 'http://www.rforge.net/').
For the record I did have to set JAVA_HOME to point to the correct directory. Also, make sure you have both the java JRE and JDK. Also, for some reason my anti-virus did not like letting that rforge install go through (didnt like the findjava.exe), so I had to pause it for a moment.


Reroute a specific domain to another server IP

Question: I have a server that gets all requests from 3 different domain names.
I would like to reroute two of the domain in another local IP.
Actually I have :

abc.com => my_server
subdomain.abc.com => my_server
subdomain2.abc.com => my_server

And I would like to get :

abc.com => my_server
subdomain.abc.com:* => my_server => 192.168.0.70:*
subdomain2.abc.com:* => my_server => 192.168.0.72:*

But I don't know how to do that, any idea, software/script name on debian ?
Thanks !
Comment: What is goal ? who or what will trigger inside 192.168.0.70 or 192.168.0.72 ?
Comment: The goal is to reroute all requests from a subdomain to another web server (ports 80 and 443). I can do that with port routing ::80 to 192.168.0.70, and ::81 to 192.168.0.72. But need a transparent reroute for users.
Comment: check my answer bellow, is what you ask
Answer: You can use proxy for what you expect and multiply configuration to manage all port needed. Following config will proxy all request for:
subdomain.abc.com:80 => 192.168.0.70:80
<code>server {
    listen 80;
    server_name subdomain.abc.com;
    location / {
        proxy_pass http://192.168.0.70:80;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
</code>
Unfortunately according to the documentation port number can't be dynamic and should be hard coded on your configuration file.


Does being the player who kicked the ball, when the opponent scores an own goal, count as an assist?

Question: I'm seeing a lot of comments saying Messi gave an assist because an opposing Nantes player changed the direction of a ball kicked by Messi, and this action lead to a goal against Nantes. I've even heard this in the media.
I dont know if they are saying this sarcastically or does a situation like this counts as indeed an assist for Messi.
Does being the player who kicked the ball, when the opponent scores an own goal, count as an assist?
Comment: Comments and media where? None of the score and stats-tracking sites that I have checked give anything except *Appiah (o.g.)* for this event.
Comment: Ah, so comments from the general public, rather than credible reporters. I would as a matter of principle ignore what they say unless they can point to official competition regulations or endorsed statistics sources that allow an assistal for own goals; there are competitions which define assists as not possible with an o.g. and others which never define them at all (or not in public, anyway).
Comment: Here assist is with quotation marks, but I've seen in other media without them,  I can't find them now https://www.infobae.com/america/deportes/espn/2021/11/20/el-partido-de-messi-su-primer-gol-en-ligue-1-y-la-asistencia-para-el-tanto-mas-extrano-del-triunfo-de-psg/ . And comments in many youtube videos, you can see some here for example (one in English) https://www.youtube.com/watch?v=VCcLwU14C88
Answer: This will likely depend on which statistics organisation you ask - but the current de facto organisation for sporting stats is probably Opta.
According to Opta, an assist is not awarded when an own goal is scored. This is described in their Event Definitions:

Goal Assist
The final touch (pass, pass-cum-shot or any other touch) leading to the recipient of the ball scoring a goal. If the final touch (as defined in bold) is deflected by an opposition player, the initiator is only given a goal assist if the receiving player was likely to receive the ball without the deflection having taken place. Own goals, directly taken free kicks, direct corner goals and penalties do not get an assist awarded.

As an aside, it may be a point of discussion if the conversation is relating to fantasy football leagues. For example, in FPL (Fantasy Premier League) an assist is awarded if the shot (or pass to a would-be goalscorer) is deflected into the goal and an own goal is given. Though this may not be the case in other Fantasy leagues.
As a concrete example - during Chelsea's 7-0 win over Norwich in the 2021/22 season, Callum Hudson-Odoi was awarded (in FPL) an assist and the 2 fantasy points for the cross he made into the box, which was ultimately deflected into the goal and given as a Max Aarons own goal.


How to listen device events in ASP .net website (In real time)

Question: Is there any way by which I can listen to events fired by device (Speech mike, Kind of dicta phone) attached to client's computer in my ASP .net website?
I need to listen to real time events of device (Speech mike, Kind of Dictaphone) and the frequency of event firing is very high.
Thanks in advance
Comment: i think it's done by installing an activex control...i am not too sure about that...
Comment: Ok.. I will look into it.. if there is any possibility.
Comment: also, which events are you trying to listen to? some events only come to UI applications that have the message pump. For example, user login/log out, etc.
Comment: I am trying to listen to events fired by a speech mike(kind of Dictaphone) attached to client's computer.
Answer: No, asp.net runs on a remote webserver and there's no way it could listen to a client's HW events. You can't even access user's files and folders, because it would be a security risk.
Answer: Browsers do not have the native capability to listen to a device's custom events. Software would have to be loaded at the client side to report the events to a webservice.
Comment: I tried that approach also([link](http://stackoverflow.com/questions/12201877/call-a-function-event-or-pass-data-to-websitec-whenever-value-of-variable-cha)). But the problem is .. events are fired too frequently. And I have to respond in real time on my website. Thanks
Answer: You cannot listen to machine events from your web application because it runs on server. You should try some kind of plugin to do this job, like a Silverlight App for example!


Can Zod reshape and rename an incoming object?

Question: I am trying to validate and reshape the following object:
{ title: "My title", body: "My body", category: { id: 1, name: "My category" }
I would like to output the following shape after validation:
{ title: "My title", body: "My body", categoryId: 1 }
Here is my schema:
const ArticleSchema = z.object({
  title: z.string().min(5),
  body: z.string().min(5),
  category: z
    .object({
      id: z.number().int(),
      name: z.string(),
    })
    .transform((input) => input.id),
});

Zod's transform method can modify the shape of the value, but I would also like to modify the name of the key to be categoryId instead of category.
ArticleSchema.parse(data) outputs this:
{ title: "My title", body: "My body", category: 1 }
I also tried this:
const ArticleSchema = z.object({
  title: z.string().min(5),
  body: z.string().min(5),
  category: z
    .object({
      id: z.number().int(),
      name: z.string(),
    })
    .transform((input) => ({ categoryId: input.id }),
});

But it outputs this:
{ title: "My title", body: "My body", category: { categoryId: 1 } }
Is this possible?
Answer: This is possible, but it may lead to a good amount of duplication (if done in a naive way) since you cannot simply merge the values and add in the field you want without keeping the old field around.
What you are looking for can be achieved by moving the transform up a level to the outermost object. The categoryId key belongs to that object so that is the place you need to transform.
import { z } from "zod";
import { isEqual } from "lodash";

const input = { title: "My title", body: "My body", category: { id: 1, name: "My category" } };
const expected = { title: "My title", body: "My body", categoryId: 1 };

const schema = z.object({
  title: z.string().min(5),
  body: z.string().min(5),
  category: z.object({
    id: z.number().int(),
    name: z.string(),
  }),
}).transform((o) => ({
  title: o.title,
  body: o.body,
  categoryId: o.category.id,
}));

const parsed = schema.parse(input);

console.log(isEqual(parsed, expected)); // Logs true


Bug de Permissão no Serviço de Aplicativo do Azure

Question: Eu tenho um serviço de aplicativo na Azure rodando wordpress.
Certo dia, ao atualizar um plugin, este não só parou de funcionar como o painel Kudu não consegue visualizá-lo.
Observe:

Consigo listar dentro da pasta pelo console na parte de baixo da tela, entretanto o visualizador do Kudu não consegue visualizá-lo.
Tentei alterar através do chmod as permissões mas não altera nada. Já apaguei a pasta e copiei outra. Já renomeei incluindo outra e nada.
O que é peculiar é ao acessar essa pasta através do KUDU, aparece uma mensagem da Azure indicando que minha sessão está espirada, mas não está porque continuo utilizando o painel após clicar em OK. O usuário e o grupo aparecem como desconhecido pela linha de comando ls -l.

Se eu acessar pelo navegador, apontando até a url final, recebo a mensagem "You do not have permission to view this directory or page.".
Já abri um suporte na Microsoft mas até agora não houve retorno de solução.
Parece ser um erro de permissão no sistema de arquivos que a Microsoft utiliza no Serviço de Aplicativo.
Alguém mais já passou por isso e consegue fornecer um caminho para a luz?
Comment: Eu tenho um suporte aberto na Microsoft com o técnico dizendo: Reinstala! Não tenho como te ajudar porque não tenho acesso. É um jogo de empurra pra cá e empurra pra lá. Parece até brasileiro! Vamos lá, Kendrick, uma forcinha pra resolver, né?!
Answer: O suporte da Microsoft concluiu que existe um plugin que pode ser utilizado no Serviço de Aplicativo chamado Composer que não permite a palavra "vendor" e com isso, ocorre o erro.

Desabilitamos esta extensão e o site voltou a funcionar normalmente.
Espero que ajude.


DRBL without modifying the DHCP: Possible?

Question: Following up this question I'd like to ask:
I use the company's network, but I have no access to the DHCP.
I'd like to set up a DRBL server to be able to (re-)install
a Linux image any time I want to.
As far as I understand, the client starts in PXE and asks the DHCP
server where to find the DRBL server.
Can I still use the PXE+DRBL if I cannot modify the DHCP?
Answer: Yes you can but you have to replace the DHCP server included with DRBL (isc-dhcp-server) with dnsmasq.
Next dnsmasq should be configured as proxyDHCP. A proxyDHCP only provides the PXE related DHCP info to booting PXE clients (NBP and the IP of the TFTP hosting it) while the regular (untouchable) DHCP server will provide IP addresses and related info as usual.


Drupal 8, very simple hierarchical form doesn't work

Question: In a custom module, I create a new form. In the buildForm function, I define my form :
<code>$form["planet"] = array(
  '#type' => 'textfield',
  '#title' => '1 : '.$this->t('planet'),
  '#maxlength' => 64,
  '#size' => 64,
  '#tree' => TRUE,
);

$form["planet"][0] = array(
  '#type' => 'textfield',
  '#title' => '0 : '.$this->t('land'),
  '#maxlength' => 64,
  '#size' => 64,
);

$form["planet"][1] = array(
  '#type' => 'textfield',
  '#title' => '1 : '.$this->t('land'),
  '#maxlength' => 64,
  '#size' => 64,
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
);
</code>
There are 3 fields, but this is the result :

Why there only first field displayed ?
Comment: I am not certain you would be able to render a textfield within a textfield, ie `$form["planet"][0]` within `$form["planet"]`, what do you need to achieve with the 'hierarchical' aspect of the form?
Answer: You need change type $form["planet"] to fieldset or container. Don't use text field in this case:
<code>$form["planet"] = array(
  '#type' => 'fieldset',
  '#title' => '1 : '.$this->t('planet'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);
</code>


How to load JSON dynamic tree data in SmartGWT TreeGrid

Question: I have a JSON tree structure that is generated dinamically, this means the keys and the structure are unknown and it can change in every request, the only common property in every object are the oldValue and newValue keys...
the JSON looks like this:
{
"obj1":
    {"oldValue": "foo", "newValue": "foofoo"},
"obj2":
    {"obj2_1":
        {"oldValue": null, "newValue": "foo"}
    },
    {"obj2_2":
        {"obj2_2_1":
            {"oldValue": "foo", "newValue": "foofoo"}
        },
        {"obj2_2_2":
            {"oldValue": "foo1", "newValue": null}
        }
    }
}

How can I load this data in a TreeGrid dinamically? Is it possible to get to the deepest key using XPath?
Answer: I came to the conclusion that is just not possible with SmartGWT because of the fact that, in SmartGWT components that can handle hierarchical data, you need to specify a parent key as an attribute, wich is not very practical (IMHO)...
Now the solution: The best alternative to this is to use the GWT core widgets Tree and TreeItem, with TreeItem you can attach items dinamically, so I loaded the json data into a JSONObject and added the nodes recursively.
Below the tree nodes loading process:
private void loadTreeNodes(JSONObject jsonObject, TreeItem parent) {
    for (String key: jsonObject.keySet()) {
        JSONValue jsonValue = jsonObject.get(key);
        TreeItem item = new TreeItem("" + key + " ");
        parent.addItem(item);

        if (jsonValue != null) {
            if (jsonValue.isObject() != null) {
                loadTreeNodes(jsonValue.isObject(), item);
            } else if (jsonValue.isArray() != null) {

            } else {
                if ("oldValue".equals(key)) {
                    item.setHTML("before: " + jsonValue.toString());
                } else {
                    item.setHTML("after: " + jsonValue.toString());
                }
            }
        } else {
            item.setText("" + item.getText() + ": null");
        }
    }
}

I loaded the json data like this:
JavaScriptObject obj = JSON.decode(jsonData);
JSONObject jsonObject = new JSONObject(obj);

Any comments are welcome!


Import curses presents an error

Question: I've searched for hours but can't find anything that works so I figured I'd just ask directly. I've been trying to use curses but whatever I do it doesn't work. My code is-
import curses

from curses.wrapper import wrapper

def main(scr):
    scr.box()
    scr.refresh()
    c = scr.getch()

wrapper(main)

But the error I get is
Traceback (most recent call last):
  File "/Users/Desktop/Code/Code.py", line 3, in <module>
    from curses.wrapper import wrapper
ModuleNotFoundError: No module named 'curses.wrapper'

Can anyone help with this?
Comment: Another problem I have is that if I try to use 'from curses import wrapper', the shell can't find the terminal
Answer: The import doesn't work since you're attempting to treat the wrapper function as a class.  This works:
import curses

# from curses.wrapper import wrapper

def main(scr):
    scr.box()
    scr.refresh()
    c = scr.getch()

curses.wrapper(main)

and so does this:
import curses

from curses import wrapper

def main(scr):
    scr.box()
    scr.refresh()
    c = scr.getch()

wrapper(main)

Import curses presents an error


Can the Response Variable ever be used in Clustering?

Question: I have the following question: Can the response variable ever be used in a clustering algorithm?
I understand that in general, clustering is considered to be an "unsupervised learning algorithm" which is meant to be used when the response variable is not present. But in terms of statistical methodology, is there anything wrong with running a clustering algorithm (e.g. K-Means) on some data that has a response variable? In theory - could it even be considered more beneficial to run clustering on data that has a response variable, seeing as you now have more information about the data?
I illustrate this example below (using the R programming language). I generated the following data (where "age" is considered the response variable, and "height" and "weight" are the covariates):
set.seed(123)
height = rnorm(1000, 6,0.5)
weight = rnorm(1000, 200, 5)
age = rnorm(1000,30,1)
my_data1 = data.frame(height, weight, age)

height = rnorm(1000, 5.5,0.5)
weight = rnorm(1000, 150, 5)
age = rnorm(1000,20,1)
my_data2 = data.frame(height, weight, age)

final_data = rbind(my_data1, my_data2)

head(final_data)
    height   weight      age
1 5.719762 195.0210 29.48840
2 5.884911 194.8002 30.23694
3 6.779354 199.9101 29.45841
4 6.035254 199.3391 31.21923
5 6.064644 187.2533 30.17414
6 6.857532 205.2029 29.38473

Next, I run clustering algorithms with and without the response variable:
1) Without the Response Variable
library(ggplot2)

cls <- kmeans(x = final_data[, 1:2], centers = 2)

final_data$cluster = as.factor(cls$cluster)

ggplot() +
  geom_point(data = final_data,
             mapping = aes(x = height,
                                  y = weight,
                                  colour = cluster)) + ggtitle("Clustering Without the Response Variable")

2) Clustering With the Response Variable
library(plotly)
library(dplyr)

  cls <- kmeans(x = final_data, centers = 2)

    final_data$cluster = as.factor(cls$cluster)

fig <- plot_ly(final_data, x = ~height, y = ~weight, z = ~age, color = ~cluster, colors = c('#BF382A', '#0C4B8E'))
fig <- fig %>% add_markers()
fig <- fig %>% layout(scene = list(xaxis = list(title = 'Height'),
                     yaxis = list(title = 'Weight'),
                     zaxis = list(title = 'Age')))

fig %>% layout(title = 'Clustering With the Response Variable ')

Question: In this example, the clustering performed on the artificially generated data does not seem to be affected by using the response variable compared to omitting the response variable. But in general, if the response variable is available - is there anything fundamentally wrong with using the response variable in a clustering algorithm? Could there be any benefits, seeing as you have additional information at your disposal?
Thanks!
Comment: Cluster analysis, as itself, does not know anything about "response" and "predictory" variables. It is outside of this distinction. Therefore the question to include or not to include a response into a clustering is solved on a higher level, the level of the project. The main question here is whether the inclusion of response brings about a _contamination_  that is, adding of information that should be kept away for a while for the subsequent analysis.
Comment: that is a great point! thank you for your bringing this up!
Comment: @ttnphns - you might want to consider expanding that (mildly) into an answer...
Comment: Your code is the same for both cases except the plotting.
Answer: The first thing to mention is that the two clusters in your data are very easily separated. This makes it hard to notice differences between approaches to improve the separation between clusters.
You can run the code below and see that the clusters will differ when taking the third variable in consideration. C here is caused by A and B so you can literally consider it a response variable.
library(ggplot2)
set.seed(123)
a = rnorm(1000)
b = rnorm(1000)
c = a+b + rnorm(1000)
df = data.frame(a, b, c)

cls <- kmeans(x = df[, 1:2], centers = 2)
df$cluster = as.factor(cls$cluster)
ggplot() +
  geom_point(data = df,
             mapping = aes(x = a,
                           y = b,
                           colour = cluster)) + ggtitle("Clustering Without the Response Variable")
cls <- kmeans(x = df[, c('a', 'b', 'c')], centers = 2)
df$cluster = as.factor(cls$cluster)
ggplot() +
  geom_point(data = df,
             mapping = aes(x = a,
                           y = b,
                           colour = cluster)) + ggtitle("Clustering With the Response Variable")

I understand that in general, clustering is considered to be an "unsupervised learning algorithm" which is meant to be used when the response variable is not present. But in terms of statistical methodology, is there anything wrong with running a clustering algorithm (e.g. K-Means) on some data that has a response variable?

There is nothing really preventing you from using approaches more commonly used in supervised learning to unsupervised learning problems and vice-versa (or semi-supervised, and so on). People do this all the time. Sometimes it works well, sometimes it doesn't. Take Support Vector Machines (SVM), for example. People usually think of it as a way to do classification in supervised learning. However, some other people have been using it for regression. Some other people for clustering in unsupervised learning. Same thing for Neural Networks (supervised, semi-supervised, unsupervised, and so on).
As for including a variable that in a supervised learning context would be seen as a response variable, it's fine, as long as you don't run into data leakage, what @ttnphns mentioned (contamination). Let's say you're trying to identify fraudulent purchases. When a new putative fraudulent purchase comes for analysis, do you have for that purchase all the variables used  to separate the clusters before? If so, it's fine.


How to sample from different datasets such that they have similar distributions?

Question: I have data from multiple datasets with the boxplot given below

In the above figure, I have data from 7 different datasets. I am looking for a sampling strategy without replacement such that samples from each dataset have similar distribution (probably they have the same mean and standard deviation or some other sort of similarity). It should be fine if the strategy loses a number of data from multiple sites.
Comment: You could create a proxy distribution of those distributions and then sample randomly from all distribution based on the probability they belong to the proxy distribution.
Comment: Why not sample from the data? If your data for group 1 are $\{1,2,3,9,4,5,7,8,3,1\}$, then draw from the data with replacement to get a data set like $\{1,2,7,9,4,7,1\}$. You can have whatever sample size you want, either larger or smaller than the original data set.
Comment: I forgot to mention that the sampling strategy should sample without replacement.
Comment: Why without replacement?
Comment: Downstream analysis of the data requires that samples shouldn't be repetitive.
Comment: Just to clarify: Are these 7 datasets say $D_1, D_2, \dots, D_7$ measuring the same quantity? Are you expected to create 7 new datasets $D_1^*, D_2^*, \dots, D_7^*$ such that $\hat{\mu}_{D_1^*} = \hat{\mu}_{D_2^*} = \dots = \hat{\mu}_{D_7^*}$ and similarly $\hat{\sigma}_{D_1^*} = \dots = \hat{\sigma}_{D_7^*}$? Also by looking at these boxplots datasets 3,4 and 5 don't seem like they have a great overlap with datasets 1 and 6; the majority of the mass of the 7 new datasets has to be in the common support of the 7 original datasets by definition and that doesn't seem to be wide...
Comment: I suspect [rejection sampling](https://en.wikipedia.org/wiki/Rejection_sampling) is a potential avenue here but it will be messy.
Comment: They don't have to be exactly equal, some margin of error should be ok there. I looked at that, but yes would be messy.
Answer: Try covariate balancing, i.e. learn weights $w_i, u_j$ such that $\sum_{i} w_i X_i = \sum_j u_j Y_j$ and $\sum_{i} w_i X_i^2 = \sum_j u_j Y_j^2$ for two of the datasets $\{X_i\}$ and $\{Y_j\}$, then sample using propabilities proportional to the weight. This should balance the mean and the variance at least.
Comment: How do you propose to learn these weights?
Comment: @AryaMcCarthy That's a good question. I am thinking of trying least squares solvers. Suppose all weights for $u_i  = 1/n$ then try to learn $w$'s such that $w^{\top}X = \bar{Y}$ and $w^{\top}X = \bar{Y^2}$ using least squares?
Comment: I am applying the balancing score idea in causal inference to a non-causal problem here. This might be helpful: https://www.stat.cmu.edu/~ryantibs/journalclub/propensity.pdf
Comment: ... Not a totally bad proposition but given that the OP says "without replacement" it kind of kills the notion of using a weighted sample indirectly.
Comment: Well in that case, for each dataset we can generate a pseudo dataset where the proportion of each datapoint matches the probability induced by the weight. Now we have an urn with $N$ balls where there are $n_i$ of color $x_i$ with $w_i = n_i/N$. Then sample without replacement?


Can't assign IPv6 address to CentOS7 VM on Oracle Cloud

Question: I just can't get to assigning a public IPv6 address to my oracle instance running CentOS 7.
I have assigned IPv6 range to the subnet, and another VM running Ubuntu successfully gets the assigned IPv6.
Output of ifconfig :
ens3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9000
        inet 10.0.0.240  netmask 255.255.255.0  broadcast 10.0.0.255
        inet6 fe80::17ff:fe01:b1b2  prefixlen 64  scopeid 0x20<link>
        ether 02:00:17:01:b1:b2  txqueuelen 1000  (Ethernet)
        RX packets 1298  bytes 1235123 (1.1 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1207  bytes 810530 (791.5 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

Comment: Check your logs.
Comment: Which log exactly ?
Answer: I had the exact same issue. On Oracle Cloud you must assign a /128 IPv6 address to the VM and once this is done you can rely on dhclient to get it set up:
dhclient -6 ens3

Comment: The VM successfully picked up the IP, but not the default gateway. I still can't ping any IPv6 address through the VM ! Also, the IP is released on reboot. I am unable to make any changes to /etc/sysconfig/network-scripts/ifcfg-ens3 permanent. Please guide me further.
Answer:
Run systemctl disable rhel-import-state to prevent overwriting /etc/sysconfig/network-script/ifcfg-ens3
Add DHCPV6C=yes to ifcfg-ens3
In "Networking -> Virtual Cloud Networks -> <your vcn> -> Security List Details" add Ingress and Egress rules for IPv6. At least egress.
Reboot and enjoy
Comment: please update your answer as I believe he wants to have a static address
Comment: Doing the above, now I do get an IPv6 address on ens3, however there's no internet connectivity.

ping6 to any address fails with : network is unreachable.
Comment: Here's my ifcfg-ens3 contents :

NAME="ens3"
DEVICE="ens3"
ONBOOT=yes
NETBOOT=yes
UUID="80ccc011-c41d-496a-adc3-xxxxxxx"
IPV6INIT=yes
DHCPV6C=yes
BOOTPROTO=dhcp
TYPE=Ethernet
NM_CONTROLLED=no


VBA namespace in createElement

Question: Trying to add a namespace before the Element but getting the error "Only a default namespace can have an empty URI".
My code is quite simple:
nmsp = "http://test.com"
    Set root = doc.createNode(NODE_ELEMENT, "ns1:currency_rates", nmsp)
    doc.appendChild root

    Set ydatasNode = doc.createNode(NODE_ELEMENT, "ns1:currency_rate", nmsp)
    root.appendChild ydatasNode

    ' ITERATE CLIENT NODES '
     For i = 2 To 3

        ' FIRST NAME NODE '
        Set firstNameNode = doc.createElement("inst_id")
        firstNameNode.Text = "1001"
        ydatasNode.appendChild firstNameNode

It generates XML as
<ns1:currency_rates xmlns:ns1="http://test.com">
    <ns1:currency_rate>
        <inst_id>1001</inst_id>
        <lastName></lastName>
        <age></age>
        <civility yid="AAAA"></civility>
        <inst_id>1001</inst_id>
        <lastName></lastName>
        <age></age>
        <civility yid="AAAA"></civility>
    </ns1:currency_rate>
</ns1:currency_rates>

what I need is to have
<ns1:inst_id>1001</ns1:inst_id>

If I'm trying with
Set firstNameNode = doc.createElement("ns1:inst_id")
i have an error: "Only default namespace can have empty URI"
If I try like this
Set firstNameNode = doc.createElement("ns1:inst_id", "uri")  - "Wrong number of arguments passed" So probably it needs override the method but not sure how to do this
Comment: Can you show a complete example?  Are you creating a document from scratch?
Comment: I think though when creating a node with a namespace you don't include the namespace alias in the tagname, so try: `doc.createNode(NODE_ELEMENT, "ns1:currency_rate", nmsp)`
Comment: Hello have in a code:
Set ydatasNode = doc.createNode(NODE_ELEMENT, "ns1:currency_rate", nmsp)
Comment: Can you show the starting point? (ie. your XML including namespace declarations)
Answer: Try following :
Imports System.Xml
Imports System.Xml.Linq
Imports System.Xml.XmlNamespaceManager
Module Module1

    Sub Main()
        Dim ident As String = "<ns1:currency_rates xmlns:ns1=""http://test.com""></ns1:currency_rates>"

        Dim rates = XElement.Parse(ident)
        Dim ns1 = rates.GetNamespaceOfPrefix("ns1")
        rates.Add(New XElement(ns1 + "currency_rate"))
        Dim rate = rates.Elements().Where(Function(x) x.Name.LocalName = "currency_rate").FirstOrDefault()

        rate.Add(New Object() { _
                 New XElement("inst_id", 1001), _
                 New XElement("lastname"), _
                 New XElement("age"), _
                 New XElement("civility", New XAttribute("yid", "AAAA")), _
                 New XElement("inst_id", 1001), _
                 New XElement("lastname"), _
                 New XElement("age"), _
                 New XElement("civility", New XAttribute("yid", "AAAA")) _
                 })

    End Sub

End Module

Comment: This code is for VB.NET and I can't explicitly move it to VBA

VBA namespace in createElement


How do you change makefile variables file extension?

Question: For example, I have a variable that holds a list of dependencies
BOARDS:=lance.mcm light.mcm sac.mcm

I need another variable named NET such that
NET:=lance.net light.net sac.net

It should be set such that when I change the BOARDS variable, NET should change as well.
For example, if I add a new zor.mcm into the BOARDS variable, it should automatically add zor.net into the NET variable.
Comment: Superset: multiple extensions: http://stackoverflow.com/questions/12069457/how-to-change-the-extension-of-each-file-in-a-list-with-multiple-extensions-in-g
Answer: The best solution I have found is to use this syntax:
NET:=$(BOARDS:.mcm=.net)

This will look at BOARDS and change the .mcm into .net
Comment: A little more explanation at [How to change the extension of each file in a list with multiple extensions in GNU make?](http://stackoverflow.com/a/12071918/1730674)
Answer: As an alternative:
BOARDS:=lance.mcm light.mcm sac.mcm
NET:= $(addsuffix .net, $(basename $(BOARDS)))

This will preserve contents inside the file pathnames should they match pattern
Comment: This is why I posted the question in the first place. This is perfect, thanks!


Extract a value from a string file and converting it to int with Java

Question: I have a text file (test.txt) :
Bob, 12, 15, 20
Ruth, 45, 212, 452

With Java, I want to extract only the last element of each line (each element being separated by a coma).
For now on, I wrote this code :
br = new BufferedReader(new FileReader("test.txt"));
while ((line = br.readLine()) != null) {

    String[] facture = line.split(",");

    int fquantite = Integer.parseInt(facture[3]);

System.out.println("Amount=" + fquantite);

But it gives me an error. The thing is that I get how to get the number (for exemple, I can write :
System.out.println("Amount=" + facture[3]);
And it works, but for some reason, I can't get to convert it to a int. The reason I want to do that is because when I'll have this int variable, I'll want to add it to another int variable.
Comment: "But it gives me an error" could you add the error message so people with same error would be able to find your question and potential solution to their problem (which is kind of main goal of this site)?
Answer: You split by comma, but your input also contains spaces. Use trim to remove them: Integer.parseInt(facture[3].trim()).


Why is my KVM, RHEL6.2 server swapping?

Question: I have a RHEL6.2 server that I'm using to run KVM virtual machines.
The server itself has 16 GB of RAM.  I want to see the biggest VM I can run on it and not let the qemu-kvm process swap.  The VM ram is ~15GB.  (Yes, I realize that this is pushing the limit, but read to the end before answering with something like "15GB is too much".)
<code>[root@xxx libvirt]# virsh dumpxml VM2 | grep -i memory
  <memory>15000000</memory>
  <currentMemory>15000000</currentMemory>

[root@xxx libvirt]# ps -ef | grep kvm
root       872     1 16 10:55 ?        00:03:00 /usr/libexec/qemu-kvm [...] -m 14649 -name VM2 [...]

[root@xxx libvirt]# free -k
             total       used       free     shared    buffers     cached
Mem:      16332640   16194440     138200          0       1544      15700
-/+ buffers/cache:   16177196     155444
Swap:     35651568    7583432   28068136
</code>
But the RSS of the KVM process is only 880 MB (column 6 below).  I expect it to be more like 12-14 GB.
<code>[root@xxx libvirt]# ps -eF | grep kvm
root       872     1 14 4534221 882916 7 10:55 ?       00:03:11 /usr/libexec/qemu-kvm
</code>
And, if I add up the RSS of all processes, its only ~ 1gig.
<code>[root@xxx libvirt]# ps -eF | awk '{print $6}' | grep '[0-9]' | tr '\n' '+' | sed 's/+$/\n/' | bc
1004064
</code>
Here are the processes that are the biggest memory users (RSS, column 6).
<code>root      5188 22329  0 27572  1192   4 11:19 pts/0    00:00:00 ps -eF
root     31461     1  0 10746  1236   7 Jul25 ?        00:06:22 [...]
root      6339  6275  0 272676 3288   4 Jul27 ?        00:13:38 [...]
root      2059     1  1 443909 13352  7 Jul17 ?        05:29:11 libvirtd --daemon
root       872     1 13 4534221 928300 2 10:55 ?       00:03:24 /usr/libexec/qemu-kvm [...]
</code>
I expect that about 300-500 MB of memory should still be available for the VM.
UPDATE
After rebooting the machine, I cannot reproduce this anymore.  The system now works as I expect it to.  Here are these expected numbers.
Oh, I should mention.  There is a memory intensive program running in the VM.  It allocates 80% of the total memory and continually writes random numbers to it.
RSS of the VM:
<code>[root@hb05b15 ~]# ps -eF | grep kvm
root      7330     1 97 4520362 12483728 2 11:59 ?     00:39:55 /usr/libexec/qemu-kvm [...]
</code>
Mem and swap numbers:
<code>[root@hb05b15 ~]# free -k
             total       used       free     shared    buffers     cached
Mem:      16332640   13277468    3055172          0      21064     215196
-/+ buffers/cache:   13041208    3291432
Swap:     35651568          0   35651568
</code>
Sum up RSS for all processes:
<code>[root@hb05b15 ~]# ps -eF | awk '{print $6}' | grep '[0-9]' | tr '\n' '+' | sed 's/+$/\n/' | bc
12607180
</code>
Comment: cat /proc/sys/vm/swappiness ?
Answer: You don't have any RAM left for the operating system, filesystem cache or anything else.
Don't push your VM's RAM so high without leaving adequate headroom.
Now, of course, you could disable swap and see what happens...
Comment: Are you sure about that?  After adding up the RSS of all processes, there is ~600MB for OS, cache and anything else.  I don't think it needs that much.
Comment: Oops. I meant to say 6GB if unaccounted RAM!  Also, the VM is using 80% of its RAM.  Due to mem overcommit, its really only a 13GB VM.
Answer: There's a big difference between swap being used and the machine actively swapping.  The kernel will preemptively move more and more onto disk as it sees calls for large amounts of memory.  If the stuff moved out to disk isn't that frequently used then it's not necessarily a huge problem.  If data is constantly being swapped in and out then there's usually a big problem.  The real measure here is to look at something like iostat to observe how much data is actually being passed back and forth in a given interval.
That said, a 15G VM on a 16G box is probably not going to play out well.  The OS itself requires a certain amount and there's always a percentage of overhead for the VM.  If you are, in fact, actively swapping then you may see substantial improvements just backing off to, say, 12 or 13G.
Comment: I can confirm that the process was indeed swapping.  top w/ nFLT enabled shows +600K faults for the kvm process.  And iostat showed that the swap disk was 100% utilized.

You're suggestion about trying w/ 12/13GB is a good one.  Unfortunately I rebooted the machine and cannot reproduce it anymore.  Also, I have another box that has been up for a while, also doing KVM stress testing.  And I cannot reproduce it on that box either.
Comment: Asking the host OS for 15gb of ram will not automatically make 15gb of ram unavailable to all other processes. (KVM guest processes aren't different to the host kernel than any other process in this respect.) There isn't per se a problem with having VMs who's defined memory collectively sums to more than the physical amount available on the host. (I have half a dozen KVM servers with 24GB RAM each, with VMs totalling twice to three times that on each.  The key is that I don't expect them to use it simultaneously.  Google for "kvm memory overcommit".
Comment: @sapeurfaire, Thanks for the comment.  Did you see my update.  The system can indeed handle this 15GB VM.  The problem is that when the error happened, I can't account for where the RAM is being used.  Also, swap was using a huge amount of memory.  The numbers are:  16GB ram.  Add up RSS of all processes (including the VM): 10GB.  So the OS needs to hold on to 6GB!
Comment: @MichaelClosson, I saw the update after I'd commented :)  I'm not sure what to make of the original problem, but wonder if it's recurring?  It's also worth looking at this:  http://publib.boulder.ibm.com/infocenter/lnxinfo/v3r0m0/index.jsp?topic=%2Fliaat%2Fliaattunsetswapiness.htm
Comment: How long had the box been up when the issue began?  If it had been up for a while then in theory a small memory leak could have accounted for the heavy memory utilization on what otherwise looks like a pretty quiet system.

Why is my KVM, RHEL6.2 server swapping?


How could I pass a database run-time parameter in ruby on rails?

Question: I need to set a run-time parameter in postgresql. It is "SET DATESTYLE TO PostgreSQL,European;". Where can I pass that in a Rails Application?
Answer: An initializer would be an appropriate place to do that:
<code># config/initializers/set_datestyle.rb

ActiveRecord::Base.connection.execute 'SET DATESTYLE TO PostgreSQL,European;'
</code>
Answer: Don't you want the "SET DATASTYLE" statement for each new connection? Then an initializer isn't the right place.
I think you should take a look at
ActiveRecord::Base.postgresql_connection
or
ConnectionAdapters::PostgreSQLAdapter#configure_connection (private)
This ticket has a patch for a similar problem in the mysql world:

http://dev.rubyonrails.org/ticket/5260

Might help you look in the right files.
On the other hand, it may be easier to set the environment variable PGDATESTYLE, see
www.postgresql.org/docs/8.2/static/datatype-datetime.html
At the end of section "8.5.2. Date/Time Output" it says
"The date/time styles can be selected by the user using the SET datestyle command, the DateStyle parameter in the postgresql.conf configuration file, or the PGDATESTYLE environment variable on the server or client. The formatting function to_char (see Section 9.8) is also available as a more flexible way to format the date/time output."
Either on the server, or the client.
Stephan
Answer: Have you tried ActiveRecord#execute ? It lets you send arbitrary sql to the database:
<code>connection.execute("SET DATESTYLE TO PostgreSQL,European;")
</code>
I'm not sure if you need or want the semicolon there.


How can I call a function stored in an object that is being used as an argument for another function?

Question: I'll be honest, I'm in way over my head with this one. Any help would be appreciated.
OBJECTIVE
I want to call a function called restart, but the function is inside an object and is being passed to a function Class.extend.
The code I'm working with is
    var Chickenz = Class.extend(
{
        init: function(value)
        {
           //do something
        },
        // restart game
        restart: function()
        {
            this.score.restart();
            //etc
        }
});

What have I tried?
restart(); Doesn't work. I get TypeError: restart is not a function  No biggy I didn't expect it to work.
Based on this question >
Javascript - Storing function in object - bad practice?
I thought I could do something like Chickenz.restart(); but it's more complicated, because of Class.extend
I've included code for Class.extend towards the bottom of this question.
Later the restart function is called with the following code
/* GUI Events */
            // restart button
            addEvent($("restart"), "click", function() {
                self.restart();
                return false;
            });

I thought I would try self.restart(); but that didn't work- TypeError: self.restart is not a function.
So my question.
How can I call the restart function?
CODE for Class.extend
var initializing = false;
  // The base Class implementation (does nothing)
  this.Class = function(){};
  // Create a new Class that inherits from this class
// Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype,
        prototype,
        name,
        tmp,
        ret;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for ( name in prop ) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" ?
        (function(name, fn){
         return function() {
           tmp = this._super;
           // Add a new ._super() method that is the same method
           // but on the super-class
           this._super = _super[name];
           // The method only need to be bound temporarily, so we
           // remove it when we're done executing
           ret = fn.apply(this, arguments);
           this._super = tmp;
           return ret;
         };
        })(name, prop[name]) :
        prop[name];
    }
    // The dummy class constructor
    //Changed according to http://ejohn.org/blog/simple-class-instantiation/
    //Use the new operator to instantiation
        function Class(args){
                if ( this instanceof arguments.callee ) {
                    if ( !initializing && this.init )
                        this.init.apply( this, args.callee ? args : arguments );
                } else
                    return new arguments.callee( arguments );
            };

    // Populate our constructed prototype object
    Class.prototype = prototype;
    // Enforce the constructor to be what we expect
    Class.constructor = Class;
    // And make this class extendable
    Class.extend = arguments.callee;
    return Class;
 };

Answer: You appear to be basing this on John Resig's example here You should look at how he does it :)
Class.extend returns a constructor for a class.  You can just create an instance of the class and then call it.
You need something like:
var chicken = new Chickenz();

chicken.restart();

Note that this will immediately throw an error right now though, because this will then be bound to the new chicken object, and the chicken doesn't have a score.restart function unless you have other code you aren't showing us.  I have no idea what you want that line to do, but you'll need to add a score property with a restart method to the chicken object or have the restart method reference something else.
Comment: Thanks for that! I haven't got it working yet, but this is definitely the right track.


How to control 3D object's position(or rotation) according to some variables in SceneKit?

Question: I have tried to find the solution about this question. But I didn't find the answer yet.(Or it's not appropriate to reach my requirement with SceneKit)
My requirement is that I want to control the position or rotation of 3D object(.dae file) by particular variables in Xcode.
I used the example game file in Xcode 6 to do this.
But the SCNAction fucntion can't use variables as the input parameter.
Example:
var position_x = 0.5

var position_y = 3

var position_z = 4

SCNAction.moveByX(x, y: position_y, z: position_z, duration: 1.0) // Error

I didn't understand why SCNAction can't use variables declared outside?
Or does it have any method to control the position or rotation of object?
Answer: what's the exact error?
SCNAction expects CGFloat arguments. Does explicitly typing your variables help?
var position_x = CGFloat(0.5)
var position_y = CGFloat(3)
var position_z = CGFloat(4)
SCNAction.moveByX(x, y: position_y, z: position_z, duration: 1.0)

Comment: Yes, the parameters must be CGFloat type. Thanks a lot!