Apply the Blaschke Selection Theorem

Question: Let the sequence of convex  $n$-gons $\{P_k\}$. Is there a subsequence $\{P_{k_i} \}$ of that sequence such that $P_{k_i} \to P$ as $k_n  \to \infty $, where $P$ is a $m$-gon for $m \leq n$ ? I think the Blaschke Selection Theorem is an option for the resolution of that problem, but I am not quite sure how to resolve with that result. Could anyone be able to help me at this point? Particularly, why $P$ must be an $m$-gon in such a way that $m \leq n$?

Blaschke Selection Theorem : For a sequence $\{K_n\}$ of convex sets contained in a bounded set, there exists a subsequence
  $\{K_{n_m}\}$ and a convex set $K$ such that $K_{n_m}$ converges to
  $K$.

Clarification :  The limit is endowed with the usual Hausdorff metric.
Comment: @Vim That result is a true result from the article The sound of Symmetry (Proposition $6$ page $820$). I was wondering how to use the following theorem.
Comment: Your $n$ is fixed? Then what is $P_{k_n}$?
Comment: Yes, n is fixed, and $\{P_{k_n} \}$ is a subsequence of $P_k$.
Comment: technically you should use another letter other than $n$. By the way, by *bounded* polygons do you only mean the polygons are *uniformly* bounded, or in a stronger sense, they are all contained in a bounded set?
Answer: In general it is not true since you can take $P_k = kP$ where $P\neq \{0\}$ is any $n-$ gon.
But if you assume that there exist a ball $B$ such that $P_k \subset B$ for infinitely many $k.$ Then it is true. To see this let $A_k =\{p_{k1} , p_{k2} ,  ... p_{kn}\} $ be the set of vertices of the $n-$ gon $P_k .$ Then there exists a sequence of natural numbers $s_j $ such that $p_{s_j l} \to p_l $ for all $1\leq l\leq n$ as $j\to \infty $, where $p_l \in \mathbb{R}^d .$
From the inequlity $$d_H (\mbox{conv} (A) , \mbox{conv}(B) ) \leqslant d_H (A,B)$$ we obtain that $P_{s_j } \to \mbox{conv}\{ p_1 , p_2 , ..., p_n\} $ as $i\to \infty$ with respect to the Hausdorff metric $d_H .$
Comment: $m\leqslant n$ because some of the poins $p_l$ may be equal each other. Yes, there should be $j$ instead of $i$. No, the sentence " if you assume that there exist a ball $B$ such that $P_k \subset B$ for infinitely many $k$ ' implies that the set $\mathcal{B} =\{P_k :k\in \mathbb{N}\}$ contains an infinite compact subset with respect to the Hausdorff metric.
Comment: Could you tell me why in the question $m \leq n$? Why is there exist a sequence of natural numbers $s_j$? And you mean probably $j \to \infty$ at the end, right?
Comment: Moreover, you mean probably by " *if you assume that there exist a ball $B$ such that $P_k⊂B$ for infinitely many $k$*" that the set of $P_k$ is compact, right?
Comment: Why is there exist a sequence of natural numbers $s_j$?
Comment: Moreover, could you clarify the notation "conv"?
Comment: Since every bounded sequence of points of finite dimensional normed space poses a convergent subesequence. $\mbox{conv} (S) =\bigcap \{M : S\subset M, \mbox{and } M \mbox {is convex}\} $

Apply the Blaschke Selection Theorem


Displaying "Related Products" in a custom tab for normal single product pages

Question: In WooCommerce, I have this code below for adding "Related Products" to a custom tab and making it work on posts that are used with a short code [product_page id="99"] on pages and posts.
The code that I use in functions.php that is working:
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20);
/*
 * Register custom tab
 */
function woo_custom_product_tab( $tabs ) {

    $custom_tab = array(
        'custom_tab' =>  array(
            'title' => __('Custom Tab','woocommerce'),
            'priority' => 9,
            'callback' => 'woo_custom_product_tab_content'
        )
    );
    return array_merge( $custom_tab, $tabs );
}
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tab' );

/*
* Place content in custom tab (related products in this sample)
*/
function woo_custom_product_tab_content() {
    global $product;
    $product->get_related();
}

Now the problem is that I get a blank tab in normal product single pages.
How can I make it work on normal product single pages too?
Thanks
Answer: To make it work also on single product pages you need to add some conditions and to reuse the woocommerce_related_products() just for single product pages.
So your code will be now:
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20);
/*
 * Register custom tab
 */
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tab', 20, 1 );
function woo_custom_product_tab( $tabs ) {

    $custom_tab = array(
        'custom_tab' =>  array(
            'title' => __('Custom Tab','woocommerce'),
            'priority' => 9,
            'callback' => 'woo_custom_product_tab_content'
        )
    );
    return array_merge( $custom_tab, $tabs );
}

/*
* Place content in custom tab (related products in this sample)
*/
function woo_custom_product_tab_content() {
    global $product;
    if(!is_product())
        $product->get_related();
    else
        woocommerce_related_products();
}

This should work for your product shortcode on pages and post on one side and also on single woocommerce normal product pages.
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Comment: Thanks man, appreciate all your WooCommerce knowledge! you've been very helpful on a various amount of questions!

Displaying “Related Products” in a custom tab for normal single product pages


jQuery JSON not passing data to Ci properly

Question: The script below works as far as i can tell:

The problem I'm experiencing with the code below is that the mysql insetion query just wont work. It creates the row in the table and auto-increments but for some odd reason it wont pass the 'var add' in the Javascript above to the Ci script below and perform an insertion in the db. Any thoughts or ideas?
<?php
class home extends CI_Controller {
    function __construct() {
        parent::__construct();
    }
    function index() {
        $data = array();
        $data['lists'] = $this->displayList();
        $this->load->view('home', $data);
    }
    function displayList() {
        $str = '';
        $query = $this->db->query("SELECT * FROM data");
        foreach ($query->result() as $row) {
            $b = '<input name="completed" type="checkbox" />';
            $a = $row->title . "
";
            $str .= $b.$a;
        }
        return $str;
    }
    function jsonAddData() {
        if($this->input->is_ajax_request()) {
        $title = $this->input->post('title');
        $query = $this->db->query("INSERT INTO data (title) VALUES ('$title')");
        header('Content-type:application/json');
        if($query) echo json_encode(array('title_posted' => true));
        else echo json_encode(array('title_posted' => false));
        }
    }
}
?>

Comment: You have HTML-injection (cross-site scripting) and SQL-injection (database compromise) security holes in this script. HTML-encode all data you output to the page `htmlspecialchars($row->title)` and use parameterised queries to avoid this.
Answer: In
$.ajax({
...
data: {title: add}

Not just a string
Comment: @MichaelGrigsby You are not passing a "JSON element" - there is no such thing in Javascript and anyway, you are not sending [JSON](http://www.json.org/) to the server - you are passing an object, which will be converted to a URL-encoded query string so it can be used in POST request. If you want to pass a string, you would need to do `data: 'title='+escapeURIComponent(add)`. You should read the [`$.ajax` manual page](http://api.jquery.com/jQuery.ajax/) and learn about [HTTP POST](http://en.wikipedia.org/wiki/POST_(HTTP)) requests.
Comment: Aw okay... so I need to pass it as a JSON element? It works though... thanks man!
Comment: My bad, lol it's been a couple months since I've worked with Javascript. I'm still learning it. That's the format JSON uses though.... So it's just an object? And I know about POST and GET requests... I've been working with PHP since 2009.
Comment: @MichaelGrigsby JSON is a sub-set of Javascript's object literal syntax - for example the only parameter you passed to `$.ajax()` is an object literal, wrapped in `{}`. When the `data` property of this object is of a vector type (`object`), it is converted to a URL-encoded string, just like an HTML form submission - this is, after all, what you are mimicking with your request. When it is a scalar type like `string` or `number`, it is converted to a string and sent literally.


AngularJS + Sharepoint + Rest API

Question: Pessoal atualmente estou tentando desenvolver um script dentro do sharepoint usando o Script Editor mas está caindo no erro do meu código, como se a conexão não estivesse correta, porém, no Dev Http do google a requisição rest funciona. Segue o código:

    Welcome to AngularJS world in SharePoint 2013!

Product Name: {{p.ProductName}}

 Rate: Rs. {{p.ProductRate}}.

Answer: Se está entrando na condição de erro, isto significa que houve algum problema na requisição HTTP feita via Ajax.
No código mostrado, a variável _spPageContextInfo não está definida, mas é utilizada:
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('ProductList')/items?$select=ProductName,ProductRate,ProductImage",

Certifique-se de que o URL efetivamente contém o endereço correto.
Eu recomendo que utlize ou Firebug no Firefox ou as Ferramentas do Desenvolvedor no Chrome.
Com o Chrome, fica bem fácil analisar todos os detalhes de uma requisição HTTP. Tecle SHIFT+CTRL+I, clique na aba "Network", recarregue sua página e observe os resultados - deverá aparecer a sua chamada HTTP feita via Ajax pelo jQuery. Então, clique com o botão da direita do mouse sobre a chamada HTTP que apareceu na lista, em seguida clique em "Copy All as HAR" - e depois cole o resultado aqui na pergunta, pois conterá todos os detalhes da chamada HTTP que está falhando.
Comment: J. Bruni não funcionou da forma como disse. Como ele entra direto na minha condição de erro (que é mostrada na tela sempre que recarrego) o problema está na conexão, pois ele não faz o que está dentro de success. Não sei ainda o que pode ser. Alguma outra ideia?
Comment: Estou executando direto pelo sharepoint dentro de um Script Editor no local onde ele tem que funcionar. A requisição já testei inclusive colocando o mesmo endereço que uso no Dev Http do Chrome onde funciona e tras os itens corretamente. O erro quando rodo no ie10 direto do sharepoint usando o console do próprio ie10 é: SCRIPT7002: XMLHttpRequest: Erro de Rede 0x2ee7, Não foi possível concluir a operação. Erro: 00002ee7.
Comment: Pesquisei o erro 0x2ee7 significa "The server name could not be resolved" - ou seja, ou o endereço na URL está mesmo errado, ou há algum problema de DNS.
Comment: Mas pq no Dev Http o mesmo endereço funciona? Fiz o que vc sugeriu de abrir o log do chrome mas apareceu muita coisa, não sei qual copio.
Comment: Não sei - vai ver ele remove os espaços em branco automaticamente - estou sugerindo isso porque acabei de ler isto aqui: http://www.pc-library.com/errors/error-code/12007-0x2EE7/
Comment: É mesmo um problema de conexão...
Comment: Espera aí... na verdade, há muitos outros fatores para uma requisição HTTP ser bem-sucedida - os *headers* (cabeçalhos), *cookies*, etc, podem ser tão importantes quanto o endereço (URL).
Comment: O problema é que eu sou novo usando isso e não sei se tem algo a mais errado no código. O header eu estou colocando o mesmo que uso no Dev Http.
Comment: Definitivamente esse erro não tem a ver com o código, mas com a requisição HTTP mesmo. Talvez você precise mexer no código para incluir um header, mudar o URL, incluir um cookie. O ideal seria ter um raio-X exato para comparar as duas requisições HTTP. No Linux, eu usaria o Wireshark - não faço a menor ideia de uma ferramenta semelhante de "network sniffing" para o Windows.
Comment: É vou procurar por algo assim então pra poder ver melhor e posto aqui assim que conseguir mais alguma pista.
Comment: Nada feito. Continuo preso no mesmo ponto, já me aconselharam a modificar para `$http.get` no lugar de `jQuery.ajax()` mas não sei bem como fazer e acho que por isso também não funcionou. Mais alguma ideia? Esgotei as minhas.
Comment: Sugestão 1: remova a linha `headers: { "Accept": "application/json;odata=verbose" },`
Comment: Sugestão 2: inclua `alert(_spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('ProductList')/items?$select=ProductName,ProductRate,ProductImage");` antes de `jQuery.ajax({` - certifique-se que o endereço está certo - copie e cole aqui para a gente o que aparece no alert.
Comment: Sugestão 3: usando o DevHttp, salve a requisição bem sucedida, em seguida vá embaixo, em "REPOSITORY" - "Export", selecione a requisição para salvar a mesma num arquivo *json* - e então disponibilize esse arquivo para nós (seja editando a pergunta e colando o conteúdo, ou usando um serviço como *pastebin* ou outro) - aí a gente pode ter mais pistas para ajudar.
Comment: Quando fui colocar o endereço completo observei que estava colocando como http e no dev estava como https. Aparentemente era isso pois ele entrou no meu success onde coloquei um alert para confirmar se havia entrado, porém outro erro surgiu. O alert funciona mas está com esse erro: SCRIPT438: O objeto não oferece suporte à propriedade ou método 'indexOf'.
Comment: Pois é... foi o que disse desde o começo: "Certifique-se de que o URL efetivamente contém o endereço correto." :-) Quanto ao erro no "indexOf", significa que a variável "pImage" não é *string*. Para forçar que seja *string*, exprimente mudar a linha anterior para `var pImage = "" + value.ProductImage;`
Comment: Troquei como você sugeriu e funcionou como deveria. Cara muito obrigado mesmo.
Comment: vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/13089/discussion-between-douglas-and-j-bruni)
Answer: Tenta mudar o:
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('....

para:
url: _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getByTitle('....

Comment: Isto não responde à pergunta. Quando você tiver [reputação](https://pt.stackoverflow.com/help/whats-reputation) suficiente, você vai poder deixar [comentários em qualquer post](https://pt.stackoverflow.com/help/privileges/comment) mas, até lá, escreva apenas resposta que não [dependam de mais informações de quem perguntou](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [Da Revisão](/review/low-quality-posts/153484)
Comment: Na verdade o erro que ele vem encontrando é na montagem no endereço de consulta no SharePoint. Enfrentei problema semelhante e no SharePoint Online essa alteração me garantiu a conexão corretamente.

AngularJS + Sharepoint + Rest API


Is it possible to narrow the types of overloaded parameters without exhaustively checking each parameter in the function body?

Question: I'd like to define a function which can accept parameters typed in one of two ways. For example:
type Fn = {
    (abc: number, def: string): void,
    (abc: string): void,
};

Given this type signature, if abc is a number, then def is a string, and if abc is a string, then def is not defined. This is clear to humans, but is there any way for Typescript to recognize it? For example, the following implementation fails:
const fn: Fn = (abc: number | string, def?: string) => {
    if (typeof abc === 'string') console.log(abc.includes('substr'));
    else console.log(def.includes('substr'));
}

because although the type of abc has been narrowed, TS doesn't understand that the type of def has been determined too, so def.includes is not permitted. The grouping of argument types is recognized for callers of the function, so the following is forbidden, as expected:
fn('abc', 'def');

But the overloaded type grouping seems to have no effect inside the function.
When there are only a couple of parameters, it's easy enough to explicitly (and redundantly) type-check each parameter, or use a type assertion for each once one has been checked, but that's still ugly. It gets much worse when there are more than a couple of parameters.
Another problematic redundancy is that each possible argument type needs to be listed not only in the type, but also in the function's parameter list. Eg (abc: number) and (abc: string) in the type definition also requires = (abc: number | string) in the parameter list.
Is there a better pattern available for function overloading without ditching it entirely? I know of at least two workarounds that don't involve overloading:

Pass an object of type { abc: number, def: string } | { abc: string } instead of multiple separate parameters, then pass the object go through a type-guard
Use two separate functions for the two different types of parameters

But I'd rather use overloading if there's a decent way to handle it.
Answer: This is now possible to a limited extent with TypeScript 4.6's Control Flow Analysis for Dependent Parameters.
TypeScript can narrow down the types of arguments if the narrowing is done with ===. (A typeof check doesn't appear to work, at least not yet.)
To tweak the example in the question, if the first argument, when it is a string, is abc, has no second argument, that can be detected and narrowed by TypeScript thusly:
type Fn = (...args: [number, string] | ['abc', undefined]) => void;
const fn: Fn = (abc, def) => {
    if (abc === 'abc') console.log(abc.includes('substr'));
    else console.log(def.includes('substr'));
}

The narrowing of the first argument to abc allows TS to infer that in the else, the second argument is a string, and not undefined.

It'd be great if types wider than literals could use this same technique, but they don't work (yet) - the typeof check on the first argument fails to narrow the second argument.
type Fn = (...args: [number, string] | [string, undefined]) => void;
const fn: Fn = (abc, def) => {
    if (typeof abc === 'string') console.log(abc.includes('substr'));
    else console.log(def.includes('substr'));
}

Answer: All of your approaches can be reasonable: (1) separate function declarations (2) union of object parameters or (3) a function overload like in question.
I would prefer (1), If the caller already has enough information to decide which function has to be called, as this reduces the overall conditional complexity of fn body.
(2) makes more sense with a discriminated union type, so you don't loose excess property checks for the caller. Example:
type OverloadParam =
    | { kind: "a", abc: number; def: string }
    | { kind: "b"; abc: string }

type Fn = (arg: OverloadParam) => void

const fn: Fn = (args) => {
    if (args.kind === "a") {
        args.def.includes('substr')
    } else {
        args.abc.includes('substr')
    }
}

In addition, you don't have to list the types twice both in Fn and as part of fn signature. I found this oldie here as a reason: only functions with a single overload can apply a contextual type.
With (3) there is no clever way to handle variable function parameters inside the function. TS/JS don't support a function overload implementation like this:
function fn(abc: number, def: string): void { }
function fn(abc: string): void { }
// error (TS): Duplicate function implementation. JS would overwrite the first declaration

So you will always have to use a wider type signature with optional parameters and/or union types and narrow these types down inside the function body.


Listar Pastas e excluir arquivos dentro das mesmas de uma vez só

Question: Minha ideia é que eu conseguisse apagar todos os arquivos dentro das pastas de uma vez só ou por período (exemplo, a cada 5 meses me listar esses arquivos dentro do período).
Eu consegui listar todas as pastas e clicando nelas consigo visualizar os arquivos.
Alguém poderia sanar com algum exemplo pra poder dar continuidade a partir do código PHP abaixo?
EDIT: Basicamente, seria listar todas as pastas e apagar todos os arquivos dentro das pastas existente de uma vez só.
Agradeço desde já!
CÓDIGO:
<?php
    $dir = "./";
    foreach (glob ($dir."*", GLOB_ONLYDIR) as $pastas) {
        if (is_dir ($pastas)) {
        echo "Motorista: ";
            echo str_replace ( $dir,"",$pastas)."  - Olhar pasta
";
                        echo "";
        }
    }
    ?>

Comment: Possível duplicata de [Como deletar pastas, subpastas e arquivos?](https://pt.stackoverflow.com/questions/15144/como-deletar-pastas-subpastas-e-arquivos)
Comment: No meu caso seria percorrer em todas as pastas existentes e apagar todos os arquivos dentro dessas pastas.Não quero apagar as pastas
Answer: Isso é bem simples vc só precisa usar outro glob() dentro do primeiro loop, para criar outro loop e excluir todos os arquivos das subpastas.
## lista as pastas do diretorio atual
foreach(glob('./*', GLOB_ONLYDIR) as $i){
    ## lista e apaga todos os arquivos das subpastas
    foreach(glob($i.'/*') as $e){
        unlink($e);
    }
}

Edit:
$date = "27-4-2019";

## checa a data
if(date("d-m-Y") == date("d-m-Y", strtotime($date.'+5 Month')));
    foreach(glob('./*', GLOB_ONLYDIR) as $i){
        foreach(glob($i.'/*') as $e){
            unlink($e);
        }
    }
}

Comment: Parse error: syntax error, unexpected 'foreach' (T_FOREACH) in C:\xampp\htdocs\chametaxi\motorista\admin\uploads\teste.php on line 5

dá esse erro, mas como eu poderia colocar isso funcional naquele código acima?
Comment: Eu editei o código, mas é a mesma coisa, vc disse que queria apagar todos os arquivos das subpastas, e é isso que o código acima vai fazer, então pq vc iria querer dar `echo` para o link das pastas?
Comment: Era mais pra ter a certeza de que as pastas estariam "criadas" ainda. Obrigado pela ajuda!
Ainda nesse código, é possível colocar um tempo com alert para apagar os arquivos?
Ex: Abri a página e me dá um alert "Somente abra este link após 5 meses" e colocar uma condição de data pra quando for abrir de novo não apagar os arquivos e sim após a data especificada?
Comment: Sim, é possivel, eu editei o código. Ma em relação ao `alert()` vc tem que da uma pesquisada sobre ajax ou javascript pra fazer tudo isso.
Comment: A date é fixa né? então eu teria que ficar editando essa data fixa pro dia atual que for excluir? teoricamente isso que impede se caso abrir de novo, não exclua?
Comment: vc so tem que alterar o valor da variavel `$data` para o dia em que vc quer que inicie a contagem (dia atual + 5 meses).
Answer: Tente isto:
<?php
    function excluir($dir){
        if(is_file($dir)){
            return unlink($dir);
        }elseif(is_dir($dir)){
            $files = array_diff(scandir($dir), array('.','..'));
            foreach ($files as $file){
                (is_dir("$dir/$file")) ? excluir("$dir/$file") : unlink("$dir/$file");
            };
            //return rmdir($dir); //remova caso queira apaga a pasta
        };
    };
    excluir("./"); //coloque aqui o diretório que deseja excluir.
?>


Continue training a deeplearning4j model after it has been saved and loaded

Question: I am using a Convolutional Neural Network and I am saving it and loading it via the model serializer class.
What I want to do is to be able to come back at a later time and continue training the model on new data provided to it.
What I am doing is I load it using
ComputationGraph net = ModelSerializer.restoreComputationGraph(modelFileName);
and then I give it the data like before with
net.train(dataSetIterator);
This seems to work, but it makes my accuracy really bad. It was about 89% before I did this, and, using the same data, it gets to be around 50% accurate after a few iterations (using the same data it just trained itself on, so if anything it should be getting stupidly more accurate right?).
Am I missing a step?
Answer: I think it'll be difficult to answer based on the information given, but I'll give you an example.
I had this exact problem. I had based my app on the GravesLSTMCharModellingExample (which is LSTM). I had saved my model after running for a couple of epochs (at which point it generated legible sentences), but when loading it, it produced garbage.
I thought everything was the same, but in the end it turned out I didn't initialize the CharacterIterator the same. When I fixed it, it worked as expected.
So to cut a long story short;
Check your values when initializing the auxiliary classes.


Prevent form fields changes

Question: I have custom field on theme settings. I get default_value for that field from .info file and that's OK. I change the value of that field and submit the form and get a changed value but I do not want it. I want, after submitting form the value of that field will be changed but in that field the value will be showing the default_value from .info file. How could I do that.
Answer: If I've understood right you should implement next steps to achieve your goal:

Take a look at drupal_parse_info_file() function to get a value from .info file.
Alter your form and set appropriate value to <code>#default_value</code> property whithin your field.

Prevent form fields changes


Hoc Hof syntax on typescript

Question: I got TS2300: Duplicate identifier 'UIBuilderForm'. exception.
I was trying to apply HoC (high order component) on UIBuilderForm
What's the correct way to use this syntax on typescript with ES6?
    class UIBuilderForm extends React.Component<any, {}> {
        ...
    }

    let UIBuilderForm :any = reduxForm({
        form: FORM_NAME
    })(UIBuilderForm as any);

    const selector = formValueSelector(FORM_NAME) //

    let UIBuilderForm = connect(
        formStates
    )(UIBuilderForm)

    ??? UIBuilderForm = connect(
        mapStateToProps,
        mapDispatchToProps
    )(UIBuilderForm)

    export default UIBuilderForm

Comment: You just need to name your new thing something else, the error is because you reuse the same name for the original component and the result of your `reduxForm` and `connect` calls.
Comment: The assignment even would've worked, you just need to omit the `let` declaration.
Answer: You have two let and one class declaration for the same variable name, which isn't allowed. Either choose different names, or omit the lets:
class UIBuilderForm extends React.Component<any, {}> {
    ...
}

UIBuilderForm = reduxForm({
    form: FORM_NAME
})(UIBuilderForm);

const selector = formValueSelector(FORM_NAME) //

UIBuilderForm = connect(
    formStates
)(UIBuilderForm)

UIBuilderForm = connect(
    mapStateToProps,
    mapDispatchToProps
)(UIBuilderForm)

export default UIBuilderForm;

Or just put everything in one big expression:
const selector = formValueSelector(FORM_NAME);

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(connect(
    formStates
)(reduxForm({
    form: FORM_NAME
})(class UIBuilderForm extends React.Component<any, {}> {
    ...
})));

Hoc Hof syntax on typescript


non-homogenous linear recurrence relation general questions

Question:
what happens if you have both repeated and non-repeated roots? i know there are different forms for both, so if given roots say $5, -3, -3, -3$ would it then be $A(5)^n + B(-3)^n + Cn(-3)^n + Dn^2 (-3)^n$?
since $a(n) = b(n) + p(n)$ for non homogenous recurrence relations, if this was your RR (e.g. $a(n) = 5(n-2) + (n-3) + 3(n-4) + 4*5^{n-2}$ how would p(n) look? would it look like $p(n) = 4Bn(5)^{n-2}+4C(5)^{n-2}$ (since 5 along with 3, 3, 3 is a root of the equation)?

i get quite confused about the p(n) part of a(n) = b(n) + p(n)
especially with the whole guessing part
sorry in advance for the formatting (i don't know how to use latex and this is my first post)
Answer: Your answer to the first question is correct.
I'm guessing that in the second question you meant to write
$$a(n)=5a(n-2)+a(n-3)+3a(n-4)+4\cdot5^{n-2}\;,$$
so that the non-homogeneous part is just $4\cdot5^{n-2}$. However, in that case the roots of the characteristic equation of the homogeneous part are not $5,3,3$, and $3$. If you did have a homogeneous part whose characteristic equation had those roots, however, then $p(n)$ would have the form $B\cdot5^nn^1=Bn5^n$.
The general rule here is that if the non-homogeneous part has the form $r^nQ(n)$, where $r$ is a root of multiplicity $m$ of the characteristic equation of the homogeneous part, and $Q(n)$ is a polynomial of degree $d$, then
$$p(n)=n^mr^n\left(p_0+p_1n+\ldots+p_dn^d\right)\;.\tag{1}$$
In your problem $r=5$, $m=1$, and $4\cdot5^{n-2}=\frac4{5^2}\cdot5^n=\frac4{25}\cdot5^n$, so $Q(n)=\frac4{25}$, and $d=0$.
If $r$ is not a root of the characteristic equation of the homogeneous part, leave out the factor of $n^m$ in $(1)$. (Equivalently, view the multiplicity of $r$ as $0$, and note that $n^0\equiv 1$.)
Comment: thanks for answering

in $ p(n) = 4/25 * 5^n $, would that then be the final value of p(n) so afterwards you just add that to the end of the homogeneous general solution, and then you can work on getting values with a given initial condition?
Comment: @anon: No, $p(n)=Bn5^n$, where $B$ still has to be determined. $\frac{4}{25}\cdot 5^n$ is $Q(n)$, the non-homogeneous part of the recurrence.
Comment: So does that mean for the non homogenous part to become $p(n)$ you disregard the coefficient 4? Where did the exponent -2 go? I just don't particular understand how you went from the homogenous part $4*5^n-2$ to $Bn5^n$ (I understand what B is)
Comment: @anon: I first rewrote the non-homegenous part as a polynomial times $5^n$: $4\cdot5^{n-2}=\frac4{25}\cdot5^n$. The polynomial, which I called $Q(t)$ in my answer, is the $0$-degree (constant) polynomial $\frac4{25}$. (In my previous comment I accidentally included the factor of $5^n$; that was an error.) When you set up $p(n)$, nothing about $Q(n)$ matters except its degree, which in this case is $0$; the specific coefficients (here just $\frac4{25}$) are irrelevant. One factor of $p(n)$ will be an unknown polynomial of degree at most $d$; here that's $B$. Another will be $r^n$, here ...
Comment: ... $5^n$. And the last will be $n^m$, where $m$ is the multiplicity of the root $r$; here that's $1$. Thus, we end up with $Bn5^n$.


What are the issues when performing an ANCOVA with a covariate that is influenced by experimental manipulation?

Question: Context:
I am doing a study on lying.

The independent variable was manipulated such that participants were either told to lie or tell the truth.
The dependent variable is related to the amount of detail provided and is extracted from the text provided by participants(this is a standard system of deception detection called reality monitoring).

Issue:
I noticed that much of the previous research (e.g., Sporer [2000]) has included or suggested the use of  word count as a covariate to make sure that any differences in the number of details do not simply reflect differences in the number of words.
However, I was under the impression that covariates needed to be measured before the experimental manipulation and should not be related to the independent variable.
Word count is measured after people have provided their truthful or deceptive account (And possibly related to truthfulness since people might provide more details by giving a longer account). I have read Miller and Chapman's paper on the misunderstanding of ANCOVA (FREE PDF).
Questions

Does including word count as a covariate looking at the effect of condition on details provided reduce statistical power?
Is it meaningful to include a covariate that is measured after, and is assumed to be affected by, an experimental manipulation?
How serious is violation of heterogeneity of covariance when including covariates?
Rather than including word length as a covariate, often authors calculate number of details say per 100 words and then perform their analyses as normal. how is this different to including word length as a covariate?

Additional References:
For those interested, references include:

Stromwall, L., & Granhag, A. (2005). Children's repeated lies and truths: effects on adults' judgements and reality monitoring scores. Psychiatry, Psychology and Law, 12(2), 345-356,
Vrij, A., Mann, S., Fisher, R., Leal, S., Milne, R., & Bull, R. (2008b). Increasing Cognitive Load to Facilitate Lie Detection: The Benefit of Recalling an Event in Reverse Order. Law and Human Behavior, 32(3), 253-265.
Sporer, S. L. (2004). Reality monitoring and the detection of deception. In P. A. Granhag & L. Stromwall (Eds.), The detection of deception in forensic contexts. Cambridge: Cambridge University Press.
Comment: Links to references would be helpful in getting our heads around this.  Also, please clarify the nature of the covariates & the response variables.  This is a bit too abstract at the moment.
Comment: What is your measure of the number of details?  By word length do you mean number of words?
Comment: yes, number of words. the 5 response variables are 5 types of details (space, time, vision, sound and emotion). for example the sentence "the book was on the table" contains one spatial detail, 2 visual details, no sound/emotion/time details. it's all a bit theoretical (which i didn't want to bore you with). my independent variables are truthfulness (some accounts are made up and some are true) and recall (some people have already recounted the event before and others have not). it's an experiment (With random allocation).
Comment: oh and ps. sorry about no references, none of them are accessible for free for your guys (i get them through my university library)
Comment: Some of us can access university libraries, too.  :)  And some of us may go one better: we may already have the PDF or book.  ;-)  A citation is helpful enough.
Comment: Given the update: I would say "sentence length" or "expression length"; in many other contexts, word length = # of characters, sentence length = # words.  It's unfortunate that ambiguity exists, but that's life.
Comment: hm that's a good tip for writing my paper! thanks. and a citation: everyone uses different ways of defining the types of details i am scoring for but two examples are: Stromwall, L., & Granhag, A. (2005). Children's repeated lies and truths: effects on adults' judgements and reality monitoring scores. Psychiatry, Psychology and Law, 12(2), 345-356, AND Vrij, A., Mann, S., Fisher, R., Leal, S., Milne, R., & Bull, R. (2008b). Increasing Cognitive Load to Facilitate Lie Detection: The Benefit of Recalling an Event in Reverse Order. Law and Human Behavior, 32(3), 253-265.
Comment: i am not using cognitive operations though... Sporer, S. L. (2004). Reality monitoring and the detection of deception. In P. A. Granhag & L. Stromwall (Eds.), The detection of deception in forensic contexts. Cambridge: Cambridge University Press.
 That's the one that talks about controlling for word length a LOT :)
Comment: 1. If you're doing a study of lying, why wouldn't lying/truthtelling be the dependent variable?  2. You expressed a concern about power, but I think the more relevant concern would be that one variable (let's call it "expression length") would be part and parcel of the other (degree of detail), rather than truly being a separate variable that could be tested for its plausibility as a cause.
Comment: no lying is the independent variable, they are instructed to lie or tell the truth. the dependent variable is the volume of detail provided in truthful and deceptive statements.
Comment: AHA!!! So you want to know if they are giving more details & are more talkative or reserved when lying (or telling the truth)?
Comment: sorry.i was obviously not very clear in my question! i am looking at whether they provide more details (dependent variable) when telling the truth than lying (the independent variable). the number of words they include was purely of interest as a COVARIATE rather than a dependent variable. I was just worried about including number of words as a covariate because it is so closely related to the independent variable (ie. people also tend to provide more words when telling the truth).
Comment: oh, and i should probably also mention i am using MANOVA in spss...
Comment: @Anita, I performed a huge overhaul of the question to incorporate all the content in the comments (e.g., listing references; clear description of experiment; clear articulation of the question). Feel free to tweak if I have misconstrued anything.
Comment: thanks heaps jeromy. that's right. there is one more question i have (related): how serious is violation of heterogeneity of covariance when including covariates? thanks! anita
Comment: @jeremy: thanks for the rewrite.  Were I starting without the Miller & Chapman paper, I would think it premature to suggest ANCOVA.  I'm not yet sold on the linearity; ANCOVA and the like are often misapplied anyway, and I look forward to examining the M&C paper. To the OP (Anita): in the literature, do they tend to use linear models or ANCOVA?  There may be a transform applied to the # of words (e.g. a logarithmic transformation).  If you can check or, even better, post details on common models used, that could help.
Comment: Channeled my inner @jeremy and added the question.  :)  To Anita (the OP), if anything else comes up - I think you're also allowed to edit your question - there's a little button underneath the question box.
Comment: interesting. well in two of the papers i can find (the granhag & stromwall 2005 paper mentioned above and another one), they calculated the volume of detail per 100 words spoken then put it in a MANOVA- so that's not using ancova... it's adjusting for the effects of a covariate on the dependent variable before you put it in the anova. what is the difference between adjusting for the effects of a covariate before you run the analysis and just adding a covariate?
Comment: That would be good to include in your original question - it'll get harder to answer things in the comments.  :)
Answer: [Update / Note: Answer may be revised in light of ANCOVA questions.]
This is both an answer and a clarification.  It seems like the OP is asking about studying $\textrm{E}(NumDetails | (Honesty, NumWords))$ (so to speak), where $NumDetails$ is the # of details provided, $NumWords$ is the number of words used and $Honesty$ is 0 or 1, based on whether or not the person is telling the truth.
In simple terms, the interest is on the conditional distribution (or expectation) of the number of details provided by the subject conditioned on both whether they are telling the truth and if they are particularly loquacious.
This is reasonable, but has a slight hitch: if loquaciousness is related to their honesty, then it may be helpful to find a relationship for that.  In any case, the number of details would generally have to be related to the number of words used to express the ideas.
To answer the basic question: It's not really so easy to say that it reduces power, because the question seems to be on the # of details, not on the detection of lying.
An implicit question is whether or not the number of words is a reasonable covariate.  It is.  It may be dependent on both the subject and the role they're asked to play.  You should investigate whether or not it has some dependence on the role (lying or honest), and, if the subject is measured repeatedly, the dependence on the subject.
With these in hand, you can address whether you get more details per, say, 100 words when they are lying versus when they are not.  You could stratify based on discrete intervals, such as 0-50 words, 51-100, etc. (or larger ranges), or based on quantiles (e.g. bottom quintile, 20-40%ile, and so on).  This way you may not need a formulaic model that estimates the distribution of # of words and # of details conditioned on the role and subject.


Bad performance on a simple SELECT

Question: I have a very simple SELECT statement that is taking much more time than it should. It only selects from one table with no JOINs, no computed columns. The table is not especially large (3 million rows, small row size). I have an appropriate index for the query (SQL Profile shows it's being used), which has been recently rebuilt (weekly) and the statistics are up to date (daily). I have tried putting the SELECT into a stored procedure, but that doesn't help. I also tried using WITH (NOLOCK), but there's not much improvement. It is frequently but not heavily queried -- it's not in the top 50 queries for our application. The result size is typically 1 - 5 rows. There is a fair amount of INSERT / UPDATE traffic on this table, too, a little less than the SELECT traffic.
The stored procedure with the SELECT is:
CREATE PROCEDURE [dbo].[fetchcurrentichecklistitemanswers] @p_ichecklistitemid Int
AS

DECLARE @ichecklistitemid Int = @p_ichecklistitemid

SELECT * FROM ichecklistitemanswers WITH (NOLOCK) WHERE ichecklistitemid = @ichecklistitemid AND status = 2 ORDER BY ordering ASC

GO

Any thoughts on what else could be slowing down a simple SELECT like this?
[edit -- added execution plan] The query runs fast in Management Studio (instant) but in the application, the query time averages more than 1 second.
Comment: NOLOCK is not a magic go fast button. It comes with some very serious baggage that most people don't fully understand. https://blogs.sentryone.com/aaronbertrand/bad-habits-nolock-everywhere/
Comment: Did you tried your query with execution plan ?
Comment: We need to see the execution plan. perhaps there isn't an index on ichecklistitemid or status? The order by will slow it down too. Could be a huge table... etc
Comment: Parameter sniffing may be an issue, you can try to add `OPTION (RECOMPILE)`
Answer: You could add index on that column:
CREATE INDEX idx ON ichecklistitemanswers(ichecklistitemid)
INCLUDE(status, ordering) WHERE status=2;

Bad performance on a simple SELECT


Change a user's password in ejabberd over xmpp

Question: Is it possible for the admin to change a user's password through XMPP in ejabberd? After I logged in the admin account, I issued the following stanza:
<code><iq type="set" id="change6075" from="email@example.com">
 <query xmlns="jabber:iq:register">
  <username>user1</username>
  <password>code1</password>
 </query>
</iq>
</code>
But it doesn't work, how can I modify a user's password over XMPP using the admin account?
Answer: You can change the user password with the help of mod_admin_extra command:
$ ejabberdctl change-password User Host newPassword
Comment: Is that possible to do via xml or via php script instead of executing commands
Comment: I believe this command spells "change_password" (underscore instead of hyphen) in modern ejabberd.
Comment: @Błotosmętek you're right. That is the correct spelling
Comment: @Błotosmętek, never mind. My bad. Both the hyphen and the underscore versions of the command work.


Deploy a disk image on bare-metal

Question: I try to understand Foreman and other deployment/provisioning systems, and how to use them best. Granted, installing the OS with some kind of prepared answers and scripts - Kickstart, AutoYAST etc. - is the best way for the majority of cases.
But when you want to deploy the same system to bare metal and to the cloud, you're back to images for the cloud part (optimally, constructed through a script, so you have the advantages of treating image construction as code). Now consider that your bare metal is all of the same type; would it not make sense to deploy the cloud image to bare metal, too?
Having some kind of PXE system that pulls the disk image from some place, runs some scripts similar to cloud-init, and reboots? Such a system could even be useful for other provisioning systems. Yet I do not find any of the sort, not even discussions about it, which indicates to me that I am on the wrong path. The FOG project or DRBL might be candidates, but no one seems to write about using them with Foreman?
Answer: You should make a distinction between provisioning software like FOG which works deploying a previously captured HDD image, or Foreman which deploys regular install images adding some already made generic automation scripts.
Both systems are not meant to work together; they pursue different objectives.
Depending on your needs it could be not possible to have a single setup able to provision cloud an bare metal simultaneously then you must have 2 "assets" even when them are surely made out of the same install distro ISO but configured differently.
FOG is good when you want to replicate an already deployed HDD image to exactly the same hardware. Foreman adds to the classic PXE provisioning equation the pre-made scripts but at the end you are just writing/customizing a kickstart/preseed script. Way more complicated if you try to install automated Windows instead of Linux.
You can also use Serva (Automated PXE Server Solution Accelerator) it allows you to offer for network deployment as many assets as you want which are based on distribution ISOs. you can write as you wish your automated scripts for Windows and Linux assets. Serva includes all the required server components (DHCP/proxyDHCP/TFTP/HTTP/RIS/WDS) in a single exe. (I'm related to Serva development)
Comment: Thanks. By now, I found in the Cobbler manual the idea of booting a Clonezilla Live CD with custom profiles and kernel parameters. Or maybe SystemImager.
Answer: Very good question, I am actually working on this workflow. I should have my patch ready in two weeks when I am giving a talk about this at DevConf 2017 in Brno. Check this pull request afterwards.
https://github.com/theforeman/foreman-discovery-image/pull/44
This will be integrated in Foreman Discovery Image and for transport it will use UDP Cast tool.
Answer: Well I do exactly that in our environment.
The work is reduced to a plugin that you can use with foreman, a extension of @lzap foreman discovery image.
Check it out, https://github.com/deltaprojects/foreman_discovery_image_installer
It describes what you need, boiled down to this

Create a OS image using openstack diskimage-builder or a similar tool.
Configure foreman [Create PXE, finish, provision templates and associate with OS].
Run create_image_installer_zip.sh and image_installer.zip copy to your TFTP server.
PXE boot matchine with created templates an watch it install an image to disk, it reboots and runs cloud-init to bootstrap the node.

Deploy a disk image on bare-metal


Perl: Replace many array element with another corresponding array element in a file

Question: I am trying to replace many array element with another corresponding array element in a file, but its taking ages to execute. Is there a simpler approach ? Below is my code:
<code>open( my $in,  '<', "Test.txt")  or die "cannot open Test.txt $!";
open( my $out, '>', "TestFinal.txt") or die "cannot create TestFinal $!";
while( <$in>)
{
    for(my $i=2 ; $i<=$LastRowGlossary; $i++)
    {
        s/$variable[$i]/$vardescription[$i]/g;
    }
    for(my $j=2 ; $j<=$LastRowTable; $j++)
    {
        s/$COVERAGE_TYPE_CODE[$j]/$TCOVERAGE[$j]/g;
        s/$CVG_TEST_CRIT_CD[$j]/$TCVG_TEST_CRIT_TYP[$j]/g;
    }

    print {$out} $_;

}
close $in;
close $out;
</code>
Please advise.
Comment: All the arrays elements are being picked up from an excel sheet. eg: $variable[2] contains "TEMP" $vardescription[2] contains "Temperature" and so on. And the size of each array goes upto 60 or maybe more.
Comment: You should post the content of Test.txt.
Comment: You should probably use some precaution to avoid partial substitutions, such as CAR being replaced in CARCASS.
Comment: Oh Yes! :) ($variable[$i]\b) does the job.
Answer: Sometimes, generating the regex can help:
<code>#!/usr/bin/perl
use warnings;
use strict;

my @variables =    qw/a b c d e f g h/;
my @descriptions = qw/A B C D E F G H/;

my %replace;
@replace{@variables} = @descriptions;

my $string = 'xaxbxcxdxexfxgxhx';

my $pattern = '(' . join('|', map quotemeta, @variables) . ')';

$string =~ s/$pattern/$replace{$1}/g;

print "$string\n";
</code>
Comment: Very nice one...learnt quite a few things in just a single post of yours..thank you..
Comment: @choroba I tried your approach. Really a good one! But still the time taken is same.. :(


Rectangle Theorem

Question: Could someone help me through this problem?
This theorem is already proved:
Suppose f is entire and D is the boundary of a rectangle R. Then
$\displaystyle\int_{D} f(z)\, dz$
Now he must prove this directly from the theorem:
given any rectangle with vertices (a, c), (b, c), (b, d) and (a, d), parameterize the boundary D and verify directly that
$\displaystyle\int_{D}\, dz=$$\displaystyle\int_{D}z\, dz=0$
Comment: What theorem is proved?
Comment: This:Suppose f is entire and D is the boundary of a rectangle R. Then
Comment: You should have an $=0$ after the integral.
Comment: I think I'm missing the point. The functions $z \mapsto 1$ and $z \mapsto z$ are entire so the result follows trivially from the theorem. However, the statement of the problem talks about 'parameterizing the boundary'...
Comment: @copper.hat: Yes, I thought of that after I posted my answer.
Comment: I agree with copper.hat: the point of this exercise would be to verify the theorem *by hand*, not by applying the theorem. That is: parameterize $D$ and calculate the two integrals and check that they are both zero.
Answer: $f(z)=z-1$ is entire, so $\int_D f(z)dz=0$. This translates to $\int_D dz=\int_D z dz$.
Comment: I made a correction in the statement (∫Ddz=∫Dzdz=0), it still validates your proposal?
Comment: Apply the same result for $f(z)=z+1$.

Rectangle Theorem


Como acessar o valor de um ponteiro dentro de uma função no main?

Question: #include <stdio.h>
#include <stdlib.h>
int *Notas_Baixas(float Vet[],int Total_De_Notas, int *Pont_Numero_De_Notas_Baixas){
    int i;
    *Pont_Numero_De_Notas_Baixas = 0;
    for(i = 0; i < Total_De_Notas; i++){
        if(Vet[i] < 5){
        *Pont_Numero_De_Notas_Baixas ++;
        }
    }
    return &Pont_Numero_De_Notas_Baixas;
}
int main(){
int Numero_De_Alunos, Nota, i;
float *Notas;
printf("Digite a quantidade de alunos da turma : ");
scanf("%d",&Numero_De_Alunos);
Notas = (int *) malloc((Numero_De_Alunos * 2) * sizeof(int));
printf("\n");
int Cont_De_Aluno = 1;
for(i = 0; i < (Numero_De_Alunos * 2); i+=2){
    printf("Digite a nota 1 do aluno %d : ", Cont_De_Aluno);
    scanf("%f", &Notas[i]);
    printf("Digite a nota 2 do aluno %d : ", Cont_De_Aluno);
    scanf("%f", &Notas[i+1]);
    Cont_De_Aluno ++;
    printf("\n");
}
for(i = 0; i < (Numero_De_Alunos * 2); i++){
    printf("%f ", Notas[i]);
    printf("\n");
}
int Pega_Nota_Baixa;
int *Numero_De_Notas_Baixas = Notas_Baixas(Notas,(Numero_De_Alunos * 2),&Pega_Nota_Baixa);
printf("\nQuantidade de notas baixas pelo retorno = %d",Numero_De_Notas_Baixas);
printf("\nQuantidade de notas baixas pelo ponteiro = %d", Pega_Nota_Baixa);
return 0;
}

Preciso acessar o contador ponteiro Pont_Numero_De_Notas_Baixas dentro da função Notas_Baixas no main, só que a saida é sempre 0.
Comment: Sua pergunta parece ter alguns problemas e sua experiência aqui no Stack Overflow em Português poderá não ser a melhor por causa disso. Queremos que você se dê bem aqui e consiga o que quer, mas para isso precisamos que você faça a sua parte. Veja algumas orientações que vão te ajudar: [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045) ([versão curta](https://pt.meta.stackoverflow.com/q/8089/101)). Se a solução for muito simples ainda é possível que alguém o faça nos comentários.
Answer:
Preciso acessar o contador ponteiro Pont_Numero_De_Notas_Baixas dentro
da função Notas_Baixas no main, só que a saida é sempre 0.

O pouco que deu a entender do seu problema, você está recebendo um ponteiro para Pega_Nota_Baixa na função Notas_Baixas, manipulando o seu valor e retornando um outro ponteiro apontando para ele.
De toda forma, se este for o seu problema, você não precisa retornar o dado de volta uma vez que está enviando ele como parâmetro da função. O código abaixo é um exemplo disso.
#include <stdio.h>
#include <stdlib.h>

void Notas_Baixas(int *Pont_Numero_De_Notas_Baixas){
    *Pont_Numero_De_Notas_Baixas = 5;
}

int main() {
    int Pega_Nota_Baixa;
    Notas_Baixas(&Pega_Nota_Baixa);

    printf("%d", Pega_Nota_Baixa);
    return 0;
}


mysql: multi slave replication but one slave to replicate only single table of specific database

Question: Innodb table to be more specific.
Setup would be one master and two slaves.  One of the slaves would only be replicating a single table on a specific database while the other slave replicates two full dbs.
Is this possible?
TIA
Answer: Use this option in the slave's my.cnf
<code>    --replicate-do-table=db_name.tbl_name
</code>
http://dev.mysql.com/doc/refman/5.1/en/replication-options-slave.html#option_mysqld_replicate-do-table
Comment: Straightforward and concise. +1 for brevity !!!
Comment: "Each slave receives the entire binary log but processess.." Isn't this a huge waste of data (expensive in AWS) for servers with HUGE (GBs in a day) binlogs? Is there a way to configure the master not to send this data to specific slaves?


being $\mathbf{w}$ a vector, how do I calculate the derivative of $\mathbf{w}^T\mathbf{w}$?

Question: Let's say that I have a vector $\mathbf{w}$.
How can I calculate the derivative in the following expression?
$\frac{\mathrm{d}}{\mathrm{d}\mathbf{w}}\mathbf{w}^T\mathbf{w}$
Update: found these useful definitions
Comment: Traditionally, it means "a vector whose elements are the derivative of what follows with respect to each coordinate." For instance, if $\mathbf{w} = (x,\ y)$, then $\frac{d}{d\mathbf{w}} \left( x^2+y^2\right) = (2x,\ 2y)$.
Comment: Yes, in essence. Which makes sense. Because $w^Tw$ is the closest thing you can get to $x^2$ in a vector sense, and hence you would expect the derivative to look something like $2x$, as well.
Comment: Start with a simple example and build from there. The pattern should be clear.
Comment: What's the meaning of $\dfrac{d}{d\mathbf{w}}$?
Comment: @egreg, I am pretty sure this is common notation in optimization, various computer-related fields. Meant o be a directional derivative, so here it would be $w \cdot \nabla f,$ with $f(w) = w \cdot w$ this time.
Comment: @egreg: I am not sure how to express the derivative with regards to a vector $\mathrm{w}$. Maybe it's a shorthand for $\frac{\mathrm{d}}{\mathrm{d}w_1}\frac{\mathrm{d}}{\mathrm{d}w_2}\ldots$, but I am not even sure if this is what is meant with "derivative with regards to a vector"
Comment: @Arkamis: I am surprised to see that the derivative you wrote is not a scalar. Does this mean that the solution is $2\mathbf{w}$ ?
Answer: In order to find the derivative let us calculate the h-linear term,
$$\begin{equation}
\begin{split}
(w+h)^T(w+h)-w^Tw&=(w^T+h^T)(w+h)-w^Tw\approx\\
&\approx h^Tw+w^Th= (h^Tw)^T+w^Th=2w^Th
\end{split}
\end{equation}$$
Hence the derivative is: $2w^T$.
Rather than $2w$. Indeed the gradient is not really a column- but a row-vector (or covector, or dual vector).
Answer: It is easier to see it in component form.
Let $\hat{x_i}$ be the unit vector in the $i$-th direction, then we can express a vector as
$$\mathbf{w}=\sum_{i=1}^{n}w_i \hat{x_i} \tag{1}$$
And
$$\frac{d}{d\mathbf{w}}=\sum_{i=1}^{n}\hat{x}^T_i \frac{d}{dw_i} \tag{2}$$
So
$$\mathbf{w}^T \mathbf{w}=\sum_{i=1}^{n}w_i^2 \tag{3}$$
$$\frac{d}{d\mathbf{w}}(\mathbf{w}^T \mathbf{w})=\sum_{i=1}^{n}2w_i\hat{x}^T_i =2\mathbf{w}^T\tag{4}$$
EDIT: I made a minor correction ($\hat{x}_i$ to $\hat{x}^T_i$)in (2) and (4) based on rych's suggestion. Now the final results is $2\mathbf{w}^T$
Comment: should be $2w^T$, no?
Comment: I think that you are right!
Comment: @rych Where is the final transpose coming from?
Comment: @alonsos. I made a minor change in my answer. Please take a look. Thanks


Conexão com banco de dados ASP.NET CORE 2

Question: Estou iniciando com asp.net, mas especificamente com asp.net core 2.
Estou lendo a documentação contida no docs.microsoft.com.
Porém, tenho uma dúvida. Como faço conexão a um DB?
No PHP utilizo PDO, porém no asp.net core 2 utilizo o que?
Comment: Você vai sentir uma diferença bem grande. Como você esta na tecnologia mais recente te indico conhecer o Nuget (controlador de pacotes) e o Entity Framework (ORM)
https://docs.microsoft.com/en-us/nuget/
https://docs.microsoft.com/en-us/ef/core/
Comment: Então, estou estudando o Entity Framework Core, porém eu realmente ainda não entendi a conexão em sí. O uso dele sim. Até aonde entendi ele é usado para modelagem dos dados. Obrigado pelos links! Vou olhar.
Comment: No Code First as tabelas são geradas a partir das entidades (o banco já deve existir), mas você pode gerar as entidades a paritr de um banco já existente. Lembrando que o Entity Framework é nativo do SQL Server pro demais bancos tem que baixar a versão especifica. A conexão fica dentro do webconfig e o nome da conexão é passada como paramentro no DBContext. Ve esse meu repositorio ve se te da uma luz, dentro da pasta model
https://github.com/krismorte/LigueMe
Comment: Entendi, por exemplo se eu for conectar no SQL dB da Azure eu teria que conectar lá. Mas se a tabela já existe no banco de dados, o dbset vai rodar novamente?
Comment: Sim, também da certo.
Comment: Krismorte, uma outra dúvida surgiu. O que é o ado.net? Pelo que eu vi ele é uma tecnologia .Net para conexão com o dB. Ele substitui o entity? Cara, desculpa as dúvidas mas esse mundo .Net é bem grande em vista do Photoshop e com várias tecnologias embarcadas.
Comment: ADO.NET é um conjundo de classes predefinidas dentro da plataforma va~çao de banco de dados a objetos visuais. Conexão ado.net normalmente é fetia através apenas do web.config, nos seus objetos faz referência apenas ao nome da conexão.
Comment: Estou começando a entender. Hoje eu li mais uma parte da documentação do entity. Percebi que o dbcontext faz a conexão em si e ele usa ado.net nas entranhas. Para conectar em um dB Azure eu pego a string ado net, coloco no appsettings e faço o dbcontext pelo entity. Ainda não descobri como salvar os dados, não cheguei nisso.
Answer:
Instale uma versão do SQL server communtity para você poder fazer alguns testes.
crei um novo projeto em asp.net core incluindo autenticação individual. Por padrão o Asp vai criar a string de conexão no arquivo appsetting.json parecido com a linha abaixo:

<code>"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication3-AE3FA43F-A3AF-4A87-8999-727298B6B01F;Trusted_Connection=True;MultipleActiveResultSets=true"
  },</code>

Crie os seus modelos de classes na pasta Model do tipo: cliente, empresa e seus dados por exemplo
public class cliente
   {
<code>  [Key]
  public string nome { get; set; }
  public string cpf { get; set; }
</code>
}
Adicione um controller usando a opção Controlador MVC com exibições, usando o Entity FrameWork
escolha o modelo de classe que quer criar as views, controllers
esolha o modelo de dados, provavelmente você vai encontrar "ApplicationDbContext" como padrão

é nessa classe "ApplicationDbContext" que você vai encontrar o que procura. As configurações de conexão, poderá configurar algumas propriedades das tabelas, primary key e etc..
No startup.cs você poderá configurar o tipo de banco para MySQL ou useSqlServer, eu uso o MySql. O padrão é o sqlServer e vc vai encontrar nesse arquivo
<code> services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
</code>
Lembra do arquivo appsetting.json? é aí que é chamada a string de conexão com o bando de dados "DefaultConnection".
espero ter ajudado.


Pass matrix as argument

Question: I want to pass two matrices as argument. These matrices have different size and i don't understand how i have to do this work:
#include <stdio.h>
#include <stdlib.h>

void f(int m[3][], int n);

int main()
{
  int A[3][3]={{1,2,3},{4,5, 6},{7,8,9}};
  int B[3][2]={{1,2},{3, 4}, {5, 6}};

  f(A, 3);
  f(B, 2);

  return 0;
}

 void f(int m[3][], int n)
 {
    int i,j;
    for(i=0;i<3;i++)
    {
      for(j=0;j<n;j++)
       printf("%5d", m[i][j]);
    }
    return;
 }

How can I do this?
Comment: What is not working? Are you getting a compile-time error?
Comment: Are you using [C89](http://en.wikipedia.org/wiki/C89_(C_version)#C89), [C99](http://en.wikipedia.org/wiki/C99), or some compiler-specific dialect of C?  There are differences in the ways that you can pass matrix arguments to functions, depending on which language version your compiler is configured to accept.
Comment: @HunterMcMillen yes main.c|5|error: array type has incomplete element type
/main.c|12|error: type of formal parameter 1 is incomplete
Comment: Check the [C FAQ 6.18 and 6.19](http://c-faq.com/aryptr/index.html).
Answer: The only safe way that I know of to do this is to include the matrix dimensions in the parameters, or make some kind of matrix struct
Option A) dimensions as parameters
void f(int **m, int w, int h )
{
    int i,j;
    for(i=0;i<w;i++)
    {
      for(j=0;j<h;j++)
         printf("%5d", m[i][j]);
    }
    return;
}

Option B) Use a struct
typedef struct Matrix
{
    int w, h;
    int** m;
} Matrix;

void f ( Matrix *m )
{
    for ( int i = 0; i < m->w; ++i )
    {
        for ( int j = 0; j < m->h; ++j )
        {
            printf(%5d", m->m[i][j]);
        }
    }
}

Comment: You can have interfaces like `void f(size_t n, int m[3][n])` with real 2D matrices with dynamic bounds as a parameter. You may have a look at https://gustedt.wordpress.com/2011/01/13/vla-as-function-arguments/
Comment: Your answer is ok for C89, I'd just like to note that for C99 much easier solutions exist.
Comment: I am unfamiliar with the C99 standard.  Out of curiosity, what is added in C99 that would make for easier solutions?

Pass matrix as argument


AWS Cost for Uploading to S3 and immediately transitioning to glacier

Question: I have a client uploading multiple TB of data to Glacier. They did a snowball that got 65 TB of data, and they are going to do the remaining ~25 via upload. Currently they are uploading directly to Glacier with FastGlacier, but that tool is running on their sole Windows machine (a full Mac shop) and is constantly crashing from queuing so much data. Additionally, this program leave a lot to be desired in regards to searching/browsing the store, as in order to view files in the Glacier you need to download the inventory (with the 4-6 hour lead time).
For consistency, we'd like to upload to the S3 share that we used for the Snowball, with the same 0 day transition to Glacier using a lifecycle management rule, but don't want to incur massive costs of S3 for it. I know S3 costs is based on average usage over the month, but not sure how to estimate this.
Comment: Be sure you thoroughly understand that "Glacier" != "the S3 Glacier Storage Class."  The two are very different.  I would not use Glacier itself without a rock solid storage management and indexing system in front of it.  Glacier is raw, low-level, expert mode, and almost completely opaque.  The S3 Glacier storage class is entirely different and much more usable, unless you need something accessible only by using Glacier itself, like vault locks.  Importantly, as documented, you cannot access data loaded into one service via the other service.
Answer: The AWS storage services overview whitepaper (two links) says "You can specify an absolute or relative time period (including 0 days) after which the specified Amazon S3 objects should be transitioned to Amazon Glacier".
S3 lifecycle rules say you can't transition S3 data to Infrequently access storage class until 30 days after upload. However you can transition to glacier immediately - "0 days" appears to be a valid setting.
I tried this myself. I created a new bucket with a lifecycle rule to transition to glacier after 0 days. I uploaded a small file using S3 standard class. The file changed to the glacier storage class between 5 and 8 hours after it was uploaded. I can't say more precisely because I don't see any logs about this, and I only checked occasionally.
You could consider using a storage gateway, but that relies on running a virtual machine on premises. It stores data in S3 so you'd have to transition it using lifecycle rules. An upload client may be easier, given the time that would take.
There are Glacier clients that run on mac, such as Freeze, Glacier Uploader, and others.
Comment: I don't see where it says you can't transition to Glacier before 30 days.

> "Objects must be stored at least 30 days in the current storage class before you can transition them to STANDARD_IA. For example, you cannot create a lifecycle rule to transition objects to the STANDARD_IA storage class one day after creation."

So it looks like that rule is for transfering to IA rather than Glacier, unless I missed something.
Comment: You're right, and I just tried it to be sure. The user interface let me transition to glacier after 0 days. I hope that 0 doesn't represent "never". The API suggests that 0 is a valid transition time http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html
Comment: That's what I did as well (though I set it to 1 day as I was also paranoid that 0 was never). I just checked their invoice and with a 1 day transition for ~68 TB of data it looks like it counted it as 2.3 TB-month, so it looks like it didn't prorate fully, so I think this is something I'm going to pitch and have them move to S3->Glacier. If you find out that 0=immediate, that would be even better!
Comment: I tried it out, see my update above (paragraph two).
Comment: It looks like the transition time needs to be a "positive integer", which would imply that 1 day is the minimum time you can set. https://docs.aws.amazon.com/AmazonS3/latest/API/API_Transition.html
Comment: I read in the life cycle documentation that said that the work is done at midnight UTC, in case that info is useful to anyone. The document that dmohr linked also says it: "The time is always midnight UTC."


How do you work with include pages in jsp or php or the likes without getting IDE / Editor warnings for CSS classes?

Question: If the CSS files for your site are referenced in the parent page, obviously you can use those CSS rules and classes in the sub-page or "included" page (like a jsp include or a php include).  That will run as expected in the browser.  BUT, if you are using an IDE or smart text editor of some kind (I'm using Netbeans), you will get warnings about the CSS elements in the sub-page (a .jspf for example) unless that file has a redundant reference to the css files.  Is there a work-around for this? I don't want to have to reference the CSS files in both my jsp and my jspf (jsp include).
Answer: One technique I've used is to abandon jspf files in favour of a templating system where if you want to include something from a template, the template is actually a full page of which part is marked to be included.  I actually use a home-grown template system for this, but my understanding is that thymeleaf (http://www.thymeleaf.org/) offers the same feature.


w32tm /resync not working instantly

Question: This Question is mostly for other people to learn from and to satisfy my own curiosity if someone knows why it does the following.
We had a problem with our DC not having the right time due to it being virtualized, that has since been fixed. But some of our clients and servers needed the updated time. So I tried running the following commands as admin w32tm /query /source to make sure it was getting the time from our Domain Controller then w32tm /resync to sync the time, both commands had no errors but the time didn't change.
I see something similar to the following line in the event logs.
The system time has changed to 2014-09-08T21:31:33.328000000Z from 2014-09-08T21:31:33.342455400Z.
So I try the command a few more times with no change and go search around on Google for a bit, only to come back and find the client has the right time now, but nothing new in the event logs.
I tried on a second client with the same result but I didn't leave the client but poked around the logs a bit and out of pure luck I looked down at the clock and noticed that time was getting closer to the real time. It was slowing drifting back to the right time. Every now and then the clock would go up by 2 seconds, or a second would change to the next digit before a whole second had gone by. It would do this until the clock had reached the right time.
My question is why does it do this? why not just change the time to the correct time instantly like my personal computer does when I sync the time to an NTP server?
Comment: CHmmond, I'm with the same problem with the virtualized DC, could you point me how you solve the problem? thanks!
Comment: I have just discovered that my personal workstation (Windows 10 Enterprise 20H2) does the same.
Answer: Apparently this is by design:

If the local clock time of the client is less than three minutes ahead
  of the time on the server, W32Time will quarter or halve the clock
  frequency for long enough to bring the clocks into sync. If the client
  is less that 15 seconds ahead, it will halve the frequency; otherwise,
  it will quarter the frequency. The amount of time the clock spends
  running at an unusual frequency depends on the size of the offset that
  is being corrected

http://blogs.msmvps.com/acefekay/2009/09/18/configuring-the-windows-time-service-for-windows-server/
I can't find a reference that explicitly explains WHY it is designed so, but I would guess that the aim is to avoid sudden jumps in case other applications are using the internal clock to time operations.  So if the offset is low then the 'convergence' method is used by adjusting the local clock rate.  If the difference is 3 minutes or greater then the risk of Kerberos authentication failing (>5 minutes clock diff) is considered more serious than the risks involved in 'jumping' the local clock, so the clock is just reset rather than converging
Comment: You learn something new every day!

w32tm /resync not working instantly


what is the difference between 'metadata.labels' and 'spec.template.metadata.labels'

Question: reading the kubernetes docs, it is not very clear to me what is the difference between
specifying labels at the top-level metadata key, versus at the spec level.
Consider:
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    run: nginx
  name: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      run: nginx
  strategy: {}
  template:
    metadata:
      labels:
        run: nginxv1
    spec:
      containers:
      - image: nginx
        name: nginx

which I have copied from https://stackoverflow.com/questions/54837981/k8s-significance-of-spec-template-metadata-section , where my google searching landed me.
What's the difference between the two labels that are set in this manifest?
Answer: metadata.labels sets the labels that apply to the deployment.
spec.template.metadata.labels sets the labels that apply to pods management by the deployment.
The values in spec.selectors.matchLabels are used to select pods, so they need to match the labels in spec.template.metadata.labels; they have nothing to do with the Deployment's metadata.labels.


Date format for ics file

Question: I see an date format for ics file from other article as
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");

However, I can't understand what I've got from Outlook ics file as
DTSTART:16011104T020000

Where the year 1601 came from?
Answer:
"Year 1601 (MDCI) was a common year starting on Monday of the Gregorian
  calendar and a common year starting on Thursday of the 10-day slower
  Julian calendar.
January 1 of this year (1601-01-01) is used as the base of file date
  and of Active Directory Logon dates by Microsoft Windows.
It is also the date from which ANSI dates are counted and were adopted
  by the American National Standards Institute for use with COBOL and
  other computer languages" [1]

http://en.wikipedia.org/wiki/1601
Comment: Thank you. So does it mean do not need to care about year? Can I make the date for every year as 1601 for DST start date?
Comment: @Sanghoon Yes, this is simply the default so any dates you do not change will always be 1601.

Date format for ics file


TCP/IP ack loss between firewall and server

Question: Scenario:
Client connects to Server using TCP/IP.
Issue:
During initial TCP/IP connection setup, the ACK packet [3rd step in TCP] sent from Client to Server has crossed the firewall [evidence from tcpdump] but not reached the server. Therefore server ignores all the packets sent from Client after ACK packet [3rd step in TCP] and Server tries to send SYN/ACK packet [2nd step in TCP] after few seconds to Client again [and the step repeats]. Finally Server sends Reset request to Client.
When we captured the network traffic using wireshark in the server, the ACK packet [3rd step in TCP] never came to the server.
This issue happens for the first time, if we attempt to TCP/IP connect when the connection was not used in past 10 minutes. But within 10 minutes, if we perform TCP/IP connection, it connects successfully. So, the connection fails only for the first attempt when tried after 10 minutes anytime.
We could not spot where and what the issue is.
Please can  you provide your inputs?
Thank you.
Saravanan N
Comment: Thanks for sharing your inputs. The issue was the packets were getting lost in the OS where firewall is running. It got solved when the firewall Operating System was patched.
Comment: Look for any network filtering devices between the firewall and server. Otherwise your tcpdump on the firewall is probably monitoring the wrong interface.
Comment: Somewhere, there's a stateful firewall that times out connection state in ten minutes.
Answer: Thanks for sharing your inputs. The issue was the packets were getting lost in the OS where firewall is running. It got solved when the firewall Operating System was patched

Saravanan N


Property does not show value

Question: I define a property in a class like:
type Customer() =
    let mutable _lastName = String.Empty
    member val LastName = _lastName with get

And in the method QueryData I assign a value to _lastName:
member self.QueryData () =

            // CODE
            let addressData = bp.GetStructure("PE_PERSONALDATA")
            _lastName <- addressData.GetString("LASTNAME")
            null
        | RfcCommunication ex ->
            let basedComm = ex :> Exception
            basedComm
        | RfcLogon ex ->
            let basedLogon = ex :> Exception
            basedLogon
        | RfcAbapRuntime ex ->
            let basedAbap = ex :> Exception
            basedAbap

In the main function I created an instance of Customer() and read the LastName property:
[<EntryPoint>]
let main argv =

    let customer = CustomerBapi.Customer()
    let ex = customer.QueryData()

    if ex <> null then printfn "%s" ex.Message
    printfn "%s" customer.LastName

The result is empty string. I tried to debug the program and see that _lastName is not empty

Why is the LastName property is empty?
Answer: Your property should look like this:
member this.LastName with get () = _lastName

The type of property you are using is passing _lastName as the value to initialise it with.

Explanation from MSDN:

Private values that hold the data for properties are called backing
  stores. To have the compiler create the backing store automatically,
  use the keywords member val, omit the self-identifier, then provide an
  expression to initialize the property. If the property is to be
  mutable, include with get, set. For example, the following class type
  includes two automatically implemented properties.  Property1 is
  read-only and is initialized to the argument provided to the primary
  constructor, and Property2 is a settable property initialized to an
  empty string:

type MyClass(property1 : int) =
    member val Property1 = property1
    member val Property2 = "" with get, set

Property does not show value


python lockf: LOCK_EX works but LOCK_SH doesn't

Question: I'm puzzled by the behaviour of the lockf function from the python fcntl library: I can't get a shared lock, while the exclusive one works:
In [1]: import fcntl

In [2]: f = open('file', 'w')

In [3]: fcntl.lockf(f, fcntl.LOCK_SH | fcntl.LOCK_NB)
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-3-5d23c6a5f968> in <module>
----> 1 fcntl.lockf(f, fcntl.LOCK_SH | fcntl.LOCK_NB)

OSError: [Errno 9] Bad file descriptor

In [4]: fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)

In [5]:

The error code corresponds to EBADF from the http://man7.org/linux/man-pages/man3/lockf.3.html, which does not make much sense, as f is a writable open file descriptor.
Any ideas?
(Python 3.6.9, Ubuntu 18.04.4 LTS)
Answer: fcntl.lockf sure looks like it should be a wrapper around POSIX lockf, but it's not. POSIX lockf doesn't even have shared locks.
fcntl.lockf is a wrapper around POSIX fcntl. LOCK_SH corresponds to F_RDLCK, which requires a file descriptor opened for reading.
While you're at it, you might want to read about the problems with file locking.
Comment: Thanks a lot! I read that post, and this one as well: https://gavv.github.io/articles/file-locks/ (mentioning it here, as it is super informative, even though it does not deal with what Python did with lockf).
Comment: Another comment for people from the future: opening with `a+` allows for both types of locks on the same file descriptor.


error: free(): invalid next size (fast)

Question: Here's the code:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = malloc(sizeof(int));
    int n;
    printf("input number:\t");
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
    }
    for(int i = 0; i < n; i++) {
            printf("%d", arr[i]);
    }
    free(arr);

    return 0;
}

It runs until the scanf and then it just crashes:
1234875770417Aborted (core dumped)

I've looked at the other posts that are similar to this, but none of them solve my problem.
Comment: You allocated memory only for one object of the type int  int *arr = malloc(sizeof(int)); So n may not be greater than 1.
Answer: The initializer in this declaration
int *arr = malloc(sizeof(int));

allocates memory only for one object of the type int. So in this case n may not be greater than 1.
You should write at least
int main( void ) {
    int n;
    printf("input number:\t");
    scanf("%d", &n);
    int *arr = malloc( n * sizeof(int));
    //...

Also it would be better to declare the variable n as having the type unsigned int instead of the type int.
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )

Here is an updated program.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    unsigned int n = 0;

    printf( "input a non-negative number:\t" );
    scanf( "%u", &n );

    int *arr = malloc( n * sizeof( int ) );

    for ( unsigned int i = 0; i < n; i++ )
    {
        scanf( "%d", &arr[i] );
    }

    for ( unsigned int i = 0; i < n; i++ )
    {
        printf( "%d ", arr[i] );
    }
    putchar( '\n' );

    free( arr );

    return 0;
}

Its output might look like
input a non-negative number:    10
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9

Comment: int *arr = malloc( n * sizeof( int ) );
so basically this is n elements and not only one such as:
int *arr = malloc( sizeof( int ) ); ?
Comment: @Mytavaz Yes the memory is allocated for n objects of the type int.
Answer: Since you allocated memory only for one integer using int *arr = malloc(sizeof(int)); and you are trying to store n elements into that so it crashes.
First scan the n value and then allocate memory for n elements using malloc().
int main() {
        int n;
        printf("input number:\t");
        scanf("%d", &n);
        int *arr = malloc(n*sizeof(*arr)); /*it's generic it allocated memory for any type */
        if(arr == NULL) {
           printf("memory allocation failed \n");
           exit(0);
        }
        for(int i = 0; i < n; i++) {
                scanf("%d", &arr[i]);
        }
        for(int i = 0; i < n; i++) {
                printf("%d", arr[i]);
        }
        free(arr);
        return 0;
}

error: free(): invalid next size (fast)


Is there a way to do SSH password-less login when the server only allows keyboard-interactive authentication?

Question: Suppose I've got a server foo.com which only allows keyboard-interactive authentication, and that I can't change this. This means I can do,
sshpass -p PASSWORD ssh foo.com

but I can't create public/private keys to log in without a password.
If I want to automate getting to this server, i.e. ssh without password, I could just create an alias ssh_foo="sshpass -p PASSWORD ssh foo.com", but then I have to create aliases for scp, for sftp, and in general it won't work for any other programs that use these, e.g. graphical programs based on sftp which mount remote folders. So I'm looking for a more generic solution.
In particular, is there any way to set up my .ssh/config file to allow password-less login in this case? This should then work for everything. I feel like some clever combination of ProxyCommand and LocalCommand might do it, but I can't figure out what.
(Note, I do understand the security implication of this, I'm just curious if you can do it)
Answer: ssh -p is for specifying the remote port, SSH doesn't take passwords from the command line or from files.
The easiest way to achieve this is to multiplex the connection, login once with ssh -fN (which might be automatable by piping the password) which will create the control master, and use this connection to multiplex all others. Look at the ControlMaster and ControlPath options in your friendly man 5 ssh_config.
Otherwise the use of a terminal manager à la tmux/terminator might be your only resort, but that would mandate wrapping all commands that rely on SSH.
Comment: Note it was `sshpass -p`, not `ssh -p`. But the `ControlMaster` is an interesting idea I hadn't thought of, thanks. I will play with it.


Tela "loading" na activity

Question: Gostaria de poder saber ou entender como se coloca na tela um loading.
Meu app faz consulta em um webservice, e as vezes dependendo da conexão ele demora para trazer as informações. E o app fica todo branco. Para o usuário final parece que travou. Então gostaria de colocar uma tela de loading.
Código de requisição HTTP
<code>    private static final String BASE_URL = "https://LINK DO MEU Json";
private static Retrofit mRetrofit;
private static ApiNOMEDOPROJETORequestInterceptor mInterceptor;
private static Gson mGson;
private static OkHttpClient mClient;

public static Retrofit getInstance() {
    if (mRetrofit == null) {
        //create Gson
        mGson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();

        //create interceptor
        mInterceptor = new ApiNOMEDOPROJETORequestInterceptor();

        //create httpClient with interceptor
        mClient = new OkHttpClient.Builder().addInterceptor(mInterceptor).build();

        //create retrofit
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(mGson))
                .client(mClient)
                .build();
    }
    return mRetrofit;
}
</code>
}
Comment: Edite a pergunta e coloque o código que faz a consulta ao webservice.
Comment: Pelo o que eu entendi, esse todo branco que o aplicativo fica durante o procedimento é porque não tem realmente informação na tela. Certo? Caso não seja por isso, mas porque a tela travou, a solução começa colocando a requisição ao web service em uma thread separada. Sobre a questão da sua tela de loading, particularmente, eu não criaria uma tela para isso, mas usaria um ProgressBar, exibindo quando a requisição iniciasse e escondendo quando ela fosse finalizada. Por favor, nos mostre seu código como o @ramaral solicitou para podermos te mostrar um exemplo.
Comment: @YoungerAuad acho que o que eu preciso é isto mesmo. Vou editar a minha pergunta e colocar o código da requisição.
Comment: Tem que capturar os dados do webservice em segundo plano, senão a tela fica travada esperando acabar a requisição.
Answer: Bom dia Artur, provavelmente você usa a classe async pra fazer esta conexão, tente usar o código abaixo. Quando chama a classe ela mostra um Dialog pro usuário, espero ter ajudado.
<code>public abstract class AsyncData extends AsyncTask<String, String, String> {

    protected final Context mContext;
    protected final String mMsqInfo;
    protected ProgressDialog mDialog;

public AsyncData(String msgInfo, Context context) {
    mContext = context;
    mMsqInfo = msgInfo;
}

@Override
protected void onPreExecute() {
    if (mIsShowDialog){
        mDialog = new ProgressDialog(mContext);
        mDialog.setTitle(R.string.app_label_wait);
        mDialog.setMessage(mMsqInfo);
        mDialog.setCancelable(true);
        mDialog.show();
    }
}

@Override
protected String doInBackground(String... params) {
    // seu código...
}

@Override
protected void onPostExecute(String results) {
    super.onPostExecute(results);
    if ((mDialog != null) && ( mDialog.isShowing()) {

        mDialog.dismiss();
        mDialog = null;
    }
}
</code>
}
Comment: Arthur - xará - você viu o código que postei depois ?

Tela "loading" na activity


Interpreting a Schoenfeld plot for Cox PH univariate model and correcting for violation of PH assumption (R)

Question: I am having trouble understanding how to interpret a Schoenfeld plot and how to correct for the violation of PH assumption in Cox PH model when using continuous numeric covariates.
Here is the code I am using to call the model, the variable I am investigating is average spring/summer precipitation (AS_avg_total_p_mm) over the study period (10 years):

The image and plot below is the output of the cox.zph() test, and the test graphed using ggcoxzph().

While the statistics indicate the model violates the PH assumption, I am unsure how to correct for this. I have read about introducing a time interaction variable into the model (either by var:time, or tt(var) and adding a tt function), but I am unsure how to do this properly. My knowledge of statistics and modeling is very basic.
When I add the var:time variable to my model, the covariate and the interaction are significant, but even further fail the cox.zph() significance test (image below). I have also read that this might be an inappropriate approach.

Introducing a tt(var) hinders me from using cox.zph(), as the function does not support the use of this.
Therefore:

How can I implement a time interaction and still test that my model is following the rules?

How do I interpret a Shoenfeld plot that looks like mine? Most that I see example wise are scattered or follow some specific pattern. What should a "good" plot look like?

Is the failure of this assumption drastic enough to warrant changes to my model? Is this up to my interpretation?

Does my sample size play a role in how these tests are behaving? It is quite large.

Please let me know if any additional information is needed here and forgive me if my question is redundant. I have tried many examples to solve my problem. Thank you for your time!
Comment: Welcome to Cross Validated! Try fitting your continuous predictor flexibly, like with a regression spline. It's unlikely that there's a strictly linear association between that predictor and the log-hazard of an event, and a poorly specified form for a continuous predictor can show up like a PH violation. Also, you might be using an old version of ggcoxzph, with a serious coding error that makes its plots nearly useless. Use the standard survival function tools.
Comment: See section 4.2 page 21 of https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf for why your time:covariate interaction term is problematic.
Comment: Thank you for your comments, I actually just saw the post where you mentioned issues with ggcoxzph and have been plotting in accordance to the survival package. Additionally, looking at the pdf, specifically the spline viginette, I am having a bit of trouble understanding the effective df. From my understanding, pspline creates 3 df for each variable? How do I choose df for the model? I did a test with the smoothHR package indicating my df = 3.06, however when I use 3 4  or 5 df my model fails the cox.zph test, passing when df = 6. Should I be concerned the model is not passing still?
Comment: and to clarify this is without a time interaction, only the non-linear covariate by itself. Should I try pspline and a time interaction?
Answer: Section 6.6 of Therneau and Grambsch discusses causes of non-proportionality. A couple of issues there should be dealt with before you jump to assuming that there your predictor requires a time-varying coefficient.
First, your model allows for only a linear association between your continuous predictor AS_avg_total_p_mm and the log-hazard of an event. Strictly linear associations are seldom correct. Mis-specifying the functional form of a continuous predictor's association with outcome can lead to an apparent violation of proportional hazards (PH), while there might be no violation if that functional form were specified properly. See this page, for example. If you perform a flexible fit in the Cox model,* for example with a spline, your problem might go away.
Second, your model only includes that one predictor. Omitting any outcome-associated predictor from a Cox model can lead to bias in the coefficient estimates for included predictors and to apparent violations of PH, violations that would also disappear if you didn't omit that predictor. If you have information on other variables that might be associated with outcome, based your understanding of the subject matter, include them.
With 259 events you have a lot of potential flexibility in dealing with these issues. Frank Harrell recommends, as a general strategy in regression modeling, to decide how many degrees of freedom (df) you can afford to spend (coefficients to estimate, adjusted for penalization), to decide where to spend them, and then to spend them. With 259 events, the rule of thumb of about 15 events per df in survival models means that you could probably afford to spend 15 df. That allows you to include several additional predictors while including a very flexible fit of AS_avg_total_p_mm.
There are several different approaches to smooth fitting of continuous predictors, outlined on this page. The ps() function provided in the survival package is a particular type of penalized smoothing spline. The penalization means that the effective number of degrees of freedom used up is smaller than the number of coefficients. An example in Section 5.8.3 of Therneau and Grambsch uses up only 4 degrees of freedom for 13 coefficients. You also could consider an unpenalized regression spline; see Section 2.4 of Harrell's Regression Modeling Strategies.
Even if PH is violated, there might be no need to find the function of time that fits the predictor's coefficient. First, as AdamO frequently points out (for example here), the coefficient of a Cox model is then a type of time-averaged value. If you use robust standard errors (cluster() term), you can still do valid inference. Second, the plot of the smoothed Schoenfeld residuals over time is the estimated form of the coefficient's value over time. That is probably more useful to the reader than the results of a numerical fit. And, as you've learned, there's no good way to document that your numerical fit solved the PH problem except for showing that the shape of the numerical fit matches the
shape of the Schoenfeld residual plot.

*I mean the Cox model of survival here without any time-varying covariate, not the model that tries to accommodate a general form of a time-varying coefficient as in Section 4.2 of the time-dependence vignette. With a continuous predictor in a Cox model, it's critical to distinguish the functional form of its association with log-hazard from the functional form in time of its potentially time-varying coefficient. You appreciate that, as indicated in a comment, but this needs to be written for those that might later come upon this page.
Comment: thank you for the explanation, I am extremely grateful as it has helped me tremendously. I have been implementing more variables into my model, fitting the non-linear variables with pspline and assigning df appropriate to # of events. The issue I am running into is validating the model with cox.zph() and schoenfeld plots. Some of my variables look very flat and in my opinion acceptable, however the test indicates some variables and the model are still significantly non linear. Should I take this test with a grain of salt and go off of the plot? How does this effect the power/validity?
Comment: Additionally, some variables fit with pspline indicate that the linear form is non-significant in the model while the non-linear form is. Does this show that the spline is ineffective in correcting the proportionality issue? Should I remove variables that are unable to be corrected due to a lack of power? I do not really want to do this as they are important to my analysis. Should I provide model and test outputs for clarification on my question?
Comment: and just to add, I have been plotting the schoenfeld residuals with plot() rather than the previous method where issues were identified with the code. thanks again!
Comment: @TylerBrown unless your model is using up more than about 15 degrees of freedom with your 259 events, don't omit predictors or spline df. If the fit of a continuous predictor is improved by a spline over a linear fit in in the Cox model, that's good. That's not guaranteed to fix PH, however.
Comment: @TylerBrown  If PH is violated, see [this answer](https://stats.stackexchange.com/a/347783/28500) or several others by [AdamO](https://stats.stackexchange.com/users/8013/adamo?tab=profile) on [proportional hazards](https://stats.stackexchange.com/search?q=user%3A8013+proportional+hazard*). You get a sort of time-averaged coefficient estimate, with perhaps some loss of power. The Schoenfeld residual plot shows directly how the estimate changes over time. Show that plot and use a `cluster` term in the model to get robust standard errors that allow for valid inference if PH is violated.


Linear Algebra solving for x,y,z in a system

Question: Question 3: (6 pts) A company makes 3 kinds of snacks, using almonds and raisins. The Fruity snack
contains 100g of almonds and 300g of raisins. The Nutty snack contains 300g of almonds and 100g of
raisins. The Variety snack contains 200g of almonds and 200g of raisins. There are currently 900g of
almonds and 700g of raisins available, and we want to determine how many of each kind of snacks can be
made so that all the ingredients are completely used.
a) Define variables and set up a linear system in order to solve the problem.
b) Find all the realistic solutions to the problem.
I answered A)
<code>100x + 300y + 200z = 900

300x + 100y + 200z = 700
</code>
How do I do B)?
Comment: Worded a different way, you have the following matrix equation:  $\begin{bmatrix} 100&300&200\\300&100&200\end{bmatrix}\begin{bmatrix} x\\y\\z\end{bmatrix} = \begin{bmatrix}900\\700\end{bmatrix}$  It is asking you to solve the matrix equation, which should be a known process to you in a linear algebra course (keeping in mind that it doesn't make sense to sell a negative amount of a specific type of snack).
Comment: Regarding b)  you have 3 variables and 2 unknowns.  If you were to solve this over a solution set defined over the real numbers, there would be a line of potential solutions.  However, "realistic solutions" will restrict the solutions to the natural numbers.
Answer: To simplify, divide both equations by $100$, solve the first for $x$ to get $$x = 9 - 3y - 2z$$ and plug it into the second one to eliminate $x$, and solve the second for $y$ in terms of $z$.
Then, find a range for $z$ which results in realistic values for all 3 components.
Comment: The answer is (1,2,1) and (0,1,3). how do they get two results?
Comment: @RajaSharma You know that $x, y, z \geq 0$, and therefore $x < 9$ by the equation in the answer. Therefore, plug in from $x=0$ to $x=8$ into the two equations and solve for $x$ and $y$. The solutions from $x=2$ to $x=8$ are probably excluded because they make $y$ and $z$ negative or non-integers.