Write a list to file containing text and hex values. How?

Question: I need to write a list of values to a text file. Because of Windows, when I need to write a line feed character, windows does \n\r and other systems do \n.
It occurred to me that maybe I should write to file in binary.
How to I create a list like the following example and write to file in binary?
output = ['my first line', hex_character_for_line_feed_here, 'my_second_line']

How come the following does not work?
output = ['my first line', '\x0a', 'my second line']

Comment: open the file in binary mode open(path,"wb")
Comment: i get that part for sure but in python 3.3, what does the hex representation of a line feed looks like using my example above? Something like... \x0a  ?
Comment: I guess my question is, how do I convert anything inside of a list to its hex character representation if it isn't already, then write to file?
Comment: `'\x0a'` is *exactly* the same character as `'\n'`.
Answer: Don't. Open the file in text mode and just let Python handle the newlines for you.
When you use the open() function you can set how Python should handle newlines with the newline keyword parameter:

When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

So the default method is to write the correct line separator for your platform:
with open(outputfilename, 'w') as outputfile:
    outputfile.write('\n'.join(output))

and does the right thing; on Windows \r\n characters are saved instead of \n.
If you specifically want to write \n only and not have Python translate these for you, use newline='':
with open(outputfilename, 'w', newline='') as outputfile:
    outputfile.write('\n'.join(output))

Note that '\x0a' is exactly the same character as \n; \r is \x0d:
>>> '\x0a'
'\n'
>>> '\x0d'
'\r'

Comment: @Vini: That is because you are opening the file with `newline=None` and a `\r\n` is written. Use `newline=''` instead.
Comment: line feed is not the only hex character I'd like to add to this string. For some reason this does not work: output = ['my first line', '\x0a', 'my second line']
Comment: @Vini: Why do you need to add explicit linefeeds? They'll work just fine, btw, Python will write those to your file unchanged. `'\x0a'` *is the same character* as `\n`.
Comment: Record separators, Carriage Returns. I am basically building a string that follows a standard and gets encoded to pdf417 Bar Codes.
Comment: @Vini: If you need to write *exact* line separators, set `newline=''` and no translation takes place. If you need them translated to platform-specific newlines, use `newline=None`. This is still ASCII data, so textual mode is just fine.
Comment: @Martinjn Pieters: When I write in w mode '\x0a' and look at the text file in a hex editor a '\x0d' gets appended before '\x0a'. When I do it in wb mode, it crashes
Comment: Un... real. It's in the details after all. Thanks a lot Martinjn Pieters.
Answer: Create a text file, "myTextFile" in the same directory as your Python script. Then write something like:
# wb opens the file in "Write Binary" mode
myTextFile = open("myTextFile.txt", 'wb')

output = ['my first line', '369as3', 'my_second_line']

for member in output:
    member.encode("utf-8") # Or whatever encoding you like =)
    myTextFile.write(member + "\n")

This outputs a binary text file that looks like:
my first line
369as3
my_second_line

Edit: Updated for Python 3
Comment: This is Python 3; you need to write *bytes*, not strings to files when opening a file in binary mode. Your code does not work on Python 3.
Comment: Ah I see, the OP didn't specify the version. Edited my code to encode the string to bytes first.
Comment: Yes, he did, in the tags on the question.
Comment: Didn't see the tag. Still, edited my code to encode the string to bytes first.


Como fazer os dados aparecerem nos campos em AngularJS

Question: Estou entrando com um cep e uma busca é feita e me traz os outros dados...
Porém, quero que os dados sejam exibidos, cada um no seu respectivo campo, pois serão inseridos no banco de dados.
Como proceder?
html:

<form>

    CEP

    <input type="text" ng-model="endereco.cep" ng-blur="pegaCep()">

    Estado

    <input type="text" ng-model="endereco.uf">

    Cidade

    <input type="text" ng-model="endereco.cidade" size="30">

    Bairro

    <input type="text" ng-model="endereco.bairro" size="30">

    Rua

    <input type="text" ng-model="endereco.logradouro" size="30">

</form>

controller:
app.controller('appController', function ($scope, $http){
$scope.endereco = {}
$scope.pegaCep = function () {
    $http.get("php/pegaCep.php?cep="+$scope.endereco.cep).success(function (endereco){
        console.log(endereco);
        $scope.endereco = endereco;
    });
 }

});

php:
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

$cep = $_GET['cep'];
//print_r($cep);

include('correios.class.php');
if(isset($_GET['cep'])){
$correios = Correios::cep($_GET['cep']);
$correios = json_encode($correios[0]);
    die($correios);
}elseif(isset($_GET['codigo_rastreio'])){
    die(json_encode(Correios::rastreio($_GET['codigo_rastreio'])));
}else{
    die('informe parametro GET cep ou codigo_rastreio');
}
?>

Comment: Pode incluir um exemplo do conteúdo retornado pela URL `php/pegaCep.php` ?
Comment: [{"cliente":"","logradouro":"Beco A (Estr Cristiano Kraemer)","bairro":"Vila Nova","cep":"91750073","cidade":"Porto Alegre","uf":"RS"}]
Answer: Você está utilizando o serviço $http. O objeto retornado inclui vários parâmetros. Faça as seguintes mudanças no seu código:
$scope.endereco = {};

$scope.pegaCep = function () {
    $http.get("php/pegaCep.php?cep="+$scope.endereco.cep).success(function (retorno){
        console.log(retorno);
        $scope.endereco = retorno.data;
    });
 }

Perceba que a propriedade data contém o valor retornado.
Propriedades do objeto retornado pelo serviço $http:

data – {string|Object} – o conteúdo da resposta, devidamente transformada.
status – {number} – Código HTTP retornado.
headers – {function([headerName])} – função para retorno de cabeçalhos.
config – {Object} – O objeto de configuração da requisição original.
statusText – {string} – O status HTTP em formato de texto.

Referência: https://docs.angularjs.org/api/ng/service/$http
Comment: Mesmo com essa mudança no código, os dados não aparecem.
Comment: @GustavoSevero No log do browser - pode confirmar se o endpoint está retornando algum conteúdo *quando chamado pela função, e não diretamente*?
Comment: @lbotinelly não seria o caso de usar um `$apply();`? Ou de atribuir diretamente o valor ao campo? ex.: `$scope.endereco.logradouro = retorno.data.logradouro`. Lembro que já passei por isso e só assim resolveu
Comment: Sim, está retornando, eu já postei o retorno dos dados:

[{"cliente":"","logradouro":"Beco A (Estr Cristiano Kraemer)","bairro":"Vila Nova","cep":"91750073","cidade":"Porto Alegre","uf":"RS"}]
Comment: @CelsomTrindade, aparece uma mensagem no console dizendo que logradouro não é reconhecido
Comment: @CelsomTrindade $apply() deve ser utilizado apenas em situações especiais, onde o modelo não recebe a propagação de eventos do $digest. O caso atual me parece bem simples, e não haveria necessidade.
Comment: @GustavoSevero se você está recebendo esta mensagem o objeto não está corretamente formado. Seu erro é outro - o valor enviado como parâmetro para o endpoint, ou a interpretação, por parte do serviço, do parâmetro enviado.
Comment: Vou postar o endpoit para vocês verem. Vejam no post
Comment: @GustavoSevero outra coisa - inicialize o objeto `$scope.endereco` antes de utilizá-lo na view, guarantindo assim que o modelo $scope.endereco.cep exista. Eu atualizei minha resposta com um exemplo.
Comment: Veja se é isso que vc sugeriu... Coloquei no post.
Comment: @GustavoSevero Sim, exatamente. Está obtendo o mesmo erro?
Comment: Nada, não aparecem os dados.
Answer: Como alternativa à resposta do amigo @lbotinelly, quando passei por uma situação semelhante, o que resolveu o meu problema foi aplicar diretamente o valor para cada campo, deste modo:
$scope.pegaCep = function () {
    $http.get("php/pegaCep.php?cep="+$scope.endereco.cep).success(function (retorno){
        $scope.endereco.cep = retorno.data.cep;
        $scope.endereco.logradouro = retorno.data.logradouro;
        //etc..
    });
};

Ou o uso do $apply() (em último caso).
Caso ainda assim não resolva o seu problema, verifique se o console realmente exibe os dados como você os espera.
$scope.pegaCep = function () {
    $http.get("php/pegaCep.php?cep="+$scope.endereco.cep).success(function (retorno){
        console.log(retorno.data);
    });
}

Pois o problema pode não estar no AngularJS.
Obs.:
Utilize a minha resposta em último caso, a dele está do modo correto.
Comment: Aparece no console "Cannot read property 'cep' of undefined""
Comment: O que o console disso aqui: `console.log(retorno.data)` mostra?
Comment: Isso:

0: Object
bairro: "Vila Nova"
cep: "91750073"
cidade: "Porto Alegre"
cliente: ""
logradouro: "Beco A (Estr Cristiano Kraemer)"
uf: "RS"
Comment: Consegue print? Acho que sua array que não está sendo gerada corretamente
Comment: Segue o print no post
Comment: estranho.... tente a minha resposta, mas ao invés de `$scope.endereco.cep = retorno.data.cep;` faça como o Nicholas propos: `$scope.endereco.cep = retorno.data[0].cep;` veja se funciona.
Comment: Consegui, tive que fazer ajustes no endpoint, no php, vejam no post
Comment: Beleza! Mas evite de colocar a resolução do problema na pergunta. Coloque como resposta, pois se mais alguém tiver o mesmo problema, saberá como resolver.
Answer: [{"cliente":"","logradouro":"Beco A (Estr Cristiano Kraemer)","bairro":"Vila Nova","cep":"91750073","cidade":"Porto Alegre","uf":"RS"}]
Já que o retorno do php é esse acima, você precisa fazer o seguinte:
app.controller('appController', function ($scope, $http){
$scope.endereco = {}
$scope.pegaCep = function () {
    $http.get("php/pegaCep.php?cep="+$scope.endereco.cep).success(function (endereco){

        $scope.endereco = endereco.data[0];
    });
 }

});

agora vai funcionar
Comment: Aparece no console "ReferenceError: endereco is not defined"
Comment: Eu estou me baseando no código que voce mandou na pergunta, é o mesmo que está atualmente?
Comment: Desculpe, não tinha feito uma alteração... Sim, está igual
Agora a resposta no console é "TypeError: Cannot read property '0' of undefined"


In ER Diagram how can we represent a relation like some players are coaches or some students are teachers

Question: Teachers and Students are two separate entities how can we represent this relation.
Comment: You need at least two more tables.
Comment: can u please explain in detail.
Comment: I'm less willing to write novels than you are to type out all three letters of a word.
Answer: you require 3 relations : one for teacher with attributes like name,age,phone,mail and id, one for student with attributes like name,id,age,parents' name,marks and mail and one for teaches with attributes as PK of above relations and other fields like subject and class timings and so on.
Answer: I suggest a table for
PERSON
----------
person_id
name
birth_date
etc.

Then one for
SCHOOL
---------
school_id
name
etc.

and now link them up.
STUDENT
-------------
person_id
school_id
begin_date
end_date

TEACHER
-------------
person_id
school_id
begin_date
end_date
etc.


How can I bind static string?

Question: For example, I have this interface:
import SwiftUI

struct ContentView: View {

    @Binding var statictext : String

    var body: some View {
        Text("My New Text: \(statictext)")
    }
}

and this class:
class Strings
{
    public static var mytext = "MyText"
}

How can I initialize ContentView? I need, than text in interface become "My New Text: new text" when I change the value of Strings.mytext = "new text"
P.S.: sorry for my English)))))
Answer: I dont know if this is the right answer for this question but you could do this, even thou it feels kinda dirty to me.
import SwiftUI

class Strings
{
    public static var mytext = "MyText"
}

struct ContentView: View {

    @State var statictext : String {
        willSet {
            Strings.mytext = newValue
        }
    }

    init() {
        self._statictext = State(initialValue: Strings.mytext)
    }

    var body: some View {
        VStack {
            Text("My New Text: \(statictext)")

            Button(action: {
                self.statictext = "Test"
            }) {
                Text("Button")
            }
        }
    }
}

Comment: How can I update screen, when static text is changed?

How can I bind static string?


How to read registry value correctly in C#

Question: I have created a key of type string and named it mykey in registry at HKEY_USERS\.DEFAULT with the value set to 1234.
I have a windows form application with a button on it.
I want to see the value of mykey in a MessageBox whenever the button is pressed. How can I achieve that?
This is what I did. But this code only shows HKEY_USERS in the MessageBox and not the value of mykey.
private void button1_Click(object sender, EventArgs e)
    {
        RegistryKey rk = Registry.Users;
        rk.GetValue("HKEY_USERS\\.DEFAULT\\mykey");

        if (rk == null)
            MessageBox.Show("null");
        else
            MessageBox.Show(rk.ToString());
    }

Comment: Why is that a duplicate @PedroG.Dias
Comment: @PedroG.Dias How is that link even an answer?! I don't understand. My question is within the context, while the link you gave -- which links to another link, by the way -- is not. It doesn't even have one proper example.
Comment: Sorry, removing it
Answer: You specify the Users part twice. First as the hive of the registry and then as registry key.
You can remove it from the latter:
rk.GetValue(@".DEFAULT\mykey");

Or you should start with the registry without selecting a hive:
Registry.GetValue(@"HKEY_USERS\.DEFAULT\mykey");

Answer: You have specified User two times but you have to do that anyone of that, here is the safe way to read registry value
private void button1_Click(object sender, EventArgs e)
    {
        using (RegistryKey key = Registry.Users.OpenSubKey(".DEFAULT"))
        {
            if (key != null)
            {
                Object val = key.GetValue("mykey");
                if (val != null)
                {
                    MessageBox.Show(val.ToString());
                }
                else
                {
                   MessageBox.Show("Null");
                }
            }

        }
    }


multiple validations Rails 3 (Rails for Zombies; 2:3)

Question: I am working through Rails for Zombies, loving the helpful tutorial and interested in others by the way....
My issue is as follows.
The tutorial ask me to
"Do both uniqueness and presence validation on a Zombie's name on a single line, using the new syntax"
I have tried the following in the console at RfZ;

class Zombie < ActiveRecord::Base
  validates_uniqueness_of :name, validates_presence_of :name
end

// AND  //
class Zombie < ActiveRecord::Base
  validates Name :uniqueness, :presence => true
end

The tutorial is asking for the new Rails 3 syntax. I understand the new syntax allows for multiple validation arguments in one line. Very nice, but how would I do this? Thanks in advance everyone.
-Ryan
Answer: Your second attempt is closer, but not quite correct. Try this:
class Zombie < ActiveRecord::Base
  validates :name, :uniqueness => true, :presence => true
end

FYI, the older syntax would be :
class Zombie < ActiveRecord::Base
  validates_presence_of :name
  validateS_uniqueness_of :name
end

Comment: Click the ✔ to the left of this answer :P
Comment: Rob, you rock, thanks. I totally appreciate it, that worked I see why too.
Comment: No problems! Note: you should generally accept an answer that satisfies your question so that your question is closed, and so that people searching Stack Overflow can find the answer if they have a similar question.
Comment: OK. Let me take a second to figure this out so I can accept your answer Rob, thanks again.
Answer: validates :name, :presence => true, :uniqueness => true

Comment: Why was this answer downvoted? It was the first answer to the question AFAIK
Comment: Toxic community. Happens everywhere.


open set in subspace

Question: Could someone check the following?

Consider $M=\{0\} \cup \{ 2^{-k}: k \in \mathbb{N}\}$ a subspace of $\mathbb{R}$. Which of the subsets $\{0\}$ and $\{2^{-k}\} (k\in \mathbb{N})$ are open in $M$?

Am I right to say that $\{0\}$ and $\{2^{-k}\}\; (k\in \mathbb{N})$ are open in $M$?
Since each $\{m\}\subseteq M$ can be written as $\{m\} \cap M$ where $\{m\}$ is open in $\mathbb{R}$.
added a picture to clarify the answer (see comment)
Comment: I'm afraid not: no singleton $\{x\}$ is open in $\Bbb R$. A non-empty subset of $\Bbb R$ is open if and only if it is a union of open intervals.
Answer: With respect to $\{2^{-k}\}(k \in \mathbb{N})$, you are partially correct.
Recall that an open set of a subspace of $\mathbb{R}$ is given by the intersection of that subspace with open sets of $\mathbb{R}$. So if you have an isolated point in $M$, then it will be open in $M$---this is since if $x \in M$ is isolated, there is an open neighbourhood $U$ around it which does not intersect any point of $M$. So $U \cap M = \{x\}$ is open.
Hence, each of the sets $\{2^{-k}\}$ are open.
Now, what can you say about a neighbourhood $(-\epsilon, \epsilon)$ of 0 and its intersection with $M$? Can you do the same trick?
Comment: The OP's conclusion is partly correct, but this is merely a fortunate accident, since the reasoning is entirely wrong.
Comment: Thank you, that was very clarifying! I've added the 'mental' picture to the question. Around each singleton $\{ 2^{-k}\}$ there is an open ball $U$ in $M$, while that does not exist at $\{0\}$ since it is a limit point.

open set in subspace


The minimizer of $2$-norm

Question: I am trying to compute
$$
\operatorname{argmin}_{z\in\mathbb R^n}\frac12\|z-x\|_2^2+\|z\|_2
$$
where $\|\cdot\|_2$ is the usual 2-norm.
By doing sub-differential with respect to $z$ and let it equal to 0, I got
$$
z(1+1/\|z\|_2)=x
$$
I am wondering is this all I can do? or could I future simplify it?
Answer: The formula implies that $z = tx$ for some $t$. Put that into your formula and cancels $x$, and help you solves for $t$. Then $z = tx$ is found explicitly.
Answer: You are computing the prox-operator of the $\ell_2$-norm.
The Moreau decomposition formula expresses the prox-operator of a proper closed convex function $f$ in terms of the prox-operator of $f^*$, the convex conjugate of $f$:
$$
\text{prox}_{f}(x) = x -  \text{prox}_{f^*}(x).
$$
If $f(x) = \| x \|$, where $\| \cdot \|$ is any norm on $\mathbb R^n$, then $f^*$ is the indicator function for the dual norm unit ball.  It follows that the prox-operator of $f^*$ simply projects onto the dual norm unit ball. Hence,
$$
\text{prox}_{\| \cdot \|}(x) = x - P_B(x),
$$
where $B$ is the dual norm unit ball and $P_B(x)$ is the projection of $x$ onto $B$.
In the special case where $\| \cdot \|$ is the $\ell_2$-norm, $B$ is the $2$-norm unit ball (because the $\ell_2$-norm is self-dual) .  So,
$$
\text{prox}_{\| \cdot \|_2}(x) = x - P_B(x),
$$
where $B = \{u \mid \| u \|_2 \leq 1\}$.
The prox-operator of the $\ell_2$-norm simply shrinks $x$ towards by origin by a distance of one unit.
Comment: I see. So if I am computing $\operatorname{argmin}_{z\in\mathbb R^n}\frac12\|z-x\|_2^2+t\|z\|_2$ then I should expect that $\operatorname{prox}_f(x) = x-\frac1t\operatorname{prox}_{f^*}(x)$ right?
Comment: ops, it should be $t\operatorname{prox}_{f^*}(x/t)$.
Comment: @JumpJump In that case, the formula to use is $\operatorname{prox}_{tf}(x) = x - t \operatorname{prox}_{(1/t) f^*}(x/t)$.  If $f(x) = \| x \|_2$, it turns out that $\operatorname{prox}_{tf}(x)$ shrinks $x$ towards the origin by a distance $t$.
Comment: understood. thank you sir

The minimizer of $2$-norm


Bash script containing clogin not working when executed via php

Question: I created a simple PHP site we would like to use to disable/enable ports on a cisco switch.
I am passing over two arguments (port and action) to a bash script via the php function exec(). For debugging I set those arguments at the end inside the bash script.
The important part of the php function I am calling looks like this:
function PortAction($port, $action){
    echo "
 Port:".$port."
Action:".$action;
    chdir('/usr/local/icinga-1.7.0/videowand/');
    echo exec('sh /usr/local/icinga-1.7.0/videowand/action2.sh 2>&1',$output, $return);
    echo "Return / Output: ".$return;
    print_r($output);
}

The bash script "action2.sh":
#!/bin/bash
/usr/libexec/rancid/clogin -c "conf t; int Fa0/1; shutdown" 192.168.6.6

If i execute the bash script manually (or even the directly the clogin command) as apache user, it all works as expected, the port gets disabled.
But as soon as I call it over the PHP function, I get the output:

Array ( [0] => no such variable [1] => (read trace on "env(HOME)") [2] => invoked from within [3] => "set password_file $env(HOME)/.cloginrc" [4] => (file "/usr/libexec/rancid/clogin" line 66)

And nothing gets done.
Which indicates some problem with the password entry (as far as I can see).
Permissions on this file(s) are correct, I guess they have to otherwise it wouldn't work directly inside the shell.
Even tried to change the .cloginrc path using the -f switch, no success.
PHP Safe-mode: Off
Display errors: On
The script takes a while because a telnet connection needs to be opened. This is why I put this into a separate bash script.
Answer: Provide the full path to the sh binary, like this:
echo exec('/bin/sh /usr/local/icinga-1.7.0/videowand/action2.sh 2>&1',$output, $return);

I'm assuming /bin/sh above, as that is commonly the standard path for sh, but make sure with which sh command.
/bin/sh is a soft link to your shell, which usually is /bin/bash, I'm not sure exec() can work with soft links of binaries, so if above doesn't works then just use /bin/bash instead of /bin/sh
Comment: Thanks for this, but the output's still the same error, whether I use /bin/sh, /bin/bash or nothing at all (just /usr/local/icinga-1.7.0/videowand/action2.sh)
Comment: Try with system()  `system('HOME=/home/user /bin/bash /usr/local/icinga-1.7.0/videowand/action2.sh 2>&1', $return);`


SVN Update - Most Simple Merge - After merge its still not happy

Question: Trying to learn the basics of SVN (using SilkSVN command line for now).  I created a conflict, did "SVN Update" and selected Merge, then "(2) Use your version.  It says "merge of "Sample1.ps1" completed.  But then it puts the menu back on the screen and wants to to choose another option.  There was only one file in conflict.  Why didn't the update complete successfully after my merge?
c:\Code\Demo>svn commit -m "Test conflict"
Sending        Sample1.ps1
svn: E155011: Commit failed (details follow):
svn: E155011: File 'C:\Code\Demo\Sample1.ps1' is out of date
svn: E160028: File '/Sample1.ps1' is out of date
<code>c:\Code\Demo>svn update
Updating '.':
C    Sample1.ps1
Updated to revision 5.
Conflict discovered in file 'Sample1.ps1'.
Select: (p) postpone, (df) show diff, (e) edit file, (m) merge,
        (mc) my side of conflict, (tc) their side of conflict,
        (s) show all options: m
Merging 'Sample1.ps1'.
Conflicting section found during merge:
(1) their version (at line 6)         |(2) your version (at line 6)
--------------------------------------+--------------------------------------
Write-Host "The Demo2 Change End"     |Write-Host "The End - Some other Demo
--------------------------------------+--------------------------------------
Select: (1) use their version, (2) use your version,
        (12) their version first, then yours,
        (21) your version first, then theirs,
        (e1) edit their version and use the result,
        (e2) edit your version and use the result,
        (eb) edit both versions and use the result,
        (p) postpone this conflicting section leaving conflict markers,
        (a) abort file merge and return to main menu: 2
Merge of 'Sample1.ps1' completed.
Select: (p) postpone, (df) show diff, (e) edit file, (m) merge,
        (r) mark resolved, (mc) my side of conflict,
        (tc) their side of conflict, (s) show all options: s
</code>
Comment: With a `svn up`, I usually end up selecting `postpone` and resolving the issue manually by myself. Then, using `svn resolved` to mark the file resolved. I don't like trying to resolve in the middle of an update.
Answer: I simply need to pick the "R" for "Resolved".  I thought the merge resolved it, not sure why the final step is required.


Check values inside a foreach loop

Question: I have an array
 A[0]=array {
    title="a";
    filename="1.jpg"
    }
 A[1]=array {
    title="a";
    filename="2.jpg"
    }

Now my out put like
A
1.jpg
A
2.jpg

I wish an output like
A
1.jpg
2.jpg

So i tried
<?php
$name='';
foreach($items as $item){
    if ( $item['title'] =$name) {
        $item['name']['file']=$item['filename']
    }
}
?>

Bad luck its not working.please help me
Comment: Coding is never based on Luck
Comment: Your array looks odd... Are you sure it's not an object?
Comment: Bad logic* is not working
Comment: Look up when to use `=` and when to use `==` HINT: tests use `==`
Comment: _Small Point_ This code is not OUTPUTTING anything?
Answer: You need to re-arrange array first and then printout data from it:
<?php

$finalArray = [];

foreach($items as $item){
    $finalArray[$item['title']]['filename'][] = $item['filename'];
}

foreach($finalArray as $key=>$value){
    echo $key.PHP_EOL;
    foreach($value['filename'] as $val){
        echo $val.PHP_EOL;
    }
    echo PHP_EOL;
    echo PHP_EOL;
}

Output:- https://3v4l.org/oklHW
Note:- if your initial array is an stdClass object array then do like below:-
$finalArray = [];

foreach($items as $item){
    $finalArray[$item->title]['filename'][] = $item->filename;
}

foreach($finalArray as $key=>$value){
    echo $key.PHP_EOL;
    foreach($value['filename'] as $val){
        echo $val.PHP_EOL;
    }
    echo PHP_EOL;
    echo PHP_EOL;
}

Output:-https://3v4l.org/DWrn1

Check values inside a foreach loop


Criando relatórios com ASP.NET MVC e AngularJS

Question: Meu backend é com C#/MVC, no frontend uso Angular, cheguei num ponto do projeto que preciso criar relatórios.
Como gerar relatórios em ambiente web?
Qual ferramenta que usa?
Comment: Sua pergunta é meio ampla. Você precisa fazer uma pesquisa pois há enumeras ferramentas e formas de fazer relatórios, que vão de relatórios em HTML(tables) até com ferramentas pagas ou gratuitas como Report Viewer, Crystal Reports, Active Reports entre outras tantas
Answer: Pode usar o ng-report
Ou então o wijmo-5
Isto, se do lado do Front End.
Comment: o que vc aconseha, do lado do front ou do back ? qual a principal diferença
Comment: Aconselho do lado do BackEnd.
reduzes o tamanho de dados a serem enviados para o FrontEnd e se necessitares de usar esses mesmo dados em uma outra parte do FrontEnd ou um outro aplicativo não tens de voltar a replicar o mesmo  código logico para obter os mesmos  valores.


Proximal Functions / Proximal Operators

Question: I am a little bit new to proximal functions and I am currently stuck with the following problems
How would I derive the prox function for the regularizer (h(x) function) : $\alpha\sum_{k+} $ and for $ \alpha ||z||_2$?
Any hint about how to start and do this would be great.
Comment: What are $\sum_{k+}$ and $z$?
Comment: I edited it. Does that help?
Answer: There is a nice table of proximal operators of several commonly used functions in Combettes and Pesquet, 2010. You might want to have a look.
Comment: Please try to describe as much here as possible in order to make the answer self-contained. Links are fine as support, but they can go stale and then an answer which is nothing more than a link loses its value.
Comment: Oups! Sorry. Will do that.

Proximal Functions / Proximal Operators


Ubuntu Server 14.04.2 LTS: MOTD always displays the same packages to be updated

Question: Since yesterday I always get this message when I log in via SSH:
2 packages can be updated.
0 updates are security updates.
There's nothing to be updated running apt-get update and apt-get upgrade:
sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
(1 not upgraded: I can't find it)
I've followed these posts but to no avail:
ubuntu server: SSH banner telling to update packages but nothing to update
Ubuntu tells me I have packages to upgrade when I don't
Any hints/suggestions?
Thanks in advance.
Answer: I get similar behavior when there is kernel updates.
Run sudo apt-get dist-upgrade and you should get rid of this one package.
dist-upgrade Will install new kernel and such, it does not install a newer release of Ubuntu.


Connected set cannot be written as the union of numerable proper connected separated sets.

Question: Is there a proof or a counterexample to such an affirmation?
For example, we know that no finite union of proper connected sets is connected.
Can it happen that given any connected set, and given a numerable collection of proper connected separated subsets of X, that X is equal to the union of such a collection?
In other words, given a connected set $X$, is $X$ is always bigger than any union of proper connected separated sets?
Comment: $$\mathbb{R} = (-\infty,0) \cup [0,\infty)$$
Comment: I think that I should edit my question. Thanks.
Comment: How does your edit invalidate the example in my previous comment?
Comment: Note the word "separated."
Comment: Define separated.
Comment: A, B are separated if $cl_X(A)\cap B = \varnothing$ AND $A\cap cl_X(B)=\varnothing$.
Answer: Let $X$ be any countably infinite set, with the cofinite topology.

Then $X$ is connected, and also, $X$ is the countable union of its singleton subsets, which are proper connected sets.

Also, any two distinct singletons sets are separated.


TYPO3 extension generate view error

Question: I'm building my first TYPO3 extension, exactly I'm just trying to build the example that is on the TYPO3 page, see link. Looks like something in the controller goes wrong. I'm using the following code
class Tx_Mtclnt_Controller_AdsController
   extends Tx_Extbase_MVC_Controller_ActionController {

   public function listAction() {

       $adsRepository = t3lib_div::makeInstance('Tx_Mtclnt_Domain_Repository_AdsRepository');
       $ads = $adsRepository->findAll();
       $this->view->assign('ads', $ads);
   }
}

I'm getting the following error:

1: PHP Catchable Fatal Error: Argument 1 passed to TYPO3\CMS\Extbase\Persistence\Repository::__construct() must implement interface TYPO3\CMS\Extbase\Object\ObjectManagerInterface, none given, called in /home/mtclnt02/typo3_src-6.2.9/typo3/sysext/core/Classes/Utility/GeneralUtility.php on line 4431 and defined in /home/mtclnt02/typo3_src-6.2.9/typo3/sysext/extbase/Classes/Persistence/Repository.php line 75 (More information)
TYPO3\CMS\Core\Error\Exception thrown in file
/home/mtclnt02/typo3_src-6.2.9/typo3/sysext/core/Classes/Error/ErrorHandler.php in line 101.
Comment: Is this really 6.2 code ???
Answer: The error you get results from the repository, which you try to create. The class TYPO3\CMS\Extbase\Persistence\Repository has a constructor, which requires \TYPO3\CMS\Extbase\Object\ObjectManagerInterface as argument. Since you don't pass an objectManager class in your t3lib_div::makeInstance, the error is thrown. You can avoid this, by using dependeny injection like shown below.
/**
 * @var Tx_Mtclnt_Domain_Repository_AdsRepository
 * @inject
 */
protected $adsRepository;

public function listAction() {
  $adsRepository = $this->adsRepository->findAll();
}

But I also see a general problem here, because the Extbase / Fluid book you refer to is outdated on some topics. From my point of view, the refered book is a quite useful resource if you want to understand the concept and architecture of an Extbase/Fluid extension, but not for code examples any more, since a lot of things have changed in TYPO3 since the book has been written.
If you want to start with TYPO3 extension development for TYPO3 6.2 or higher, I would suggest you install the extension extension builder and use it to create your first extension. The manual contains a short but helpful users manual, which guides you through the basics of creating a simple TYPO3 extension.
After you created your first extension with extension builder, you can go some steps further by adding functionality to the code created by extension builer.
Comment: Thanks for the clear anwser, I will start working with the extension builder!

TYPO3 extension generate view error


Exportação de dados CSV

Question: Pessoal alguém teria algum exemplo de como criar uma exportação de dados via web em .CSV? eu já tenho uma em meu sistema em .XLS, porém preciso modifica-la, alguem pode ajudar?
Controller
private void ExportacaoDados(DataSet data, string fileName, int type = 0)
        {
            if (type == 0)
            {
                var gv = new GridView();
                gv.DataSource = data;
                gv.DataBind();

                Response.Clear();
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xls");
                Response.ContentType = "application/vnd.ms-excel";
                Response.Charset = "";
                var sw = new StringWriter();
                var htw = new HtmlTextWriter(sw);
                gv.RenderControl(htw);
                Response.Output.Write(sw.ToString());

                Response.Flush();
                Response.Close();
                Response.End();
            }
            else
            {
                var sw = new StringWriter();
                sw.Write(ExportToCSVFile(data.Tables[0]));

                Response.Clear();
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".txt");
                Response.ContentType = "text/plain";
                Response.Charset = "";
                var htw = new HtmlTextWriter(sw);
                Response.Output.Write(sw.ToString());

                Response.Flush();
                Response.Close();
                Response.End();
            }
        }

        private string ExportToCSVFile(DataTable dtTable)
        {
            var sbldr = new StringBuilder();

            foreach (DataColumn c in dtTable.Columns)
            {
                sbldr.Append(Regex.Replace(c.ColumnName, @"\n|\t|\r", "") + "|");
            }

            sbldr.Append("\r\n");
            foreach (DataRow row in dtTable.Rows)
            {
                foreach (DataColumn column in dtTable.Columns)
                {
                    sbldr.Append(Regex.Replace(row[column].ToString(), @"\n|\t|\r", "") + "|");
                }
                sbldr.AppendLine();
            }

            return sbldr.ToString();
        }

Comment: csv, é arquivo de texto... só escrever... qual a origem dos dados ?
Comment: Eu fiz uma query puxando dos dados no meu SQL Server nisso trago a exportação
Comment: Coloque o código que já fez
Comment: Da uma olhada [nessa biblioteca](https://github.com/ServiceStack/ServiceStack.Text), ela é capaz de serializar uma classe ou converter valores para CSV.
Comment: @RovannLinhalis Atualizei o topico
Comment: @gato vou dar uma olhada!
Answer: Esse seu código, acredito que esteja correto, só acho desnecessário o Replace no nome da coluna, e, utilizar , ou ; para separar os campos, não o pipe | mas, ok.
    private string ExportToCSVFile(DataTable dtTable)
    {
        var sbldr = new StringBuilder();

        foreach (DataColumn c in dtTable.Columns)
        {
            sbldr.Append(c.ColumnName+ ";");
        }

        sbldr.Append("\r\n");
        foreach (DataRow row in dtTable.Rows)
        {
            foreach (DataColumn column in dtTable.Columns)
            {
                sbldr.Append(Regex.Replace(row[column].ToString(), @"\n|\t|\r", "") + ";");
            }
            sbldr.AppendLine();
        }

        return sbldr.ToString();
    }

Se quiser continuar com ele, e depois escrever o retorno em um arquivo texto:
string csv = ExportToCSVFile(dtTable);
using (TextWriter tw = new StreamWriter(arquivo, false, Encoding.Default))
{
   tw.Write(csv);
   tw.Close();
}

onde: arquivo é uma string com o caminho do arquivo que você irá salvar, e depois disponibilizar para download.

Dependendo do tamanho do conteúdo, acredito que será mais rápido se abrir o Writer dentro do método que gera o csv e ir escrevendo no arquivo ao invés de guardar em uma string.
Se possível, utilize a biblioteca pronta pra isso, certamente o resultado será melhor, evitaria a perda das quebras de linha, tabulação e caracteres de escape dentro de strings.
Answer: Primeiro conselho que te dou, tente adaptar o seu código para que ele receba uma lista tipada no lugar de um DataTable. Porem o exemplo abaixo vai levar em contar que continuara com o DataTable.
Outro ponto, escrever um arquivo CSV envolve dezenas de pequenos detalhes, então faze-lo manualmente, tornará o seu codigo bastante propenso à erros, então aconselho que utilize o CsvHelper.
private void ExportacaoDados(DataSet data, string fileName, int type = 0)
{
    Response.Clear();
    Response.ClearContent();
    Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".txt");
    Response.ContentType = "text/csv";
    ExportToCSVFile(Response.OutputStream, data.Tables[0]);
    Response.Flush();
    Response.Close();
    Response.End();
}

private void ExportToCSVFile(Stream stream, DataTable table)
{
    var encoding = Encoding.GetEncoding("ISO-8859-15");
    using (var writer = new StreamWriter(stream, encoding, 1024, true))
    {
        using (var csv = new CsvHelper.CsvWriter(writer))
        {
            foreach (var column in table.Columns)
            {
                csv.WriteField(column.ColumnName);
            }
            csv.NextRecord();
            foreach (var row in table.Rows)
            {
                for (var i = 0; i < table.Columns.Count; i++)
                {
                    csv.WriteField(row[i]);
                }
                csv.NextRecord();
            }
            writer.Flush();
        }
    }
}

Comment: Acabei de adicionar o CsvHelper, só que na linha csv.WriteField(column.ColumnName); em ColumnName Está dando erro   'object' does not contain a definition for 'ColumnName' and no extension method 'ColumnName' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
Comment: e na linha csv.WriteField(row[i]); em row[i] Cannot apply indexing with [] to an expression of type 'object'
Comment: Este seu DataTable é o que é definido em System.Data?
Comment: Mandou bem no ISO-8859-15... geralmente rodando o sistema em ambiente de lingua inglesa, sendo os dados em portuga, dá um monte de problemas +1 por isso!

Exportação de dados CSV


Borel sigma algebra in topology and R

Question: This is a very basic question about which I am concerned. What is the difference between the Borel $\sigma$-algebra for a topological space and for $\mathbb R$? or they are same?
Answer: For a general topological space $S$ it is the $\sigma$-algebra generated by the open subsets of $S$. The same definition applies to $R$.
In the case of $R$ the Borel sets can be shown to be the smallest $\sigma$-algebra containing the intervals $(-\infty,x]$. This can be proved using the fact that every open set in $R$ is a countable union of open intervals.
Comment: wah it's very quick answer. thank you so much sir :)
Comment: hai, sir. can I find a red-line between Borel $\sigma$-algebra on topological space and Borel $\sigma$-algebra on $\mathbb{R}$?

Borel sigma algebra in topology and R


How can you use the BYPASS output on a BOSS TU-3 Tuner Pedal?

Question: I was wondering, what are the different ways to use the BYPASS output on a BOSS TU-3 shown here:

Is there more than one use? Is there many uses for it ore just one and how helpful are the uses? Any help is appreciated!
Answer: The bypass jack bypasses the switch on the pedal so you when you engage the tuner you don't cut the signal. In a live situation you are usually going to want to be silent when you tune, so you should use the regular output to your amp/effects. Only use bypass if you want the signal to be heard even when you are tuning. This might be useful at home so you can hear yourself tune through the amp.
It just occurred to me one interesting use might be to use the tuner as a splitter- you could have one signal chain going from the "output" to your effects pedals then into a higher-gain amp, while the bypass could go into a clean amp. That way when the pedal is engaged, the "output" won't get any signal (dirty amp is off) but the bypass (clean amp) will be on. When the pedal is off, both amps will get the signal. Of course this is just one possible scenario, you could split it into two different dirty amps, two different clean amps with different effects, split it into two different effects chains, etc. As with all pedals: experiment and use your ears.
Comment: Is it possible that I could have the bypass go to say my in ears or something that only I could hear?
Comment: Possibly.. Assuming you have an extra spot on the mixer/sound desk that is compatible with the signal the pedal puts out.. Never tried it myself, not sure if the signal is line level or closer to instrument level.  Either way, I don't know how great it would sound without going through an amp.
Answer: One use for the bypass is when recording. The pedal then acts as a split box, the output is sent to e.g. an amp, while the bypassed signal could be sent to e.g. a re-amp box, which allows recording of the "clean" signal. This allows the track to be recorded again, with a different amp, the same amp on a different setting, sent to modelling software, something else or an combination of all.
This is how we've used a Boss tuner, especially for bass, where it pays to have the clean signal for extra low frequency goodness.


Finding the derivative of $\frac1{\sqrt{x^2-1}}$

Question:
Use first principles to find the derivative of the following.
$$\frac1{\sqrt{x^2-1}}$$
Comment: Differential Equations?
Answer: I assume first principles means $\frac{d}{dx} f(x) =\lim_{h\rightarrow 0} \frac1h (f(x+h)-f(x))$. Then
\begin{align}
(f(x+h)-f(x)) &= \frac{1}{\sqrt{(x+h)^2-1}} -\frac{1}{\sqrt{x^2-1}} \\
&= \frac{\sqrt{x^2-1}-\sqrt{(x+h)^2-1}}{\sqrt{(x+h)^2-1}\sqrt{x^2-1}} \\
&= \frac{\sqrt{x^2-1}-\sqrt{(x+h)^2-1}}{\sqrt{(x+h)^2-1}\sqrt{x^2-1}} \cdot
\frac{\sqrt{x^2-1}+\sqrt{(x+h)^2-1}}{\sqrt{x^2-1}+\sqrt{(x+h)^2-1}} \\
&=\frac{\left(\sqrt{x^2-1}-\sqrt{(x+h)^2-1}\right)
\cdot\left(\sqrt{x^2-1}+\sqrt{(x+h)^2-1}\right)}{\sqrt{(x+h)^2-1}\sqrt{x^2-1}\cdot \left(\sqrt{x^2-1}+\sqrt{(x+h)^2-1}\right)}
\\ &=
\frac{\left({x^2-1}-{(x+h)^2+1}\right)
}{\sqrt{(x+h)^2-1}\sqrt{x^2-1}\cdot \left(\sqrt{x^2-1}+\sqrt{(x+h)^2-1}\right)}
\\ &=
\frac{-\left(2xh+h^2\right)
}{\sqrt{(x+h)^2-1}\sqrt{x^2-1}\cdot \left(\sqrt{x^2-1}+\sqrt{(x+h)^2-1}\right)}
\end{align}
Now if we consider $\lim_{h\rightarrow 0} \frac1h (f(x+h)-f(x))$ we can see, that the enumerator is $-2x$ while the denominator becomes $\sqrt{x^2-1}\sqrt{x^2-1}\cdot \left(\sqrt{x^2-1}+\sqrt{x^2-1}\right)=2\sqrt{x^2-1}^3$.
Thus
\begin{align}
\frac{d}{dx} f(x) = \frac{-2x}{2\sqrt{x^2-1}^3} = -\frac{x}{\sqrt{x^2-1}^3}
\end{align}
Answer: You should evaluate
$$\lim_{h\to 0} \frac{((x+h)^2-1)^{-1/2}-(x^2-1)^{-1/2}}{h}.$$ in your calculation, you have $(x+h-1)^{-1/2}$ in place of $((x+h)^2-1)^{-1/2}.$
Answer: Ill provide an answer using the limit definition of a derivative, which may or may not be easier to follow
$$
\lim_{h \rightarrow 0}\frac{((x+h)^2-1)^{-1/2}-(x^2-1)^{-1/2}}{h}
$$
$$
\lim_{h \rightarrow 0}\frac{[((x+h)^2-1)^{-1/2}-(x^2-1)^{-1/2}]\times[((x+h)^2-1)^{-1/2}+(x^2-1)^{-1/2}]}{h[((x+h)^2-1)^{-1/2}+(x^2-1)^{-1/2}]}
$$
$$
\lim_{h \rightarrow 0}\frac{((x+h)^2-1)^{-1}-(x^2-1)^{-1}}{h[((x+h)^2-1)^{-1/2}+(x^2-1)^{-1/2}]}
$$
since
$$
\frac{1}{(x+h)^2-1} - \frac{1}{x^2-1} = \frac{h(-h-2x)}{(x^2-1)(h+x-1)(h+x+1)}
$$
$$
\lim_{h \rightarrow 0}\frac{-h-2x}{(x^2-1)(h+x+1)(h+x-1)[((x+h)^2-1)^{-1/2}+(x^2-1)^{-1/2}]}
$$
$$
=\frac{-2x}{2(x^2-1)(x^2-1)\sqrt{x^2-1}}
$$
$$
= \frac{-x}{(x^2-1)^{3/2}}
$$


Array, List, or Dictionary for 3 hierarchy classes

Question: I had a hard time setting the Title for this question, but here goes:
I have Cars, Race, Ticket.
I need to hold around 1.000.000 Tickets. Each Ticket has 10 races. Each Race has 15 cars.
I would need to iterate through Cars and Races. Tickets will be created on the fly. So i'm thinking Tickets as List<>. But how about Cars / Races? 2d-array, dictionary? Or List within List?
myTicket[n][race 1..10][car 1..15].color = "blue"; // ??

Any ideas regarding, performance, and beeing easy to work with?
Thanks in advance! Sorry if the question is a bit unclear....
Answer: You should create some classes, that's what they are there for.
Class Ticket would have a property Races of type List<Race> (or similar).
Each Race would have a property Cars of type List<Car> (or similar).
Comment: Ah, I only had Ticket and Car, as their own classes. Hm, this sounds like a good idea
Answer: Use following data structure
public class Car
{
}

public class Race
{
    public IList<Car> Cars { get; set; }
}

public class Ticket
{
    public IList<Race> Races { get; set; }
}

Comment: Nice, but why IList over List?
Comment: Please see [this](http://stackoverflow.com/questions/8717582/why-use-ilist-or-list)


parse lines without subshell ... how?

Question: i need to parse a number of lines without entering a subshell
cat << EOF | while read -r cmd
sleep 100
sleep 110
sleep 120
EOF

do
    echo $cmd
done

will result:
sleep 100
sleep 110
sleep 120

and it is working, but problem is i need the result outside subshell (be cause i need the results after), tried with for instead of while, but then it won't parse lines but words:
for cmd in `cat << EOF
sleep 100
sleep 110
sleep 120
EOF`

do
  echo $cmd
done

will result:
sleep
100
sleep
110
sleep
120

so, any ideea how to do that ?
Answer: while read -r cmd; do
   echo $cmd
done <<EOF
sleep 100
sleep 110
sleep 120
EOF

Pipes create a subshell.  I/O redirection (including here-documents) doesn't.
Comment: code looks a little ... kinky :P, but thank you ! it is working and get the job done ;)

parse lines without subshell ... how?


Sublinear Inequality

Question: For $f(x,y)=x^2/y$, is it possible to prove that $$f(x_1,y_1)-f(x_2,y_2)\le Cf(x_1-x_2,y_1-y_2)$$
or
$$|f(x_1,y_1)-f(x_2,y_2)|\le C|f(x_1-x_2,y_1-y_2)|$$ with $0< x_k,y_k \le M<\infty$, $k=1,2$, where $C$ is a positive constant?  Thanks for any suggestions.
Answer: The following is true
\begin{eqnarray*}
0 \leq (x_1 y_2 - x_2 y_1)^2.
\end{eqnarray*}
Rearrange & create some terms
\begin{eqnarray*}
&x_1^2y_1y_2 - x_1^2y_2^2 &-x_2^2y_1^2 +x_2^2y_1y_2  &\leq x_1^2y_1y_2 - 2x_1x_2y_1y_2 +x_2^2y_1y_2, \\
&x_1^2 y_2(y_1-y_2)&-x_2^2y_1(y_1-y_2) &\leq (x_1-x_2)^2 y_1 y_2.
\end{eqnarray*}
Now assume $y_1 > y_2 >0 $,so we can divide by $y_1y_2(y_1-y_2)$ and we have
\begin{eqnarray*}
\frac{x_1^2}{y_1}  -\frac{x_2^2}{y_2}  \leq \frac{(x_1-x_2)^2 }{y_1- y_2} .
\end{eqnarray*}
Comment: This is an excellent answer.  Thank you so much!

Sublinear Inequality


disabling extra message after changing to new directory

Question: Whenever directory is changed, it is displaying the new directory name:
<code># cd /home/
Directory: /home/
# cd ~
Directory: /root
</code>
How to disable it?
We are logging into csh. We already verified /etc/csh.cshrc, /etc/profile, /etc/csh.login.
Answer: try looking in the user folder instead of only looking for the system wide files.
if you are logged in as root:
<code>/root/.cshrc
</code>
or
<code>/home/[USERNAME]/.cshrc
</code>
i do not know for additional csh files similiar to bash files (.bash_login .bash_logout) in the user folder, so you might need to check the existence with ls -a for showing the "hidden" . files.


quickfixJ Getting Session settings from the session object

Question: I would like to customize the sent Login message in the toAdmin method by adding the Username and Password values from the current session settings. Something like that:
@Override
public void toAdmin(Message message, SessionID sessionId) {
    Header header = message.getHeader();
    if (!header.isSetField(MsgType.FIELD) || !header.getString(MsgType.FIELD).equals(MsgType.LOGON))
    {
        // not a logon message: do not modify it
        return;
    }

    Session session = Session.lookupSession(sessionId);

    message.setField(new Username(seesion.getSettingValue("Username")));
    message.setField(new Password(seesion.getSettingValue("Password")));
}

The getSettingValue method doesn't exist. Is there any way to do this in quickfixJ? BTW this is possible in quickfixn.
Comment: Starting with QuickFIX/J 2.2.0 you are able to pass `LogonTag` session settings to have these tags set on the Logon message that is sent out. Also see https://stackoverflow.com/a/62445873/4962355
Answer: I assume you mean that you want to define custom Username/Password settings in your config file.  (QF does not have these built-in.)
This link will show you how to use custom settings.
http://www.quickfixj.org/confluence/display/qfj/Using+Custom+Settings
(Ignore the bit in the prose about getSessionSettings(); this method does not appear to actually exist in the current build.)
In case that page goes down, in a nutshell the process is this:
Somehow give your MessageCracker app a reference to your SessionSettings object (whether by constructor or get/set or however).
In your toAdmin(), do something like this:
final String msgType = msg.getHeader().getString(MsgType.FIELD);
if(MsgType.LOGON.compareTo(msgType) == 0)
{
    msg.setString(quickfix.fields.Username.FIELD,
      mySettings.getString(sessionID, "Username");
    msg.setString(quickfix.fields.Password.FIELD,
      mySettings.getString(sessionID, "Password");
}

(I haven't compiled this code; please let me know if I have a syntax error and I'll fix it.)
I literally just added the C# equivalent to the QF/n User FAQ yesterday.  You must be on the QF/n mail list, or else just have really great timing.
(I should probably add this to the QF/j User FAQ as well.)
Answer: You can do something similar to this in QuickFIX/J. Take a look at the QFJ wiki for an example. Rather than accessing the session settings through the Session you can provide a SessionSettings instance to your Application implementation and then use that object to get your custom settings.
Answer: Are you sure you are looking in the right direction. I just checked the Session  class in the QuickfixJ documentation. It doesn't have any data members username or password. So you cannot extract any values, which it doesn't contain.
Or are you using your special version of Session class ? I don't believe Session should be holding any of those data either, it is unecessary and open to malicious use. I am not sure how the same side can have multiple userid and passwords to connect to another side(same one and I am assuming so because you are trying to use the same session id to fetch the user id and password), opens up all issues once again.
So if you have a single userid/password, better take it from your DB or other source you might be using rather than trying to fetch it from the session.
Comment: My question here is more about getting session settings from the session object. let's put username/pwd aside, how to get LongonTimeout or HeartBtInt from the session object? You can do so in .NET as I mentioned. Is there a way to get any session settings from a session object?


Need to find correlation between two entities

Question: I have a scenario where I have a User which likes 10 different sports and there is another user which likes 20 different sports. I need to find the correlation between them. What kind of correlations can be used in such a scenario. Any kind of guide would be helpful. I tried with Pearson correlation but was not helpful. I would like to program using MATLAB. Thanks in advance.
Comment: yes, i have a matrix for individual users where columns are different sports and the one they like have a value one.
Comment: Exactly what do you plan to do with this correlation once you compute it?
Comment: We would deduce whether the two users according to their sports interest are related or not. Something like If I like soccer and football, and some one likes just football, still we both are related by some percentage. So i want to calculate that percentage of similarity
Comment: Do you have a large matrix where rows are users and sports are columns and values are measures how much someone likes a sport?
Answer: This is like inter-rater reliability. The code here should do it.
Comment: The OP said the number of liked objects is not the same for the two raters. How would you apply Cohen's $\kappa$ in this case?
Comment: @chi I was thinking of the users each rating each of a few dozen sports as one of two levels (like or not). Does that answer your question? If not, I should probably review how Cohen's $\kappa$ works.
Answer: If your goal is to measure similarity between individual users or groups of users you may use similarity or distance measures used in cluster analysis, biclustering or multidimensional scaling. In situations where you need such a measure the above techniques themselves may be useful, too.
Comment: Or correspondence analysis


How do I add a Javascript library to a field formatter?

Question: I'm trying to include a Javascript gallery (jQuery lightGallery) on my new Drupal 8 site and wrote a field formatter for this purpose.
Now I need to add the jQuery lightGallery to pages using this field formatter and call the library when the page is ready. I am confused about how I am supposed to do this, though.
I defined the library in the module containing my field formatter, but I'm not sure how I attach it only on sites that contain the field.
The documentation of the library uses the jQuery $(document).ready function to call the libary, how would that work inside a Drupal module?
Answer: In your formatter's viewElements
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
  $elements[$delta] = array(
    '#theme' => 'theme_name_if_any',
    '#variablenametobepassed' => $this->viewValue($item) * 20, // any other preprocessing
    '#attached' => array('library'=> array('module_name/library_name')),
  );
}

return $elements;
}

Answer: So for Drupal 8, in order to add JS or CSS files you first needs to defined a library that defines which files should be include. You need to create a module_name.libraries.yml file. That file could look something like this:
library_name:
  js:
    js/path.to.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

There is documentation about the libraries files. Basically you list the files you want to include (along with some optional settings) and add depencies to other libraries that your library depend on if any (like jQuery).
After your library has been defined (remember to clear cache), you should add the library where needed. In your case that would be the form definition. You can add the library to any render array and Drupal will find them and add the needed js files to the page.
To add a library all you need to do this:
$render_array['#attached']['library'][] = 'module_name/library_name';

This can be done anywhere in the render array.
There is detailed documentation about this on Drupal.org documetation area.
Comment: You were correct. This should go into viewElements(). You could attach like here.

     public function viewElements(FieldItemListInterface $items, $langcode) {
        $elements = [];
        foreach ($items as $delta => $item) {
          $elements[$delta] = array(
            '#theme' => 'xxxxx',
            '#ratingvalue' => $this->viewValue($item) //Any other processing,
            '#attached' => array('library'=> array('module_name/library_name')),
          );
        }

    return $elements;
  }

@MadScientist
Comment: Thanks for the answer, but I'm having trouble finding the correct place to add the `#attached` to the render array. I tried it in the viewElements function from the ImageFormatter I used as a base, but that doesn't work. I can't see a place where I have access to the render array in a field formatter.


Piano pedaling notation

Question: I have been playing piano for several years, but I never got a particular lesson on pedaling. I know the basics: for most romantic pieces, the point is to clean the pedal (with "clean", I mean raise and press again) at the moment where the chords change. For what I have heard, that is the key: release the pedal when harmony changes and press it back again. But then I started learning about how pedal is notated. Consider this example from Chopin's nocturne Op. 9 No. 1:

As far as I know, there are essentially two symbols here, the Ped and the star; where Ped means "press the pedal", and star means "release the pedal. If this is the case, then, in this example, the notation does not coincide with the description I learnt; there would be two options here (measure 2):
Method 1) Following the notation: Pedal is pressed in beat 1 and released in second half of beat 3, pressed back again in beat 4
Method 2) Release-press method: Pedal is pressed in beat 1 and released in beat 4, pressed back again just afterwards.
So is my interpretation of the notation wrong (i.e. is the notation describing the method 2)) or is the notation saying what method 1) says?
Hope this question makes sense, thanks in advance!
Answer: I think this sort of pedalling instruction is simplified. It has to be, to be able to be printed tidily.
The basic pedal operation is to use it when any harmony is static - in other words don't pedal over different chord sounds. That needs clarification.
For me, play the first note, and before letting go of the key, press pedal. Hold until the harmony changes (here on the 7th note), and, as that 7th note is played, change pedal - lift and re-press quickly, before that key has been released. That then gets repeated in this example twice per bar, and will smooth the two halves of the bars nicely. As well as the transitions between bars.Hence 'simile'. In the 2nd full bar, the two halves have the same harmony, but it seems Chopin preferred a re-pedal in the middle anyway.
It can't be printed as such - there's no room - but that's what should happen.
Comment: @Clockwork - seems right. Listen to what happens, and if it sounds clean, and not muddy, it's good.
Comment: @Clockwork - that's the primary use of the sustain pedal - to smooth out the transition between notes, giving fingers chance to leave the keys just pressed, and get to the next, with no perceivable gap between, as would be the case with no pedal. Check out *sostenuto* pedal also, if available in your part of the world, which, let's face it could be anywhere. Not sure the state of Flux is a good one to be in, but that's anywhere and everywhere right now! Or am I just dyslexic..?
Comment: @Clockwork - you like in Europe? There's still time to change that. In Europe, most 3 pedal pianos have the middle used as a practice pedal, unlike in U.S., where the middle is sostenuto. Other states to consider may be Despair, Panic, Confusion...  All of which are probably familiar.
Comment: This solved my issue perfectly, thank you very much! The thing is when I took piano lessons, I was told the intuition to use pedal in general, and suddenly started to encounter this notation which made it all way more confusing. The point is that this notation cannot express the raise-press action really precisely.
Comment: Just to be 100% sure: you basically press the notes, release the pedal and press it down again, still with the notes pressed, where it's marked "Ped.", instead of releasing it before the notes and pressing down again as you play the notes?
Comment: Alright, thanks. That's basically what I was doing, because I thought it felt better to sustain the notes until I press the new ones, rather than cut it short before sustaining the new ones.
Comment: @Tim Nah, it's a fake state I took out from a game. I live in Europe. My upright piano doesn't have a sostenuto though (it has a training pedal instead).
Answer: In the middle of the first full bar I would release the pedal as I start to play the notes of the 4th crotchet beat and re-apply it immediately. Even when there is no previous pedalling I would begin the pedal after the beginning of the note, rather than with the beginning of the note.
The reasoning is that by lifting the pedal at the start of the note rather than earlier, the pedal helps maintain legato leading into that note. Applying the pedal later, instead of at the beginning of the note avoids sustaining sound from the previous note, by allowing time for it to be stopped by the dampers.
Comment: Doing that guarantees the F will be held over. Not a problem, given there's an F in the second half, but not a good idea if the harmony doesn't include an F later.
Comment: No, the pedal is released as the F is released and the following note played. Then the pedal is applied after the start of the note, allowing time for the F strings to stop sounding.
Answer: The notation for pedal is much more loose than the notation for the notes themselves. Pedaling varies greatly with the piano and even with the room. Therefore, don't see the Pedal in the score as something that you have to follow strictly. When the composer wants something unusual, or wants the pedal notation to be followed strictly, the composer writes explicitly about this.
That said, your intuition is right. Usually, press the pedal if you want this effect, and release it when harmony changes. This is also what is in method 1 above. The star is not on the last note of the previous beat, it is just before the the note with the indication Ped.
Comment: Sadly not so half way through the bar - star *is* under the note - and shouldn't be!

Piano pedaling notation


CakePHP: shortcomings with indirectly associated models

Question: I'm having some issues with dealing with indirectly associated models in cakephp.  My current model setup is as follows:
<code>Deliveries hasOne License
License belongsTo Delivery
License hasAndBelongsToMany Product (and vice-versa)
License hasAndBelongsToMany ProductOption (and vice-versa)
</code>
I'm trying to save information about ALL of these models inside ONE form.  The shortcomings I'm running into are the following:

The form helper only seems able to see the field type one level deep.
saveAll() only seems able to save records one level deep (for multiple model forms).

I'm searching everywhere for the solutions to these issues, but since I'm new to CakePHP, I'm not sure what the newest methods or "correct" methods are for dealing with these issues.
Any advice is much appreciated. Thank you all!
EDIT: I've posted code to my failed attempt here: http://bin.cakephp.org/saved/58501
Comment: Could you post some code from your form? Also what does License mean in this case?
Comment: My company typically makes a physical "delivery" of a software "license", which lets the customer run different types of software "products" that they purchased, along with the purchased "product options".
Answer:
saveAll() only seems able to save records one level deep (for multiple model forms).

I have stumbled across this limitation in the past and chose, at the time, to work around it by breaking up my form into multiple smaller forms.
One thing to bear in mind when using saveAll and InnoDB tables is that you get atomic transactions, as Cake will perform a rollback if it is unable to commit changes to the database.
So, while you can obviously work around the issue with a few lines of your own code (since Cake's saveAll one-liner doesn't live up to expectations), you would have to spend more time if transactions were a requirement.
Answer: Hi I know this is an old post but thought I'd post this to help others, As of CakePHP 2.1 you can save multiple levels of model association using an option on the call the saveAll(), more details here: http://book.cakephp.org/2.0/en/appendices/new-features-in-cakephp-2-1.html#model-saveall-model-saveassociated-model-validateassociated
Example:
<code>$this->MyModel->saveAll($this->request->data, array('deep'=>true));
</code>
As for the FormHelper limitation, I'm as lost as you are, I will probably resort to setting the input types manually as my fields don't need too much validation.


How to perform NAT with inside interface as bridge

Question: (dublicate question from AskUbuntu) I have a following network diagram:
network diagram
192.168.0.0/24 network with 4 web servers (.1,.2,.3,.4).
There are 2 Ubuntu 14.04 (VM1 and VM2) in it.
They have 2 physical interfaces both (eth0 and eth1). And a L2TP ethernet tunnel, configured that way:
root@vm1:~# modprobe l2tp_eth
root@vm1:~# ip l2tp add tunnel tunnel_id 1000 peer_tunnel_id 2000 encap udp local 10.0.0.1 remote 10.0.1.1 udp_sport 6000 udp_dport 5000
root@vm1:~# ip l2tp add session tunnel_id 1000 session_id 3000 peer_session_id 4000

root@vm2:~# modprobe l2tp_eth
root@vm2:~# ip l2tp add tunnel tunnel_id 2000 peer_tunnel_id 1000 encap udp local 10.0.1.1 remote 10.0.0.1 udp_sport 5000 udp_dport 6000
root@vm2:~# ip l2tp add session tunnel_id 2000 session_id 4000 peer_session_id 3000

On every VM I have a brigde configured between eth1 (connected to 192.168.0.0 net) and l2tpeth0 interface (the tunnel). In /etc/network/interfaces of VM2:
auto l2tp
iface l2tp inet static
        address 192.168.0.6
        netmask 255.255.255.0
        network 192.168.0.0
        broadcast 192.168.0.255
        bridge_ports l2tpeth0 eth1
        bridge_stp off
        bridge_fd 0
        bridge_maxwait 0

Now a server at 192.168.0.5 sends a packet to remote adress of 188.8.131.52. It's path is shown with orange dotted line (it gots captured by brigde and sent via tunnel).
My task is to make it follow blue dotted path - got NATted on VM1 and go through eth1 interface.
On VM2 I have a simple NAT configured:
iptables -t nat -A POSTROUTING -o eth0 -j LOG
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

But it doesn't help - I don't see packets in questing in /var/log/syslog (there are some though).
Just in case:
root@vm2:~#  cat /proc/sys/net/bridge/bridge-nf-call-iptables
1
root@vm2:~# cat /proc/sys/net/ipv4/ip_forward
1

So the question is how to NAT packet destined only to certain destinations? I'm okay that for example traffic from 192.168.0.4 to 192.168.0.1 uses tunnel and doesn't get NATted (that why I have a tunnel in the first place)
Answer: The solution was very simple. The configuration showed was ok. But 192.168.0.5 and .6 VMs were not using configured gateway 192.168.0.6 and sent L2 frames to 192.168.0.254 thus not reaching l2tp interface IP stack. These are not standard appliances but Cisco WMS.


How to prove the series ${S_n}$ converges where $S_n$ is $\sum_{k=1}^n\frac{1}{\sqrt{k\cdot n}}$ and what is the limit?

Question: How to prove the series ${S_n}$ converges where $S_n$ is
$$\sum_{k=1}^n\frac{1}{\sqrt{k\cdot n}}$$
and what the limit is?
I thought it was $p$-series where $p=1/2<1$ so it must diverge but according to the question, it must converge, I'm not sure about which convergence test I can use.
Any tip is much appreciated
Comment: Riemann sum. ${}{}{}{}$
Comment: $S_n$ is a sequence, not a series. The limit is $2$.
Comment: Related https://math.stackexchange.com/q/2986785/505767
Answer: By Stolz-Cesàro theorem ($*/\infty$ case):
\begin{align}
& \lim_{n \to \infty}\frac{\sum_{k = 1}^n\frac{1}{\sqrt{k}}}{\sqrt{n}} =
\lim_{n \to \infty}\frac{\frac{1}{\sqrt{n + 1}}}{\sqrt{n + 1} - \sqrt{n}}
= \lim_{n \to \infty}\frac{1}{\sqrt{n + 1}}(\sqrt{n + 1} + \sqrt{n}) \\
=& 1 + \lim_{n \to \infty}\sqrt{\frac{n}{n + 1}} = 2.
\end{align}


Constructor and property namespaces bringing up "URI is not registered" error

Question:
As you can see, I've declared a namespace for the constructor namespace, however it says the URI is not registered. I have a few ideas how to fix them, but I'm not sure how to implement them.

I could manually register the URI, however, I would need a matching .xsd file for that, and looking around, I can't find one for that specific namespace.
I tried ignoring the error and seeing if that would fix it, but when I did that the XML parser didn't recognize the elements (should have seen that coming)

Not sure what's going on here. Every single example I've found online has this exact line copied in order to make use of the c & p namespaces (this error also happens for the p namespace). Any help would be appreciated.
Answer: You need to define this schema location in Settings (Preferences on macOS) | Languages & Frameworks | Schemas and DTDs → External Schemas and DTDs settings:

It may be a directory a XSD or DTD file in one of you library jars or file on the file system.


Can't add an image extension to the field_image of the Article content type

Question: I need to upload an image with the webp extension and add it as the main image of a content item with the "Article" content type. Since its field_image doesn't have the webp extension by default, I've added the extension to the "Allowed file extensions" input at the managing tab of the field_image.
When I check the row with the name='field.field.node.article.field_image' in the config DB table, I see that the extension was successfully added to the data array under the keys ['settings']['file_extensions'].
But when I try to upload and add an image with the webp extension on the editing page of the article I still receives the error that only png, gif, jpg and jpeg are allowed.
How to resolve the problem?
ps. Drupal 8.7.3
Answer: Drupal 8.7 does not support WebP.
You can:

Upgrade to Drupal 9.2+, which supports WebP (recommended, see more info in this question)
Use the WebP module
Use the ImageAPI Optimize WebP module (more complicated to set up than WebP module but lets you do complicated chains of processing if you have a site that needs to do a lot of work with images)


Como criar um tabuleiro de tamanho determinado pelo usuário e apresentá-lo como texto usando python?

Question: Estou tentando criar um programa em Python 3.6.1 que cria um tabuleiro de acordo com o tamanho digitado pelo usuário final e imprime o resultado no shell.
Ele precisa ser apresentado como texto, e não pode utilizar nenhuma biblioteca.
Por mais que a biblioteca seja interna.
Exemplo: se o usuário digitar um tabuleiro com 10 linhas e 15 colunas. O programa  teria que gerar esse tabuleiro 10x15. Sendo que todos os valores dele devem ser células preenchidas por strings. Porque, posteriormente, ao usuário inserir o valor "P", por exemplo, ele irá alterar uma célula pré-definida por mim.
Em seguida o tabuleiro seria impresso novamente com o valor da célula pré-definida anteriormente por mim.
EX:
O usuário insere as informações iniciais:
insira a quantidade de linhas: 10
insira a quantidade de colunas: 15
o tabuleiro inicialmente seria assim:

  0123456789.....
0 XXXXXXXXXXXXXXX
1 XXXXXXXXXXXXXXX
2 XXXXXXXXXXXXXXX
3 XXXXXXXXXXXXXXX
4 XXXXXXXXXXXXXXX
5 XXXXXXXXXXXXXXX
6 XXXXXXXXXXXXXXX
7 XXXXXXXXXXXXXXX
8 XXXXXXXXXXXXXXX
9 XXXXXXXXXXXXXXX

Em seguida, o usuário iria inserir P nas coordenadas 3x3, por exemplo:
insira o que deseja na linha 3 coluna 3: P <<<< usuário digitou P
Após isso, o tabuleiro seria impresso novamente, com o seguinte resultado:

   0123456789.....
 0 XXXXXXXXXXXXXXX
 1 XXXXXXXXXXXXXXX
 2 XXXXXXXXXXXXXXX
 3 XXXPXXXXXXXXXXX #o P seria inserido nessa linha. Exatamente onde foi mandado.
 4 XXXXXXXXXXXXXXX
 5 XXXXXXXXXXXXXXX
 6 XXXXXXXXXXXXXXX
 7 XXXXXXXXXXXXXXX
 8 XXXXXXXXXXXXXXX
 9 XXXXXXXXXXXXXXX

Alguém sabe me dizer como fazer isso?
A parte das perguntas ao usuário, eu sei como fazer.
Meu problema é com o tabuleiro. Não faço nem idéia de como deixar como falei.
Criar uma matriz seria uma boa solução? Ou existe uma forma menos complicada?
já tentei de várias formas gerar esse tabuleiro, mas, sem sucesso.
Não sei se estou errando na lógica ou na sintaxe, pois comecei a programar com python há pouco tempo.
pesquisei bastante sobre uma possível solução, mas não encontrei informações claras.
Eu tenho mais experiência com php atualmente.
Toda ajuda é bem-vinda.
Desde já, obrigado.
PS: O resultado mais próximo do que preciso que consegui fazer foi esse:
linhas = int(input('insira a quantidade de linhas:'))
colunas = int(input('insira a quantidade de colunas:'))
celula = "X"

for a in range(linhas):
    print(celula*colunas)

Ele gera tudo aparentemente como preciso.
Mas não é bem assim que o resultado final deveria ficar.
Eu preciso que cada X impresso na tela seja um "espaço" dinâmico, onde cada um pode ser alterado posteriormente com qualquer outro valor de acordo com as coordenadas. Ex: F na linha 4 coluna 7 .
Não estou sabendo fazer isso.
Answer: O que fiz foi algo mais complexo, e com algumas coisas desnecessárias, mas que obtém o mesmo resultado.
Por conta dos espaços, o tabuleiro só poderá ter 56 colunas (acho que pode aumentar essa quantia se o monitor for maior, senão fica tudo bugado).
Coloquei espaços por que após chegar na 10ª coluna e adiante não tem como por "10" em cima de um único "X"
linhas = int(input('Quantas linhas? : '))
colunas = int(input('Quantas colunas? : '))

print('\n    |  ',end='')
for i in range(0,colunas):
        if i > 9:
                print(str(i)+' ', end='') #Retirei um espaço para que a posição dos numeros não fique errada
        else:
                print(str(i)+'  ', end='')
#print('|','\n   |'+'-'*3+'-'*((colunas*3)-1)+'|') #Um traço que entre os numeros da coluna
print('|')
for i in range(0,linhas):
        if i >= 10 and i < 100:
                print(i,' |'+'  X'*colunas,' |') #Linhas maiores que 9 e menores que 100 (10-99)
        elif i >= 100:
                print(i,'|'+'  X'*colunas,' |') #Linhas maiores que 9 e menores que 100 (10-99)
        else:
                print(i,'  |'+'  X'*colunas,' |') #Linhas menores que 10

while 1:
        local_c = int(input('\nQual local da coluna? : '))
        if local_c > colunas-1:
                print('local inválido.\n')
                continue
        break

while 1:
        local_l = int(input('Qual local da linha? : '))
        if local_l > linhas-1:
                print('local inválido.\n')
                continue
        break

print('\n    |  ',end='')
for i in range(0,colunas): #Numeros da coluna
        if i > 9:
                print(str(i)+' ', end='') #end='' serve para impedir a quebra de linha "\n"
        else:
                print(str(i)+'  ', end='')
print('|')
for i in range(0,linhas):
        if i == local_l: #Linha que será alterada
                c1 = local_c
                c2 = (colunas-c1)-1
                if i > 9 and i < 100:
                        print(str(i),' |'+'  X'*c1,' P'+'  X'*c2,' |') #Linhas maiores que 9 e menores que 100 (10-99)
                elif i >= 100:
                        print(str(i),'|'+'  X'*c1,' P'+'  X'*c2,' |') #Linhas maiores que 9 e menores que 100 (10-99)
                else:
                        print(i,'  |'+'  X'*c1,' P'+'  X'*c2,' |') #Linhas menores que 10
        elif i >= 10 and i < 100:
                print(i,' |'+'  X'*colunas,' |') #Linhas maiores que 9 e menores que 100 (10-99)
        elif i >= 100:
                print(i,'|'+'  X'*colunas,' |') #Linhas maiores que 99
        else:
                print(str(i),'  |'+'  X'*colunas,' |') #Linhas menores que 10

saída:
>>> Quantas linhas? : 10
>>> Quantas colunas? : 10
>>>
>>>     |  0  1  2  3  4  5  6  7  8  9  |
>>> 0   |  X  X  X  X  X  X  X  X  X  X  |
>>> 1   |  X  X  X  X  X  X  X  X  X  X  |
>>> 2   |  X  X  X  X  X  X  X  X  X  X  |
>>> 3   |  X  X  X  X  X  X  X  X  X  X  |
>>> 4   |  X  X  X  X  X  X  X  X  X  X  |
>>> 5   |  X  X  X  X  X  X  X  X  X  X  |
>>> 6   |  X  X  X  X  X  X  X  X  X  X  |
>>> 7   |  X  X  X  X  X  X  X  X  X  X  |
>>> 8   |  X  X  X  X  X  X  X  X  X  X  |
>>> 9   |  X  X  X  X  X  X  X  X  X  X  |
>>>
>>> Qual local da coluna? : 5
>>> Qual local da linha? : 5
>>>
>>>     |  0  1  2  3  4  5  6  7  8  9  |
>>> 0   |  X  X  X  X  X  X  X  X  X  X  |
>>> 1   |  X  X  X  X  X  X  X  X  X  X  |
>>> 2   |  X  X  X  X  X  X  X  X  X  X  |
>>> 3   |  X  X  X  X  X  X  X  X  X  X  |
>>> 4   |  X  X  X  X  X  X  X  X  X  X  |
>>> 5   |  X  X  X  X  X  P  X  X  X  X  |
>>> 6   |  X  X  X  X  X  X  X  X  X  X  |
>>> 7   |  X  X  X  X  X  X  X  X  X  X  |
>>> 8   |  X  X  X  X  X  X  X  X  X  X  |
>>> 9   |  X  X  X  X  X  X  X  X  X  X  |

Espero que eu tenha te ajudado, se quiser, posso simplificar o código.
Answer: Veja se isso te ajuda, comentei o código para te dar uma noção do que está acontecendo.
Minha sugestão é que vá rodando parte a parte para entender o funcionamento
Código:
#pergunta a qtd de linhas e colunas para o usuario
lins = int(input("Insira o num de linhas: "))
cols = int(input("Insira o num de colunas: "))

#cria uma lista com o "X" aparecendo tantas vezes quando o nºde colunas
table = []
for i in range(lins):
    table.append(list('X'*cols))

#une as listas sem nenhum espaco para mostrar na tela
for line in table:
    print(''.join(line))

#pergunta qual linha e coluna deseja alterar
lin_alterar = int(input("Qual linha deseja alterar?: "))
col_alterar = int(input("Qual coluna deseja alterar?: "))

#qual o valor novo a ser inserido
vlr_novo = 'P'

#altera o item da posicao escolhida para o vlr_novo
table[lin_alterar - 1][col_alterar - 1] = vlr_novo

#une as listas sem nenhum espaco para mostrar na tela
for line in table:
    print(''.join(line))

Output:
>>> Insira o num de linhas: 5
>>> Insira o num de colunas: 10
>>> XXXXXXXXXX
>>> XXXXXXXXXX
>>> XXXXXXXXXX
>>> XXXXXXXXXX
>>> XXXXXXXXXX
>>> Qual linha deseja alterar?: 3
>>> Qual coluna deseja alterar?: 2
>>> XXXXXXXXXX
>>> XXXXXXXXXX
>>> XPXXXXXXXX
>>> XXXXXXXXXX
>>> XXXXXXXXXX

Na essência, sua tabela padrão nesse exemplo tem o seguinte formato:
[['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']]

Ela é uma lista contendo M listas com N itens, onde:

M = nº linhas
N = nº colunas


Simple linear regression output interpretation

Question: I have run a simple linear regression of the natural log of 2 variables to determine if they correlate. My output is this:
R^2 = 0.0893

slope = 0.851

p < 0.001

I am confused. Looking at the $R^2$ value, I would say that the two variables are not correlated, since it is so close to $0$. However, the slope of the regression line is almost $1$ (despite looking as though it's almost horizontal in the plot), and the p-value indicates that the regression is highly significant.
Does this mean that the two variables are highly correlated? If so, what does the $R^2$ value indicate?
I should add that the Durbin-Watson statistic was tested in my software, and did not reject the null hypothesis (it equalled $1.357$). I thought that this tested for independence between the $2$ variables. In this case, I would expect the variables to be dependent, since they are $2$ measurements of an individual bird. I'm doing this regression as part of a published method to determine body condition of an individual, so I assumed that using a regression in this way made sense. However, given these outputs, I'm thinking that maybe for these birds, this method isn't suitable. Does this seem a reasonable conclusion?
Comment: The [Durbin-Watson statistic](http://en.wikipedia.org/wiki/Durbin%E2%80%93Watson_statistic) is a test for serial correlation: that is, to see whether *adjacent error terms* are mutually correlated.  It says nothing about the correlation between your X and your Y!  Failing the test is an indication that the slope and p-value should be interpreted with caution.
Comment: I would just like to add a slope can be very significant (p-value<.001) even though the relationship is weak, especially with a large sample size.  This was hinted at in most of the answers as that the slope (even if it's significant) says nothing about the strength of the relationship.
Comment: Ah, ok. That makes a little more sense than whether the two variables themselves are correlated...after all, I thought that's what I was trying to find using the regression. And that failing the test indicates I should be cautious interpreting the slope and p-value makes even more sense in this case! Thanks @whuber!
Comment: You need $n$ to determine the strength of the relationship. Also see http://stats.stackexchange.com/a/265924/99274.
Answer: The estimated value of the slope does not, by itself, tell you the strength of the relationship. The strength of the relationship depends on the size of the error variance, and the range of the predictor. Also, a significant $p$-value doesn't tell you necessarily that there is a strong relationship; the $p$-value is simply testing whether the slope is exactly 0. For a sufficiently large sample size, even small departures from that hypothesis (e.g. ones not of practical importance) will yield a significant $p$-value.
Of the three quantities you presented, $R^2$, the coefficient of determination, gives the greatest indication of the strength of the relationship. In your case, $R^{2} = .089$, means that $8.9\%$ of the variation in your response variable can be explained a linear relationship with the predictor. What constitutes a "large" $R^2$ is discipline dependent. For example, in social sciences $R^2 = .2$ might be "large" but in controlled environments like a factory setting, $R^2 > .9$ may be required to say there is a "strong" relationship. In most situations $.089$ is a very small $R^2$, so your conclusion that there is a weak linear relationship is probably reasonable.
Comment: @macro Excellent answer, but I would stress (for those new to this subject) that R^2 can be very low even with a strong relationship, if the relationship is nonlinear, and particularly if it is nonmonotonic. My favorite example of this is the relationship between stress and exam score; very low stress and very high stress tend to be worse than moderate stress.
Comment: @Macro (+1), fine answer.  But how does the "strength of the relationship" depend on the "size of the intercept"?  AFAIK the intercept says nothing at all about correlation or "strength" of a linear relationship.
Comment: @macro Yeah, your answer was good, but I have worked with people who don't know a lot of statistics, and I've seen what happens ... sometimes what we say is not what they hear!
Comment: Thanks Macro. Very helpful answer. I'm glad you included the part about what, exactly, the p-value is testing. It makes a lot of sense that the p-value would be so low considering how close to 1 the slope is. It seems to me, in light of your answer and @jedfrancis', the r^2 value describes that 'cloud' of data points around the line of regression. Excellent! That's much more clear now!
Comment: @whuber, you're right - the intercept is irrelevant and definitely doesn't change the correlation - I was thinking about the regression function $y = 10000 + x$ vs. $y = x$ and thinking somehow of the second one being a stronger relationship (all else held equal), since a greater amount of the magnitude of $y$ was due to $x$ in the latter case. Doesn't make much sense now that I think about it. I've edited the post.
Comment: @Macro It's hard to see how $R^2$ would be a "measure of linear dependence" because by definition *all* dependence in these regression models is linear in the parameters. For instance, if $y=\alpha+\beta x+\gamma x^2+\varepsilon$, $R^2$ could be high due to the *quadratic* relationship between $x$ and $y$.  It seems to me rather that $R^2$ is trying to address, in a quantitative way, the split of a response into a sum of deterministic and stochastic terms. It's even a stretch to conceive of it as quantifying a "strength of the relationship"; it seems more a measure of residual variance.
Comment: @whuber - absolutely. But, the question was posed in the context of simple linear regression, which doesn't include a quadratic term like that. In the multiple regression setting I believe it is interpreted as the proportion of variation explained by a linear relationship with the predictors as a set, where $x^{2}$ is just another one of those predictors; I believe $R^2$ equals the squared correlation between the true values and the fitted values in multiple regression.
Comment: @Macro Excellent points.  I just didn't want to let the issue go unclarified, because undoubtedly people will be referring to your reply in the future.
Answer: The $R^{2}$  tells you how much variation of the dependent variable is explained by a model. However, one can interpret the $R^{2}$ as well as the correlation between the original values of the dependent variable and the fitted values. The exact interpretation and derivation of the coefficient of determination $R^{2}$ can be found here.
The proof that the coefficient of determination is the equivalent of the Squared Pearson Correlation Coefficient between the observed values $y_{i}$ and the fitted values $\hat{y}_{i}$ can be found here.
The $R^{2}$ or coefficient of determination indicates the strength of your model in explain the dependent variable. In your case, $R^{2}=0.089$. This that your model is able explain 8.9% of variation of you dependent variable. Or, the correlation coefficient between your $y_{i}$ and your fitted values $\hat{y}_{i}$ is 0.089. What constitutes a good $R^{2}$ is discipline dependent.
Finally, to the last part of your question. You cannot get the Durbin-Watson test to say something about the correlation between you dependent and independent variables. The Durbin-Watson test tests for serial correlation. It is conducted to examine whether your error terms are mutually correlated.
Answer: The $R^2$ value tells you how much variation in the data is explained by the fitted model.
The low $R^2$ value in your study suggests that your data is probably spread widely around the regression line, meaning that the regression model can only explain (very little) 8.9% of the variation in the data.
Have you checked to see whether a linear model is appropriate? Have a look at the distribution of your residuals, as you can use this to assess the fit of the model to your data. Ideally, your residuals should not show a relation with your $x$ values, and if it does, you may want to think of rescaling your variables in a suitable way, or fitting a more appropriate model.
Comment: Welcome to our site, @jed, and thanks for your reply!  Please note that the slope itself says almost nothing about the correlation, apart from its sign, because correlation does not depend on the units in which X and Y are measured but the slope does.
Comment: @whuber is saying that the value of the **slope** does **not** tell you anything about the strength of the association unless variables are standardized. See shabbychefs answer.
Comment: Thanks @jed. Yes, I'd checked the normality of the residuals, and all was well. Your suggestion that the data is spread widely around that regression line is exactly right - the data points looks like a cloud around the line of regression plotted by the software.
Comment: @wolf.rauch gotcha
Comment: @jed It would be good if you were to correct your reply.
Comment: @whuber thanks, it wouldnt let me edit it, so i deleted it and re-posted the edited version:
I meant to say in a linear model, slope with a value close to +1 is indicative of a strong positive relationship between the variables IF the variables are standardized.
Comment: @jed Thanks.  Whatever you did, it seems to have worked, because the comments and votes stuck with your answer.  By the way, the questions of linearity and normality of residuals are really separate ones; lack of normality does not necessarily imply a linear model is wrong (but it does suggest a more cautious approach).
Comment: @whuber I clarified the 3rd paragraph. Although one can fit a linear model to data with a non-linear relationship you would be right to suggest caution in its use and interpretation.
Answer: For a linear regression, the fitted slope is going to be the correlation (which, when squared, gives the coefficient of determination, the $R^2$) times the empirical standard deviation of the regressand (the $y$) divided by the empirical standard deviation of the regressor (the $x$).  Depending on the scaling of the $x$ and $y$, you can have a fit slope equal to one but an arbitrarily small $R^2$ value.
In short, the slope is not a good indicator of model 'fit' unless you are certain that the scales of the dependent and independent variables must be equal to each other.
Answer: @Macro had a great answer.

The estimated value of the slope does not, by itself, tell you the strength of the relationship. The strength of the relationship depends on the size of the error variance, and the range of the predictor. Also, a significant pp-value doesn't tell you necessarily that there is a strong relationship; the pp-value is simply testing whether the slope is exactly 0.

I just want to add a numerical example to show what is looks like to have a case OP described.

Low $R^2$
Significant on p-value
Slope close to $1.0$
set.seed(6)
y=c(runif(100)*50,runif(100)*50+10)
x=c(rep(1,100),rep(10,100))
plot(x,y)

fit=lm(y~x)
summary(fit)
abline(fit)

> summary(lm(y~x))

Call:
lm(formula = y ~ x)

Residuals:
   Min     1Q Median     3Q    Max
-24.68 -13.46  -0.87  14.21  25.14

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  25.6575     1.7107  14.998  < 2e-16 ***
x             0.9164     0.2407   3.807 0.000188 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 15.32 on 198 degrees of freedom
Multiple R-squared:  0.0682,    Adjusted R-squared:  0.06349
F-statistic: 14.49 on 1 and 198 DF,  p-value: 0.0001877

Answer: I like the answers already given, but let me complement them with a different (and more tongue-in-cheek) approach.
Suppose we collect a bunch of observation from 1000 random people trying to find out if punches in the face are associated with headaches:
$$Headaches = \beta_0 + \beta_1 Punch\_in\_the\_face + \varepsilon $$
$\varepsilon$ contains all the omitted variables that produce headaches in the general population: stress, how contaminated your city is, lack of sleep, coffee consumption, etc.
For this regression, the $\beta_1$ might be very significant and very big, but the $R^2$ will be low. Why? For the vast majority of the population, headaches won't be explained much by punches in the face. In other words, most of the variation in the data (i.e. whether people have few or a lot of headaches) will be left unexplained if you only include punches in the face, but punches in the face are VERY important for headaches.
Graphically, this probably looks like a steep slope but with a very big variation around this slope.


Isotropy of 5-dimensional quadratic forms

Question: There is an exercise in Ch X of TY Lam's book Introduction to quadratic forms which asks us to prove that if a 5-dimensional quadratic form is universal then it is isotropic.
I have been able to prove an easier version of it which shows if a 3-dimensional quadratic form is universal then it is isotropic.
I approached it in the following way: Let $\sigma$ be a 5-dim form with d($\sigma$)=d. Since
$\sigma$ is universal , it represents d . Hence $\sigma$ $\cong$ $<d>$ $\bot$ $\gamma$  where $\gamma$ is 4- dim form with d($\gamma$)=1. Hence, $\gamma$ is a Pfister neighbor and a.$\gamma$ $\subseteq$ $\tau$ where $\tau$ is 2-fold Pfister form.
I am stuck here and don't know how to proceed from here.
Comment: It's in Cassels, Rational Quadratic Forms. Pigeonholes, as I recall. Alright, Lemma 2.7 on page 60. Uses Corollary same page, a regular ternary represents all except possibly one squareclass; these are the p-adic fields which Lam does not
Comment: Isn't the corollary only for for fields Qp? The question is for arbitrary fields.
Comment: Right. I'm comparing in Lam (2005) Your ternary thing is problem 6 on page 75. I suspect you can tweak Cassels just a little
Answer: Your attempted solution is the correct way to start.  Let's now finish your solution using the notation you have already introduced. We have
$a \sigma = <ad> \perp a \gamma = <ad> \perp \tau$, where $\tau$ is a $2$-fold
Pfister form.
Let $\psi = <1, ad> \otimes \tau$, which is a $3$-fold Pfister form.
Since $a\sigma$ is also universal and is a proper subform of $\psi$, it follows that $\psi$ is isotropic.  Since $\psi$ is a Pfister form, it follows that
$\psi$ is hyperbolic.
Any $5$-dimensional subform of $\psi$, such as $a\sigma$, must be isotropic.
Therefore, $\sigma$ is isotropic.


Choose Checkbox Insted of radio as a widget in drupal custom content type

Question: While adding field in content type I had chosen Check boxes/radio buttons as widget.
By default it takes radio button as a widget.I want check boxes as a widget instead of Radio Button. What should I do?
Answer: You need to edit in Field Settings to set Number of Values to Unlimited or more than 1. Then Checkboxes will be used.
Radio buttons are used when user can only select one value.


Data part of Response is a long script instead of desired json object

Question: I am building a web app using laravel and vuejs. I have made a axios get request to get a list of users .
I am getting a Promise object, and from what i have read. Reason for getting a promise object is because it's an async request.
I have tried .then() to get data part of the response. But i am getting a huge script instead of desired data.
axios......then(function(response){
    console.log(response.data);
})

Initially what i did was
 var res = axios.get('/allUsers');
   console.log(res)

That time i came to know about promise object and read about.
When i checked network in dev tools, status code is 200 and i can see list of users. So i guess my request is successfully completed.
What should be done to get the list of the users. That list i will be using to update my UI.
Answer: Depending on what you're getting back for data there are a few ways to handle this. You may need to convert the data after the you get receive the response.
axios.get('some_url')
    .then(res => res.json())
    .then(data => {
        // do something with the data
    }).catch(err) {
        conosole.error(err);
    }

if you're seeing the data come through properly in the response and you're getting what you need without doing that then just do
axios.get('some url').then(res => {
  // do something in here with the data here
})

also make sure you're getting back json if that's what you're looking for. check your response to see if its html or json because they can be handled a bit differently
as an "Edit" you could also handle this with async await so you dont end up in callback hell
async function fetchData() {
    try {
      const res = await axios.get('some url');
      // next step might not be necessary
      const data = await res.json();
      // do something with the data
      console.log(data); // if converting it was necessary
      console.log(res); // if not converting
    } catch (err) {
      console.error(err);
    }
}


Unit root test (e.g. ADF) vs Autocorrelation test (e.g. Breusch-Godfrey)

Question: I am confused with the purpose of unit root tests in relation to serial correlation tests. I know they test for different things, but ultimately tests if a time series is stationary or not.
From what I understand, you perform a unit root test on a time series and when you reject the null, that time series is I(0), and is stationary.
So then, what will be the purpose of the auto-correlation test on the residuals for in this case? Since the time series is already proven to be stationary by the unit root test, what then is the purpose of the auto-correlation test? Or do you only choose one test? Seems to me that if a time series has a unit root, performing an auto correlation test on the residuals will indicate non stationarity anyways, so why not just use the auto-correlation test in the first place.
Both test indicates the stationarity of the time series, and hence why should I perform both tests?
Comment: As far as I'm concerned, the unit root test can in no way "prove" that a series is stationary. See my question here: https://stats.stackexchange.com/questions/450468/dickey-fuller-test-significant-series-stationary - I didn't get an answer but I'm pretty sure I'm right on that matter.
Answer:
I know they test for different things, but ultimately tests if a time series is stationary or not.

The mistake in your argument is that tests of autocorrelation assess stationarity. Actually, they assess presence of autocorrelation (unsurprisingly). Now, an autocorrelated time series can be stationary or nonstationary. (Note that a stationary time series can have zero or nonzero autocorrelation; nonzero autocorrelation by itself does not make a time series nonstationary.) Therefore, learning that a time series is autocorrelated does not indicate the time series is nonstationary. If you want to assess nonstationarity of the unit root kind (there are other kinds, too, e.g. nonstationarity due to a structural break or changing variance), you need a unit root test.
Comment: @OGARCH, you are correct, if by *ACF should converge towards 0* you mean convergence as the time lag goes to infinity (as opposed to the sample size going to infinity for a fixed lag).
Comment: Ok, I have done some research and would like to see if I am in the right direction.
1. Auto-correlation of a time series does not necessary access the stationarity of a time series. But for a stationary time series, ACF should converge towards 0.
2. Serial correlation in the residual of a regression model picks up the composite effect of everything not accounted for by the explanatory variables, e.g. misspecfication, etc. Hence, even if a the residuals have no auto-correlation, it does not mean that the regression is stationary.
3. To test stationarity of a time series, one can use ADF.
Comment: I have asked the above in another post with more clarity - https://stats.stackexchange.com/questions/466932/clarification-of-some-concepts-with-regards-to-unit-root-and-auto-correlation?noredirect=1#comment862795_466932