Proving functions are injective or surjective

Question: determine with proof whether the functions are injective or surjective:
1) $ g: \mathbb{R} \rightarrow \mathbb{R}$ $ g(x) = 3x^3 - 2x $
2)$ g: \mathbb{Z} \rightarrow \mathbb{Z}$ $ g(x) = 3x^3 - 2x $
for 1) using the definition set $ f(x_1) = f(x_2) $ and we get $3x_1^3 - 2x_1 = 3x_2^3 - 2x_2 $ and we can this does not imply x_1 is equal to x_2 as we take values e.g. x_1 = 0 and x_2 = rt2/3 and get $f(x_1) = f(x_2) = 0 $ but x_1 is not x_2
for surjectivity I'm kind of stuck
we have to show $ \forall y \in \mathbb{R} \exists x \in \mathbb{R} $ s.t. $ f(x) = y$ but I don't know where to start
for the second one:
I done the same approach as the first but I'm not sure whether or not it's injective as I'm dealing with the integers
Comment: For surjectivity on the first one, as you say, you need to find an $x$ for any given $y$ such that $f(x)=y$. So set:

$$y=3x^2-2x$$

If for any $y$ you can find an $x$ that makes that equation true, then the function is surjective. Can you do that? You may be able to use this to prove surjectivity in question (2). For injectivity in question (2) I'm not sure, have you tried just looking for counterexamples?
Comment: Note: the graph of the first is a **parabola**, which will have a *maximum (or minimum)* value. So...
Comment: @JackM to show injective, we show F(x)=F(x')=> x=x'. Then can we also use this method- F(x) not equal to F(x') => x not equal to x'.
Answer:
$g(x)=3x^3−2x$ in $\mathbb R$ is continuous function. If it is injective, it must monotonous. But its derivative $9x^2-2$ is clearly not always positive (negative between $\pm\frac{\sqrt{2}}{3}$), so $g$ can't be injective.
It's surjective because it's continuous and $\lim_{x\rightarrow-\infty}g(x)=-\infty$ and $\lim_{x\rightarrow\infty}g(x)=\infty$ (So by continuity, it takes all values between those limits).

$g(x)=3x^3−2x$ in $\mathbb Z$ : $g(n+1)-g(n)= 9n(n+1)+1>0$ for all integers $n$. So $g$ is increasing and injective.
But $g(1)=1$ and $g(2)=20$, so there is no integer such that $g(n)=7$ for example, because $g$ is increasing. So $g$ is not surjective.


Mover várias mensagens para uma pasta utilizando o JavaMail

Question: Estou querendo refatorar um código de manipulação de e-mail, sei que dá para remover várias mensagens em uma operação só, mas e para mover várias mensagens para determinada pasta, tem como?
Utilizo o protocolo IMAP.
Answer: Tem sim. Implementei uma função para isso, é bem fácil!
<code>public void saveMessages(Message[] mArray, String folderName) throws Exception{
      //Primeiro copiamos...
      Folder f = findFolder(folderName);
      currentFolder.copyMessages(mArray, f);

      // Depois removemos do diretório antigo!
      for ( int i = 0; i < mArray.length; i++){
          mArray[i].setFlag(Flags.Flag.DELETED, true);
      }
      currentFolder.expunge();
   }
</code>
Comment: Pô cara, legal, eu não sabia que dava para passar para um folder de uma só vez várias mensagens, para apagar sim. Obrigado
Comment: poderia por favor postar o código do `findFolder`.
Comment: Olha cara, eu vim do C++ e não sei muito de Java não... Dá uma procurada aí e vê se tem um jeito de achar pastas e depois eu edito a pergunta! `:)`


VNC server failure after booting - Failed to get connection to session

Question: I'm having this error from the log file of a Tiger VNC server (version tigervnc-server-1.1.0-5.el6_4.1.x86_64):
Failed to contact configuration server; some possible causes are that you need to enable TCP/IP networking for ORBit, or you have stale NFS locks due to a system crash. See http://projects.gnome.org/gconf/ for information. (Details -  1: Failed to get connection to session: Failed to connect to socket /tmp/dbus-Auq6xEVNZb: Connection refused)

(Details -  1: Failed to get connection to session: Failed to connect to socket /tmp/dbus-Auq6xEVNZb: Connection refused)GConf warning: failure listing pairs in `/apps/nautilus/desktop-metadata': Failed to contact configuration server; some possible causes are that you need to enable TCP/IP networking for ORBit, or you have stale NFS locks due to a system crash. See http://projects.gnome.org/gconf/ for information. (Details -  1: Failed to get connection to session: Failed to connect to socket /tmp/dbus-Auq6xEVNZb: Connection refused)

When I reboot the server, it works nice, but after a while it start failing and when I connect there's no desktop and there's a pop-up windows appearing and disappearing.
I've recently have deleted by mistake /tmp directory, could that be the source of the problem?  How could this be solved?
This problem is also causing problems with disk usage because this log file is always growing, which seems to be related with a persistent error state.
Thanks!
Comment: When writing questions, use "" to distinguish things like error text. Indentation and the ` charcter are used to designate code.

Its also not clear which VNC server you are talking about. Perhaps type out the full name or provide a link to the software you are using.

Lastly, avoid content that is not relevent. For example, in this case, the fact that the log file is getting too large sounds like an effect of the problem, but not really related to its cause. What is your reason for its inclusion here?
Answer: This was solved by creating a directory /tmp/dbus-Auq6xEVNZb (it varies on each server, you need to check the error and see the path VNC server is trying to access). The command for that is:
mkdir -p /tmp/dbus-Auq6xEVNZb

It seems that another solution could be to modify ~/.dbus directory ownership (https://bugs.launchpad.net/ubuntu/+source/gconf/+bug/367169).
EDIT: After rebooting, this solution NO LONGER WORKS. I also tried to delete the content of /tmp/ (NOT THE DIRECTORY ITSELF) and change ownership to dbus user, but it doesn't work neither.
EDIT 2: Reinstalling dbus has worked. I'm no longer having those errors.
Comment: try reinstalling dbus. so that during uninstall / reinstall it cycles through permissions without you manually having to guess them.
Comment: @Fred Concklin Yes! Reinstalling dbus seems to work fine!


How to go about detecting data usage in the Android environment

Question: I would like to be able to detect all forms of data usage using the Android environment. Is it possible to keep tabs on which applications call on say RTP vs WAP, etc. such that I can know at all times when data is being used by a native program or third-party app?
Answer: If you are talking about an Android API to monitor network statistics by application then such an API seems to have been added in Android 2.2 (Froyo).
The main class you'll need is TrafficStats.
You can use getUid{Rx|Tx}Bytes(int uid) for the given process user ID (which you can get from ActivityManager.getRunningAppProcesses()).
The API is very simple and simply gives you the total bytes received/sent, so you'll have to do some more work to keep track of hourly, daily, and monthly stats. Well, that all depends on your needs.
I haven't tried using it myself, so I cannot give you any more detail, nor do I know the supported devices (not all devices will support this as the API points out).
Comment: hmm that does give me some direction. I appreciate it. But you said I can't use this for earlier versions? and there is no way to addrss this for earlier versions? just curious?
Comment: can I get the RX/TX stats from ADB? or is the only way to access them is through an app. I would like to know if I could do something like ADB Shell cat proc/int_UID/net/dev > C:\netstats.txt ... but actually get the rx/tx stats from individual applications
Comment: Not working on device below JELLY_BEAN_MR2.
http://developer.android.com/reference/android/net/TrafficStats.html#getUidRxBytes(int)


Theming of a webform node

Question: i would to theme a specific webform page and i achieve this with devel themer help but i find it not logical.
Usually i use ID to specify a template for a page, node or other element.
Then in my case i use the node-419.tpl for my node 419.normal
For my page it's a bit more complicated because this the hierarchical applied template :
page-infos-profil-élève.tpl.php < page-webform.tpl.php < page-node-419.tpl.php < page-node.tpl.php < page.tpl.php

so why a template called page-webform-419.tpl.php doesn't work instead of page-infos-profil-élève.tpl.php ?
Could i do this with php in my template.php file ? if yes how ?
thanks
Answer: This depends on your template suggestions.
Open template.php in your theme folder, and look for a function named YOURTHEME_preprocess_page, if it does not exist, create it like:
function YOURTHEMENAME_preprocess_page(&$vars)
{
    debug($vars['theme_hook_suggestions']);
}

And see what suggestions (and in what order) you have.
EDIT: this is a preprocess function I used in a theme of mine, in theme's template.php:
/**
 * Implementation of hook_preprocess_page()
 * @param $vars
 */
function THEMENAME_preprocess_page(&$vars){
    // I like to store templates in different folders inside the theme dir
    foreach($vars['theme_hook_suggestions'] AS $i => $ths){
        $vars['theme_hook_suggestions'][$i] = 'pages/' . $ths;
    }
}
/**/

In your case, simply do debug($vars, 'preprocess page vars!'); to see what variables you have a dispostion (please note: flush the cache after editing/creating this kind of function, and the output of debug($vars) can be very big!) and then add your template suggestion.
Maybe this can help: theming d7 webforms
Comment: My suggestions are provided by devel themer module..do your function give me more infos ?
Comment: Ah ok, devel module is probably more accurate.. have you tryed to clear (flush) the cache?

A lot of problems like this one can be solved just clearing the cache.
Comment: yes i clear cache all the time i modify a tpl or css...but if devel doesn't suggest page-webform-419.tpl.php i think it's an issue in my template.php, because i have a code to get template suggestion like page-[content-type] into...?
Comment: Wait, devel *does* or *does not* suggest `page-webform-419.tpl.php` ?
If not, follow my advice; In the preprocess page you can *add* suggestions, just identify when is the page that you need and then add the suggestion ;)
Comment: exact, but i get an error with : `function Cyrano_PF_preprocess(&$vars, $hook)
{
  switch($hook)
  {
      case 'page' :
      if (arg(0) == 'node')
      {
        $vars['template_files'][]  = 'page-' . $vars['node']->type;
      }
      break;

  }
    debug($vars['theme_hook_suggestions']);
}`
Comment: What error do you get?
However remove uppercase from function name..
Comment: Take a look here: https://api.drupal.org/api/drupal/includes!theme.inc/function/template_preprocess_page/7
Comment: i get error 500 but i figure it out for now with `function Cyrano_PF_preprocess(&$vars, $hook)
{

  switch($hook)
  {
      case 'page' :
      if (arg(0) == 'node')
      {
        $vars['template_files'][]  = 'page-' . $vars['node']->type;
      }
      break;
debug($vars['theme_hook_suggestions']);
  }

}` but nothing is displayed on screen , is it normal ?
Comment: Let me update my answer with few details..
Comment: ok i saw your edit but nothing is display with : `function cyrano_pf_preprocess(&$vars, $hook)
{
   switch($hook)
  {
      case 'page' :
      if (arg(0) == 'node')
      {
        $vars['template_files'][]  = 'page-' . $vars['node']->type;

      }
      break;
debug($vars, 'preprocess page vars!');
  }

}` if i put your code into the case, i get an 500 error.But why this code would provide suggestions that devel don't ?
Comment: That code (hook_prepocess_page function) is used to **add or remove** suggestions; Devel module only **show** the suggestions for a element..
Comment: remove your switch, and in the function just put `debug($hook, 'HOOK'); debug($vars, 'VARS');` and see the output. If you get the 500 error in this way, is probably becose $vars is too big to be debugged, try then `debug(array_keys($vars), 'Vars keys');` and then again debug just the keys you need.
Comment: 500 error in both cases..empty cache or run cron do no change. :(  `function cyrano_pf_preprocess(&$vars, $hook)
{
     debug(array_keys($vars), 'Vars keys');
//   debug($hook, 'HOOK'); debug($vars, 'VARS');

}`
Comment: Well, check the error log of your server (apache i guess, should be in /var/log/apache2/ named error.log or yourdomain.error.log, depends on your apache configuration) to see what is the problem
Comment: `[Thu Sep 26 14:11:13 2013] [error] [client 192.168.100.23] PHP Fatal error:  Call to undefined function debug() in /var/www/drupal6/sites/all/themes/Cyrano_PF/template.php on line 16, r$
[Thu Sep 26 14:12:21 2013] [error] [client 192.168.100.23] PHP Fatal error:  Call to undefined function debug() in /var/www/drupal6/sites/all/themes/Cyrano_PF/template.php on line 5, re$
`
Answer: yes i figure it out like this:
function cyrano_pf_preprocess(&$vars, $hook)
{
    switch($hook)
  {
      case 'page' :
      if (arg(0) == 'node')
      {
        $vars['template_files'][]  = 'page-' . $vars['node']->type;
        $vars['template_files'][] = "page-" . $vars['node']->type . "-" . $vars['node']->nid;

      }
      break;

  }

}

with the help of https://stackoverflow.com/questions/8956045/how-can-i-customize-a-specific-node-in-drupal-6-when-a-custom-template-has-alrea , then i get this choice for now (from devel) :
Candidate template files:
page-pentreprise.tpl.php < page-webform-420.tpl.php < page-webform.tpl.php < page-node-420.tpl.php < page-node.tpl.php < page.tpl.php

now, i can use a tpl file like page-webform-999.tpl to theme a specific webform page..

Theming of a webform node


Modificar atributo href via jQuery

Question: Eu preciso saber como eu faço para alterar os links e imagens de uma página via jQuery.
Eu tenho que fazer atualições dinâmicas em uma determinanda página e preciso criar um script para isso, que altere imagens e links.
Exemplo:

Tipo, nesse exemplo eu sei que o href contém link1, link2 e que a tag img contém imagem1, imagem2
Eu preciso saber se consigo criar um script que captura a informação que o usuário digitar e faça um rastreio das tags e converta automaticamente.
Imagine que o usuário coloque um link http://wikipedia.org.link1, nesse caso ele iria alterar o href link1, o mesmo seria para as imagens.
Comment: Modifica sempre para o que está a seguir ao ultimo `.` ? Ou qual é a regra exatamente ?
Comment: A regra seria a seguinte: eu iria criar um campo (caixa de texto) e jogar o caminho das imagens e links que eu gostaria de alterar e esses mesmos dados iriam alterar alterar os dados do index.html.

Tipo, o script iria considerar a informação digitada no campo e fazer uma comparação (tipo um contains no link e imagens), mais ou menos assim.

HTML

Campo Texto
Nesse caso, com o script, o usuário iria atualizar o conteudo com um novo link e imagem, mas que contenha as informações nas tags href e img
Answer: Para evitar erros de digitação é bom usar uma outra forma de escolher qual opção alterar. Poderia usar um select, por exemplo.
Usando um select você pode fazer isso com

A função val para saber

qual o valor existente num input onde o usuário digitou. Ex: var novovalor = $("input").val()
qual o opção escolhida pelo usuário (link1, link2 ...). Ex: $("select").val()

A função attrpara modificar o valor de uma propriedade de um elemento. Por exemplo: $("a:first").attr("href", novovalor)
Comment: Muito Obrigado, já me ajudou muito :)
Comment: De nada. Se você considerar que a minha resposta solucionou sua dúvida, por favor, escolhe como solução (clica na seta que está embaixo do número de votos). Se ainda tiver alguma dúvida, pergunta aqui.
Answer: Você pode alterar com a função attr() do jquery:
$('#elemento').attr('href', 'link que será passado')
$('#elemento').attr('src', 'source da imagem')

Espero ter ajudado.

Modificar atributo href via jQuery


postfix evaluator not working

Question: For some reason, when I execute this program with the following expression 12 12 * 66 + it returns an invalid and negative answer -46. I'm curious as is to what is going wrong, and would like to fix it asap.
#include <stdio.h>
#include <stdlib.h>
#include "usefunc.h"
#define OFFSET '0'

/*
* I only use one constant.....I really don't need another. and in fact took more
* memory to use the constant than without. several bytes!!
*/

/*

* for this program, I found a library that contained C implementations
* of a stack. I thought I'd use it, since I understand everything it
* does fully. you can quiz me on the stuff I did not write, if you want.

*/

//setting up the stack
typedef char stackElementT;

//it's a struct, so it can contain several elements
//like maxSize, top, and of course the contents
//let's call it stackT
typedef struct {
  stackElementT *contents;
  int maxSize;
  int top;
  int min2;
} stackT;

//allocates the memory for the size passed to the function
//then checks if there's enough memory
//then sets the size to maxSize, `top` to -1 (empty), and contents to newContents
void StackInit(stackT *stackP, int maxSize) {
    stackElementT *newContents;
    newContents = (stackElementT *)malloc(sizeof(stackElementT)*maxSize);
    if (newContents == NULL) {
        fprintf(stderr, "Not enough memory.\n");
        exit(1);
    }

    stackP->contents = newContents;
    stackP->maxSize = maxSize;
    stackP->top = -1; //empty...
}

//frees the allocated memory
//sets it all to NULL
//sets the size to 0, all that good stuff
void StackDestroy(stackT *stackP) {
    free(stackP->contents);
    stackP->contents = NULL;
    stackP->maxSize = 0;
    stackP->top = -1; //empty
}

//just referencing top
int StackIsEmpty(stackT *stackP) {
    return stackP->top < 0;
}

//and top again
int StackIsFull(stackT *stackP) {
    return stackP->top >= stackP->maxSize-1;
}

//and top once more
//adds one to the top of the stack by first incrementing the top, and then adding the element in at the top
//unless of course it's full
void StackPush(stackT *stackP, stackElementT element) {
    if(StackIsFull(stackP)) {
        fprintf(stderr, "Can't push element: stack is full.\n");
        exit(1);
    }
    stackP->contents[++stackP->top] = element;
}
//pops it, and then subsequently updates `top`
//unless of course it's empty
stackElementT StackPop(stackT *stackP) {
    if(StackIsEmpty(stackP)) {
        fprintf(stderr, "Can't pop element: stack is empty.\n");
        exit(1);
    }
    return stackP->contents[stackP->top--];
}

/*

* my work starts here:

*/

double eval(double x, double y, char operand) {
    switch(operand) {
        case '+': return x+y;
        case '-': return x-y;
        case '/': return x/y;
        case '*': return x*y;
        case '^': return pow(x, y);
    }
}

int is_operand(char x) {
    switch(x) {
        case '+':
        case '-':
        case '/':
        case '*':
        case '^': return 1;
        default: return 0;
    }
}

double postfix(char* expr, int length) {
    //counter, and two temporary variables
    int i;
    double temp = 0, temp2;
    //and of course the stack
    stackT stack;
    //lotta frames...
    StackInit(&stack, 1000);
    //loops through string input. as of now, it only works with one digit numbers :(
    for (i = 0; i < length; i++) {
        //printf("%d : %c\n", expr[i], expr[i]);
        //is it a number? yes? push the decimal version of it to the stack
        if ((expr[i] >= '0') && (expr[i] <= '9')) {
            //printf("temp=%f\n", temp);
            temp *= 10;
            temp += expr[i]-OFFSET;
            //printf("temp=%f\n", temp);
        }
        else if (expr[i] == ' ') {
            StackPush(&stack, temp);
            temp = 0;
        }

        //no?
        else {
            //switch-case statement, easy peasy
            switch (expr[i]) {
                //operations checking
                case '+': {
                    temp = StackPop(&stack);
                    temp2 = StackPop(&stack);
                    //printf("%f+%f\n", temp2, temp);
                    StackPush(&stack, temp2+temp);
                    temp = temp2+temp;
                }
                    break;
                case '-': {
                    temp = StackPop(&stack);
                    temp2 = StackPop(&stack);
                    //printf("%f-%f\n", temp2, temp);
                    StackPush(&stack, temp2-temp);
                    temp = temp2-temp;
                }
                    break;
                case '/': {
                    temp = StackPop(&stack);
                    temp2 = StackPop(&stack);
                    //printf("%f/%f\n", temp2, temp);
                    StackPush(&stack, temp2/temp);
                    temp = temp2/temp;
                }
                    break;
                case '*': {
                    temp = StackPop(&stack);
                    temp2 = StackPop(&stack);
                    //printf("%f*%f\n", temp2, temp);
                    StackPush(&stack, temp2*temp);
                    temp = temp2*temp;
                }
                    break;
                //POWERS?!?! whoa. this wasn't required.
                case '^': {
                    temp = StackPop(&stack);
                    temp2 = StackPop(&stack);
                    //printf("%f^%f\n", temp2, temp);
                    StackPush(&stack, pow(temp2, temp));
                    temp = pow(temp2, temp);
                }
                default:
                    break;
            }
        }
    }
    //just giving the number it pushed
    return StackPop(&stack);
}

int main() {
    //so many counters...!
    //almost a shell
    while (1) {
        //prompt
        printf("postfix expression:\t");
        //getLine
        char *expr = GetLine();
        //aaaaaaaaaand evaluate it
        printf("%.0f\n\n", postfix(expr, strlen(expr)));
    }
}

Comment: This isn't a duplicate; he's asking a new question about a newly discovered problem with the same code.
Comment: We get a fair number of cases where people ask the same question repeatedly, often accompanied by blocks of substantially similar code. If you are going to post a closely related question it is a good idea to (1) Say it is a related question and link to the earlier instance (2) explain that you've moved beyond the original problem and are stuck *again* and (3) be explicit about how the new question differs. It's all part of the art of asking *good* questions.
Comment: Thank you very much! Why don't people see this?
Comment: Though it doesn't matter except for the rep loss... I fixed it several minutes ago.
Answer: The problem is that your stack elements are characters which appear to be signed on your platform, and you are wrapping around SCHAR_MAX.
(12*12)+66 = 210. 210 in hex, for clarity, is 0xd2. However, interpreting 0xd2 as a twos-complement signed character value gives us -46.

postfix evaluator not working


json: how to get the json-string into a javascript object

Question: i am converting my ajax code from xml to json, but i am missing something basic here:
when i receive the json-string on the client-side, what is the recommended way to convert it into a javascript object.
for example i get this string:
{"connectionid":12345}

and i would like to do something like this:
alert(xmlhttp.responseText.connectionid);

thanks!
Comment: you could use the evil eval :)
Answer: Use JSON.parse(), or eval(), if you like to live dangerously (or fully trust where your JSON comes from).
If you happen to be using jQuery, you get $.parseJSON().
Answer: Most browsers (the recent ones at least.. not IE7) have a native JSON object that you can use to parse and stringify JSON.
alert(JSON.parse(xmlhttp.responseText).connectionid);

In browsers that don't support the JSON object, you can either use a JSON parser from JSON.org or use eval(), however eval() is quite dangerous and i definitly don't advise you to use it.
Answer: Call eval on the response text.
var response = eval(xmlHttp.responseText);
alert(response.connectionId);

Comment: I think it's a bit rough to mark it down. Unless you are going to rely on a third party library, which was not specified in the original question, then eval is an acceptable solution, if you are in control of the source, which I am assuming you are for XmlHttpRequests.
Answer: you could use eval
check this out : http://www.json.org/js.html
edit - oops, others typed faster :(


Hosts in Nagios are disappearing

Question: This may belong in ServerFault, but I wanted to approach this community first. If this is not correct, please move this thread or close and I will open on the correct thread.
PROBLEM:
Hosts, along with their associated services, disappear and reappear upon refresh (F5 / Ctrl+F5 / etc).
STEPS TO REPRODUCE:
1. Log into Nagios
2. Click Service Detail
3. See a breakdown of services but you don't see the last one you added.
4. Refresh screen by using F5 / Ctrl+F5 / etc and it doesn't show up still
5. Refresh screen by using F5 / Ctrl+F5 / etc and it doesn't show up still
6. Refresh screen and it will show up.
(!) - Steps 4-6 vary
WHAT I'VE TRIED:

Restarting Nagios service (service Nagios restart)
Restarting HTTPD service (service httpd restart)
Restarting VPS
Refresh browser including "Clear Cache and Hard Reload"
Tried different browsers
Tried different computers
Tried different networks

SCREENSHOTS:
GOOD

https://i.stack.imgur.com/brtY4.png
BAD

https://i.stack.imgur.com/PjWCi.png
POSSIBLE CAUSE:
The reason we're in this situation now is because we had an intern add this latest host and its associated service. He added it correctly, and I even checked his work. He did the normal preflight but instead of issuing the reset command via SSH he issued the command on the Web interface itself by accessing "Process Info > Restart the Nagios process". Seems like it would work OK, but we've never restarted like this and is the only reason I suspect it's the culprit of the issue we are seeing. Is there something different that this restart does over the normal SSH restart?
EDIT: To add to all of this, we have updated a different file today, unrelated to this host or it's services and Nagios is not updating.
Thanks for helping!
Rich
EXTRA:
Here is a screenshot of the config file:

https://i.stack.imgur.com/ladvp.png
Answer: This can happen if you have multiple Nagios services running, There could be a secondary instance of the service running which hasn't been updated with the new configuration files as it technically hasn't been restarted. I've had this happen once or twice.
First, shut down Nagios
service nagios stop

Next, kill all remaining instances.
killall -9 nagios

Finally, start Nagios back up
service nagios start

That should fix your problem.
Comment: This was the issue and also the resolution. Figured it out a day after I posted (forgot to come back and mark as so). Not sure how we have two instances installed...but that's a topic for another day. Thank you!

Hosts in Nagios are disappearing


how to move one component to another component on button click in react?

Question: could you please tell me how to move one component to another component on button click in react ?
I get the react-router.js from cdn .I don't know how to use this js ..I want to show second component on button click offirst component` here is my code
http://codepen.io/anon/pen/jVoZjW?editors=1010
class Abc extends React.Component {
  handle(){
    alert('move to second component')
  }
   render (){
     return (

second
<button onClick={this.handle}>move to second page</button>
);

   }
}
class Pqr extends React.Component {
   render (){
     return (

second
<button>click</button>
)

   }
}
class Sqr extends React.Component {
   render (){
     return
third

   }
}
ReactDOM.render(<Abc/>,document.getElementById('root'));

Comment: When you say "move" do you mean "show"?
Comment: yes to to show second component using router js
Comment: Not sure you're understanding the use-case of React-Router. React-Router is meant for when you change the url, to show a different hierarchy of components. If you're not changing the route (url), then you shouldn't be using React-Router.
Answer: There is many ways this can be accomplished, all of which have there place. This is but one of many methods:
I left an alternitive to this answer aswell this answer on the codepen:
http://codepen.io/dirtyredz/pen/gLJeWY
class Abc extends React.Component {
  constructor(){
    super();
    this.state={first: true};
  }
  handle(){
    alert('move to second component')
    this.setState({first: false})
  }
  render (){
    return (

        <button onClick={this.handle.bind(this)}>move to second page</button>
        {this.state.first == true && <Pqr/>}
        {this.state.first == false && <Sqr/>}

    );
  }
}

class Pqr extends React.Component {
  render (){
    return (

First

)
  }
}
class Sqr extends React.Component {
  render (){
    return
Second

  }
}
ReactDOM.render(<Abc/>,document.getElementById('root'));

This is a quick example, like i said earlier others may be better but this works as expected.
Comment: i want to do using RouteHandler


Find all real functions $f$ such that $f(xf(y))=(1-y)f(xy)+x^2y^2f(y)$

Question:
Find all functions $f:\mathbb{R}\rightarrow \mathbb{R}$ such that for all real numbers $x,y$ we have:
  $f(xf(y))=(1-y)f(xy)+x^2y^2f(y)$

I have solved this problem but the solution is "bruteforce", so I wanted to ask if there is a more elegant way of approaching this.
Comment: you have found ***all*** solutions by bruteforce?
Answer: I claim that the only possible solutions to the functional equation
$$f\big(xf(y)\big)=(1-y)f(xy)+x^2y^2f(y)\tag0\label0$$
are $f(x)=0$ and $f(x)=x-x^2$.
To show that, first let $y=1$ in \eqref{0} and you'll get $f\big(xf(1)\big)=x^2f(1)$. Now assuming $f(1)\neq0$ we'll have $f(x)=\frac{x^2}{f(1)}$ for every real number $x$, whcih leads to a contradiction using \eqref{0}. So we have:
$$f(1)=0\tag1\label1$$
Next, let $x=1$ in \eqref{0} and you'll get:
$$f\big(f(y)\big)=\big(1-y+y^2\big)f(y)\tag2\label2$$
Now, substituting $f(y)$ for $y$ in \eqref{0} and using \eqref{2} we get:
$$f\Big(xf\big(f(y)\big)\Big)=\big(1-f(y)\big)f\big(xf(y)\big)+x^2f(y)^2f\big(f(y)\big)\\
\therefore f\Big(x\big(1-y+y^2\big)f(y)\Big)=\big(1-f(y)\big)f\big(xf(y)\big)+x^2f(y)^3\big(1-y+y^2\big)$$
So, if $f(y)\neq0$, letting $x=\frac1{f(y)}$ in the last equation and using \eqref{1}, we get:
$$f\big(1-y+y^2\big)=\big(1-y+y^2\big)f(y)\ne0$$
Thus by \eqref{2}, $f\big(f(y)\big)=f\big(1-y+y^2\big)\ne0$ and so $f\Big(f\big(f(y)\big)\Big)=f\Big(f\big(1-y+y^2\big)\Big)$. Hence by \eqref{2}:
$$\big(1-f(y)+f(y)^2\big)f\big(f(y)\big)=\Big(1-\big(1-y+y^2\big)+\big(1-y+y^2\big)^2\Big)f\big(1-y+y^2\big)\\
\therefore1-f(y)+f(y)^2=1-\big(1-y+y^2\big)+\big(1-y+y^2\big)^2\\
\therefore\Big(f(y)-\big(1-y+y^2\big)\Big)\Big(f(y)+\big(1-y+y^2\big)-1\Big)=0$$
$$\therefore f(y)=1-y+y^2\quad or\quad f(y)=y-y^2\tag3\label3$$
Now, if $f(y)=1-y+y^2$ then $f\big(1-y+y^2\big)=\big(1-y+y^2\big)^2$, but because $1-y+y^2\neq0$ we must have $f\big(1-y+y^2\big)=1-\big(1-y+y^2\big)+\big(1-y+y^2\big)^2$ or $f\big(1-y+y^2\big)=\big(1-y+y^2\big)-\big(1-y+y^2\big)^2$ by \eqref{3}. It's easy to check that the latter case leads to a contradiction and the former case leads to $y=0$ or $y=1$. But letting $x=y=0$ in \eqref{0} we have $f(0)=0$, and by \eqref{1} we have $f(1)=0$. So this case leads to a contradiction, too, since we assumed $f(y)\neq0$. So $f(y)$ cannot be equal to $1-y+y^2$ and hence by \eqref{3}, $f(y)=y-y^2$.
Finally, if there is a real number $y$ such that $y\neq0$, $y\neq1$ and $f(y)=0$, then by \eqref{0} we get $f(0)=(1-y)f(xy)+0$ for every real number $x$, which means that $f$ is the constant zero function. This yields our first claim. It's easy to check that indeed the two mentioned functions satisfy \eqref{0}.
Comment: I came to the same solution... ;) even thogh I used some different steps ;)
Comment: @Börge Post your answer. It may be useful.
Comment: If I may suggest a little simplification: from $(3)$ it easily follows that $f(x) = f(y) \implies$ $y = x$ or $y = 1-x$. Thus, when you get $f(f(y)) = f(1-y+y^2)$, you automatically get $f(y) = 1 - y+y^2$ or $f(y) = 1-(1- y +y^2)$, and can easily dismiss the first case because $1-y+y^2$ has no real roots, while $f$ does.
Comment: @Ennar I think that there's a problem with your argument. I think in that step, there's still possible that we have $f(y)=1-y+y^2$ for some $y$ and $f(y)=y-y^2$ for some other $y$. It may also be useful to note that, this part of the proof is about the real numbers for which we have $f(y)\neq0$ and so having roots is irrelevant.
Comment: Oh, ok, I was too hasty.


How do I know what setSetting is suppose to be?

Question: I am creating a custom content entity and in the BaseFieldDefinitions, I am trying to create a field for assigning a user as the designated assigner and will follow up with a assignee. So far, the code has been pretty easy to follow and makes sense, except for setSetting.
Basically the field below works, but its copy and pasted from drupal console as boiler plate code. What I don't understand is the setSetting part. If I comment out ->setSetting('target_type', 'user'), the field displays but no longer works.
So my question is, how am I suppose to know, or figure out, that I should be typing in 'target_type' and value 'user'? I went through the API but haven't managed to find any references to this. And I don't understand the setSetting below it either, 'handler' = 'default. I can comment that out and it works fine. So what gives?
How am I suppose to know what to set in the setSettings part? As I also noticed, not every field definition even has this.
$fields['assigner'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Assigner'))
  ->setDescription('The person who will issue this Task.')
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'user')
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
      'label' => 'hidden',
      'type' => 'author',
      'weight' => 0,
  ])
  ->setDisplayOptions('form', [
      'type' => 'entity_reference_autocomplete',
      'weight' => 5,
      'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
      ],
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Comment: `target_type` is the name of the database column which stores that data for an entity reference field. You find it by looking at the class which defines the field type, something, to be honest, you just need to know to do. In my experience unless you stumble across these concepts by chance in tutorials or generally reading through the core code, you're not going to know them. Trying to document something like this is difficult, as it's extremely flexible, and involves a lot of moving parts
Comment: You can also try the options available when configuring the field type in UI and check the exported yaml files.
Answer: You can look at the source code of the corresponding field type class to get an idea of the available settings.
target_type is something specific for an ER field
Base classes for field types provided in Drupal core
Almost all field types are derived from one of the above base classes, e.g. there are several number field types deriving from NumericItemBase
Custom field types are usually located in module_name/src/Plugin/Field/FieldType


Views Exposed Filter Form Submit handler

Question: I have a Views with an exposed filter block and put the block on the front page.
I use the following code to add a custom submit handler.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'views_exposed_form' )
  {
    array_unshift($form['#submit'], 'manage_custom_filters');
  }
}

function manage_custom_filters($form, &$form_state) {
 dpm($form['#id']);  // output views name
}

Here is the question, whenever i load the front page, the manage_custom_filters get called, i suppose it will be called only when i submit the exposed filter form?
I did the same thing for node form submit, it does not behave like the views exposed filter form. manage_custom_filters only get called when i submit the form.
Is this the correct behavior of views exposed filter form?
How do i differentiate the manage_custom_filters is get called by 'on load' or submit action?
Answer: The views exposed form will be submitted every time you view it. If you check the render_exposed_form() you can see they are setting the $form_state['always_process'] => TRUE, this means that the form will be submitted always while processing it. And this is understanable because submitting the exposed form and passing the argument in $GET are the same in view.
Answer: As stated above, the form is submitted as soon as you load a page. You have a couple of workarounds here:

If you are using Ajax, you could add a custom JavaScript function only fired on submit (so when you load the page it won't occur). Something like this:
Drupal.behaviors.mymoduleAjaxView = {
  attach: function(context, settings) {
    this.form.submit = customFunction();
    function customFunction() {
        alert('Fired when form is submitted');
    }
}};

If you don't wish / have to use JavaScript, you could check for a field in your form that, on page load has no value (is empty) but when submitted by a human has a value. E.g.
function manage_custom_filters($form, &$form_state) {
    if(!empty($form_state['values']['field_name_here']) {
      // Form was human submitted.
    }
}

Compare $form_state when the page loads and when you submit the form, to spot this. I know that probably this is not the ideal way, but it has worked for me.


can logstash send data simultaneusly to mulpile location along with elastic search

Question: Normally, in ELK logstash parsed data and send to elastics search.
I want to know is it possible that logstash send same data to different location at real time.
If it is possible, please let me know how to do it.
Comment: What did you found so far?
Comment: logstash can take input from 48 diffrent way and can send output to different location as well..but my concerned can it send simultaneusly to different location.
Comment: Simply use several outputs, and Logstash will send your data to each listed output
Answer: Create several output files that match type and send to different hosts.
<code>output {
  if [type] == "syslog" {
    elasticsearch {
          hosts => ["127.0.0.1:9200"]
          index => "logstash-%{+YYYY.MM.dd}"
          codec => "plain"
          workers => 1
          manage_template => true
          template_name => "logstash"
          template_overwrite => false
          flush_size => 100
          idle_flush_time => 1
    }
  }
}
</code>


How to display a block for pages that don't show nodes?

Question: My Drupal 7 module creates a block, and then in admin I can make it available for the Article content type only. I would also like it to be available to the result page for a Product Search. This page is not of a normal content type and comes to life in hook_menu().
The path for the results will be avantlink-search-results/search term and I would like it to show the block with the search form again. I would rather not use the PHP code option in the block visibility options so as to keep it simple for users of the module.
The code is viewable on AvantLinker.
Answer: I think you may want to take a look at the context module. That allows you to define multiple conditions for displaying blocks.
However, you should also consider making your module only return content on pages that it makes sense to appear on. So the user doesn't have to worry about complex configuration.
Comment: The context module is only beta for D7 and with a lot bugs getting light attention. That would be too much for people new to Drupal like the potential users of my module.
Answer: You could use the Rules block visibility module for this. ... which doesn't require the PHP filter to be enabled. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
Need to show a block only for users registered more than a month ago?
Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
What about displaying or hiding a block based on current weather conditions?
All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is only shown on your "result page for a Product Search", as in your question).
For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):
{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "avantlink-search-results/",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

If needed, further adapt the value of avantlink-search-results/ to fit your needs. And/or replace the Rules condition in it with something using an appropriate regular expression.
Answer: If you only want the block to show up on certain pages, the block admin settings page is already fit to do that. If you are using URL aliases (say the URL alias for the article content type is example.com/article/....) and not using the PHP filter, you  could try:

Unless I missed something in the question, this should work in a basic setup.


How to create a field in a document while creating another document?

Question: I have a model user that has list of badges
badges: [{type:mongoose.Schema.Types.ObjectId, ref: 'badge'}]

And while creating a new badge I want to add this badge to a specific user's list of badges
User.findById(id, function(err,user){
      user.badges.push(???)  ///// How to push the badge I'm creating
      user.save(..)
})

How can this be done ?
Answer: You must save badge before pushing into user.badges. Mongodb auto set badge._id property.
var badge = new Badge(...);
badge.save().then(badge=>{
    user.badges.push(badge._id);
    user.save;
});


Chord Progression ear training

Question: Got this ear training app. And I was wondering what to listen to when hearing chord progressions? How the app work is simple, it first play I-V-I progression in random keys, then proceeds to play a random chord between I-VII which I have to guess.
The problem is I can't distinguish if it's playing a IIm, IIIm or VIm. Other chords are fine, but these 3 minors are hard. Am I suppose to listen for the chord function?
I see some people talk about the root. That dosent work here, since the chords jumps randomly up and down the entire register. Also not to mention inversions and rootless chords
Comment: Is there no way to adjust the level or difficulty of the app? It's a big jump from I-V-I to rootless chords and inversions in different ranges. Also as Tim mentioned, knowing what the app is might help in getting a more detailed answer.
Comment: Complete ear trainer. And yes I can adjust difficulty to turn off inversions and rootless.                                                                                I was just wondering how I were meant to recognise the different degrees. I think many just use the root and sorta interval the root? But does that work with rootless inverted? So I can just train myself to listen for the function of the degree?
Comment: Having and using an ear training app is all very well. What instrument you play will have a bearing on your ear training though.
Answer: Without knowing exactly what level you have achieved in ear training and based on your comment I have a few recommendations.
To me a very important key to developing ear training is to learn to hear and recognize intervals really well. That includes intervals of notes played one after the other and also intervals of notes played simultaneously.
This will lead to being able to recognize the qualities of triads in root position. Learn the difference between major, minor, diminished and augmented triads. Also learn to identify what the lowest note is.
Use your interval knowledge to try and identify the intervals of the bass movement from one triad to another. To me the easiest way to identify chord progressions is to hear the interval of the root movement then the qualities of the chords above them.
Gradually expand to hearing and recognizing seventh chords and inversions at your own pace, but do each one individually.
Finally and most importantly, play a chording instrument and actually practice playing, listening closely to and learning the sounds of the various intervals, chords and chord progressions. You will be surprised at your ability to recognize sounds when you have already played some of them yourself. Good luck!
Answer: Seems like that app is not  a good fit yet. Find one which simply uses root position chords, until you get used to the sound. Then progress to a slightly more advanced one.
It may help to share exactly which app it is, so we can check it out as suitable or not for your stage. There are several similar questions here about chord recognition, which may also be of help.
Answer: I'm going to second the recommendation to find a simpler ear training app. Recognizing chords regardless of inversion and in random order is fairly advanced. Regardless...
Ear training took a while for me to get the hang of.
What my Aural Skills professor taught me was a simple way to train for chord identification, though keep in mind, just like any skill it takes regular practice.
First, begin with tonicization if possible within the app you use.
I highly recommend learning solfege for this. If you don't already know solfege or can't dictate melodies, work on that first. Chords are far more advanced.
At the beginning of a piece I want to notate chords for, I use the pattern
Do-Mi-Sol-La-Sol-Fa-Re-Ti-Do
for major keys.
When a chord is being played, try to match (singing or playing) the solfege pattern of chords to whatever chord is being played. The tonic, for example, is Do-Mi-Sol.
Memorizing the solfege for each chord is incredibly beneficial.
It is also imprtant to note that for Ear Training, most chords are played in inversions that lend to being played simply on a keyboard.
Here's a "chart" to help.
I: Do-Mi-Sol
ii: Re-Fa-La
iii: Mi-Sol-Ti
IV: Fa-La-Do
V: Sol-Ti-Re
vi: La-Do-Mi
vii°: Ti-Re-Fa
And that will bring us back to
Do-Mi-Sol ;)
While certainly more complex than simply learning to recognize chords on their own, this method is far more comprehensive and prevents hiccups such as not being able to differentiate minor chords.
I hope this can be of use for somebody!
Comment: Yes, it's incredibly helpful to be able to identify by ear the component notes present. If you hear "ti" (I hear "7" personally) you can immediately rule out ii or vi if you're sure you hear a simple triad.

Chord Progression ear training


a = b = c coding standards

Question: I'm in charge of creating  coding standards and doing code reviews within my organization.
I came cross something within our source code like this:
object.Property = myVar1 = myVar2;

I don't personally do this because I find it confusing.  I see this and I want to read it like this:
object.Property = myVar1 == myVar2;

Now I know what it's doing:  It assigns myVar to myVar2 and then object.Property to myVar2.  The coding standards document doesn't explicitly state whether or not you can do this.  It does state however to not assign variables within an if statement.
I guess my question is, is it bad enough style to draw out as a coding practice to not do it?  I don't like making code standard policies "just because I said so"
Edited to better explain my understanding
Comment: Obligatory Lippert blog item: http://blogs.msdn.com/b/ericlippert/archive/2010/02/11/chaining-simple-assignments-is-not-so-simple.aspx
Comment: Code is meant for humans to read and rarely for computers to execute. If there's ambiguity fix it :)
Comment: As you have already said, its confusing... That's a good reason for me to put it as a thing to avoid
Comment: @Mehrdad can't remember the citation now :P
Comment: @Jesus: It's from SICP. :P Might be worth mentioning that. :)
Comment: @Mehrdad yeah I had forgotten the source thanks
Answer: I always wrap equality expressions in parentheses:
object.Property = (myVar1 == myVar2);

This draws attention to the fact that it's not an assignment.
Answer: This so-called "chained assignment" is indeed controversial and there are quite a few questions on SO that address it.
It is a byproduct of assignment being an expression and not a statement, as you know, and to many people it can be confusing.
It many languages it is somewhat dangerous to novices.  In languages where [] is a constructor for empty array objects, writing
a = b = []

makes a and b reference the same object.  Novices tend to think it makes two separate empty arrays which can be filled independently.  Not so!  The C# equivalent,
a = b = new SomethingOrOther();

is arguably far less likely to occur, since a and b would be more likely to be initialized at the point of declaration, and such double assignments would be rarer, and furthermore C# programmers are more likely to see the obvious sharing in this case.
A good rationale for instituting a prohibition against this is three-fold:

It is completely unnecessary.
It is error-prone (as in the array example above).

When you encounter error-prone constructs, you should avoid them because in avoiding them, you will never make that particular error.  Granted, in C#, it may be far less error prone than in other languages.
Comment: The fact that people make the array mistake is completely irrelevant to C# though...
Answer: That's (usually) nothing to worry about, in C#.
Unless your variable is bool (in which case you should separate it into two statements either way), that isn't error-prone -- only one of the two will ever work correctly, so there's no danger of "accidentally" omitting or typing an extra =.
Conclusion: Don't worry about non-boolean cases.
Answer: First of all, kudos to you for not assuming "my way is the right way".  This kind of question is very subjective and devs will have different (and usually strong) opinions.
I will say that I try to avoid confusing code, but statements like this can (in some scenarios) make the code more readable by collapsing a large number of statements into fewer statements.  Not always true, but I think it is sometimes.
My opinion is not to exclude this kind of statement in your coding standard, and try to be as inclusive of different coding styles as you can be (except for blatantly unreadable or confusing code).
I have been involved in a lot more "coding standards" discussions than I would like, and I find that they tend to cause a lot more friction than the problems they are aiming to solve.
Comment: Thanks, I try my to keep in mind that the "coding standards" are really there to give our projects a certain consistency that we can expect as developers, and I don't want to have pedantic conversations around "my opinion vs. your opinion"
Comment: Yes, it's good to see people thinking through this type of thing!
Answer: Since I run across times when I would want a = b = c very rarely I just write it as two separate statements. (This is often times just as well for me because I like to not re-assign variables when possible, making the assignment only in the declaration, and I only declare one variable per variable declaration.)
Then, if I do come across a = b == c I just take that as being "assign the result of the equality to a" and don't even think twice about it (as my coding style doesn't include a = b = c).
However, this error is minimized in C# because, except when dealing with boolean types (for a, b, and c), the compiler will complain because the types will be amiss.
Happy coding.
Answer:
Now I know what it's doing: It assigns myVar to myVar2 and then object.Property to myVar1

Your understand is incorrect, the compiler don't do that.
Because assignment expressions return a value, therefore, in your example, object.Property is assigned with the return value of assignment expression myVar1 = myVar2. NOT assign myVar2 to myVar1 and thenn myVar1 to object.Property
So that, there's no confusion between 2 statement that you have given. But, if your variables do not have the same type, you should use parentheses to make your code readable.
object.Property = myVar1 == myVar2;

Answer: As this is about coding style this is very much IMHO
Almost any language feature can be seen as confusing or wonderful depending on the dev. Some people thinks that operator overloading (or generics, closures, higher-order functions and so on) is the road to hell, other sees it as a good tool to create succint and readable code.
If this is a common pattern in your code base chances are your devs are comfortable with the semantics of this pattern. In this case I would think a recommendation against it might be seen as counter-productive.
If it is an uncommon pattern in your code base this might be a confusing pattern and therefore it can be good to recommend against and search for the places where this pattern is used and consider refactoring.
Comment: Yeah, that's kind of where I am right now... it's the first time I've seen it and couldn't think of a good reason why to not accept it as a viable solution.  Ultimately, I'm going to say nothing about as it's just not that common and I'd rather my devs to follow the bigger style standards and not get hung up on this kind of stuff.

a = b = c coding standards


Is there a way to get a verbatim string out of an ElementTree element?

Question: I am trying to check the MD5 hash of the text information in an XML element including all its children. This is required to interact with hipay services.
def CheckMD5(tree):
    m = hashlib.md5()
    body = tree.find('result')
    m.update(ET.tostring(ET.ElementTree(body).getroot(), method="html"))

    return tree.find('md5content').text == m.hexdigest()

Full code:
https://github.com/fabiosantoscode/python-hipay/blob/master/hipay.py#L566
My problem is that calling ElementTree.tostring with method="xml" makes ElementTree collapse closing tags of empty elements, but using method="html" I lose capitalization. Example:
>>> ET.tostring(ET.fromstring('<rt><CapName>asd</CapName></rt>'), method='xml')
'<rt><CapName>asd</CapName></rt>'
>>> ET.tostring(ET.fromstring('<rt><CapName>asd</CapName></rt>'), method='html')
'<rt><CapName>asd</capname></rt>'
>>>

Note:
I don't need to modify this XML document at all, I just need to extract the string data of the <result> element. If there are other libraries which allow me to do this, please indicate.
Answer: LH.tostring does not collapse closing tags:
In [34]: import lxml.etree as ET

In [35]: import lxml.html as LH

In [36]: LH.tostring(ET.fromstring('<rt><CapName>asd</CapName></rt>'))
Out[36]: '<rt><CapName>asd</CapName></rt>'


How do I append a view to the node body in custom module?

Question: In Drupal 7, we could do the following within a hook_node_view:
$node->content['nodehierarchy_children'] = array(
  '#theme' => 'nodehierarchy_children_embed',
  '#nodehierarchy_view' => $node->nh_children_view,
  '#nodehierarchy_view_display' => @$node->nh_children_view_display,
  '#nodehierarchy_view_args' => $arguments,
);

Then in the hook_theme:
function nodehierarchy_views_theme() {
  return array(
    'nodehierarchy_children_embed' => array(
      'render element' => 'element',
    ),
  );
}

Finally we have the theme function:
function theme_nodehierarchy_children_embed($variables) {
  $element = $variables['element'];
  $display = $element['#nodehierarchy_view_display'];
  $arguments = $element['#nodehierarchy_view_args'];
  return $view->execute_display($display, $arguments);
}

How do I accomplish the above in Drupal 8? I'd like the implementation to be Drupal 9 compatible, so ideally I don't want to use depreciated functions etc.
I mean should I attempt to somehow override node.html.twig and provide it with a render array using something similar to:
$view = views::getView($node->nh_children_view)
$build['nodehierarchy_children_embed'] = $view->buildRenderable($display,$arguments);

I think if someone could provide the functions and general methodology, I could fill in the coding portion.
Answer: So it turns out that the hook_node_view was all that was needed, but I don't know why it didn't work the first time:
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function mymodule_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode){
  // Get the arguments to send to the view.
  $arguments = ...;
  if ($view = Views::getView('my_view')) {
    $display = ...
    $build['some_name'] = $view->buildRenderable($display,$arguments);
    $body = $node->get('body')->value;
    $node->set('body')->value = $body.render($build['some_name']);
  }
}

Answer: For later versions of Drupal 8, the above no longer worked, so I had to change it to the following:
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function mymodule_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode){
  // Get the arguments to send to the view.
  $arguments = ...;
  if ($view = Views::getView('my_view')) {
    $view->setDisplay($display);
    $view->setArguments($arguments);
    $build['some_random_name'] = $view->render();
    // Set the weight high to append the view to the end of the body or omit it otherwise.
    $build['some_random_name']['#weight'] = 1001;
  }
}

Comment: I gives this error `Warning: Illegal string offset '#weight'`


Maximum of *Absolute Value* of a Random Walk

Question: Suppose that $S_{n}$ is a simple random walk started from $S_{0}=0$.
Denote $M_{n}^{*}$ to be the maximum absolute value of the
walk in the first $n$ steps, i.e., $M_{n}^{*}=\max_{k\leq n}\left|S_{k}\right|$.
What is the expected value of $M_{n}^{*}$? Or perhaps a bit easier,
asymptotically, what is $\lim_{n\to\infty}M_{n}^{*}/\sqrt{n}$?
This question relates to https://mathoverflow.net/questions/150740/expected-maximum-distance-of-a-random-walk, but I need to obtain the value of the multiplicative constant. Thanks!
Answer: For a Brownian motion $(S_t)_{t\ge 0}$, the corresponding process $(M^*_t)_{t\ge 0}$ and $y>0$,
$$\mathbb{P}[M_t^* > y] = \frac{4}{\pi}\sum_{m=0}^\infty\frac{(-1)^m}{2m+1}\left[1 - e^{-(2m+1)^2t\pi^2 / (8y^2)}\right]$$
and
$$\mathbb{E}[M_t^*]=\sqrt{\frac{t\pi}{2}}.$$
Thanks to Sangchul Lee for computing the integral. This may be proved by considering the martingale $(\mathbb{P}[M_t^* > y | \mathcal{F}_r])_{r<t}$ and relating it to a solution of the heat equation with Dirichlet boundary conditions [see, for example, equation 25 of these notes]. I'd be happy to write this up if anyone's interested. I don't know whether a similar method works for the discrete-time random walk.
Answer: Partial answer to the first question: Using the reflection principle, I obtained
$$ \Bbb{P}(M_n^* \geq k) = \sum_{m=0}^{\infty} (-1)^m \left\{ \Bbb{P}((2m+1)k \leq |S_n|) + \Bbb{P}((2m+1)k < |S_n|) \right\}. $$
(Since $|S_n| \leq n$, this is in fact a finite sum for $k \geq 1$ and there is no convergence issue.) Now summing both sides for $k = 1, 2, \cdots$, this gives
$$ \Bbb{E}[M_n^{*}] = \sum_{m=0}^{\infty} (-1)^m \Bbb{E} \bigg[ \left\lfloor \frac{|S_n|}{2m+1} \right\rfloor + \left\lceil \frac{|S_n|}{2m+1} \right\rceil - \mathbf{1}_{\{S_n \neq 0 \}} \bigg]. $$
For me, this seems to suggest that we might be able to get
$$ \frac{\Bbb{E}[M_n^*]}{\sqrt{n}} \to \sum_{m=0}^{\infty} \frac{(-1)^m}{2m+1} \cdot 2\Bbb{E}[\mathcal{N}(0,1)] = \sqrt{\frac{\pi}{2}}, $$
which matches the analogous result for the Wiener process proved by @Ben Derrett.
(As an alternative idea, we may possibly utilize Skorokhod embedding to realize the SRW using the Wiener process evaluated at certain stopping times $\tau_n$ and then control the deviation between $\tau_n$'s to carry over Ben Derrett's result to the SRW case. Note that similar idea is used to prove the law of iterated logarithms for normalized ranodm walks. But I haven't pursued this direction further.)

Answer to the second question: For the pointwise estimate, we can rely on the law of iterated logarithm (LIL). Indeed, let
$$M_n^{+} = \max\{S_0, \cdots, S_n\}, \qquad M_n^{-} = \max\{-S_0, \cdots, -S_n\}. $$
Then we have
$$ \limsup_{n\to\infty} \frac{M^{\pm}_n}{\sqrt{2n\log\log n}} = 1 \qquad \Bbb{P}\text{-a.s.} $$
Indeed, this follows from both LIL and the following lemma:

Lemma. Suppose that $(a_n)$ and $(b_n)$ are sequences of real numbers such that $b_n > 0$ and $b_n \uparrow \infty$. Then the following identity holds:
$$ \limsup_{n\to\infty} \frac{\max_{1\leq k \leq n} a_k}{b_n} = 0 \vee \limsup_{n\to\infty} \frac{a_n}{b_n}. $$

Since $M_n^* = \max\{M_n^+, M_n^-\}$, the same bound is true for $M_n^*$:
$$ \limsup_{n\to\infty} \frac{M^{*}_n}{\sqrt{2n\log\log n}} = 1 \qquad \Bbb{P}\text{-a.s.} $$
Comment: An interesting question is whether  it is also true that for the symmetric random walk in the dimensions 2 and 3 the maximum expected  distance the drunkard is away from its starting point during the first $n$ steps  is the same as the expected distance  the drunkard is away from its starting point  after $n$ steps.   If I am correct, the famous MIT probabilist G.C. Rota once addressed the question in an unpublished(?) manuscript


What is a pfxblob

Question: I asked this question the other day.
Part of the solution required a base64binary of the pfxblob to put into the Azure Template, to pass to Azure via Powershell.
I ultimately found I could get a pfxblob by running a different Azure command, the source of which contained a chunk of c# that did what I needed it to.
Namely -
Convert.ToBase64String(cert.Export(X509ContentType.Pfx, Password));)

I'm mostly able to pick that apart and vaguely get what it is doing, at least enough to fix my immediate problem at the time. But I never did work out what a pfxblob actually is. And on the run up finding that solution, I couldn't find anything that described what it was.
So I thought one of you lot must...
Comment: Check this blog post [here](http://paulstovell.com/blog/x509certificate2) explaining what a pfx file is. With that in mind , a pfxblob is a binary file which contains the public and private stuff of the certificate.
Answer: PFX files contain encrypted private keys, certificates, and potentially other secret information.
Generally, a PFX BLOB is a binary representation of a PFX store. More precisely, a PFX BLOB is a CRYPT_DATA_BLOB structure. The CRYPT_DATA_BLOB is specified in the typedef of _CRYPTOAPI_BLOB.
The _CRYPTOAPI_BLOB contains an arbitrary array of bytes. Its struct consists of DWORD cbData, which is A DWORD variable that contains the count, in bytes, of data; and `BYTE  *pbData', which contains A pointer to the data buffer.
Therefore, a PFX BLOB contains the binary content of a PFX store, plus the length of the store.
It is worth reading this page for further information: PKCS #12 File Types: Portable Protected Keys in .NET
Major APIs that use the PFX BLOB are these:

PFXIsPFXBlob
PFXImportCertStore
Comment: Is a pfxblob a purely MS concept? does it have an equivalent in other environments?
Comment: @MichaelB PFX is a Microsoft-invented technology. https://cryptome.org/jya/pg-get-MSkey.htm , but other platforms use the PFX BLOB. For instance, see this Java documentation: http://lxr.mozilla.org/security/source/security/jss/org/mozilla/jss/pkcs12/PFX.java

What is a pfxblob


Animating a QVBoxLayout when using stretch factors/when the final size is unknown

Question: This post is closely related to this question about animating a QVBoxLayout, which got me half-way back when I found it.
I have a QVBoxLayout containing a few widgets. The last of them is only visible in certain situations, so I want to animate it when it appears and disappears.
I'm currently using QPropertyAnimation to animate the maximumHeight property of the widget I want to show and hide. However, the issue here is that I don't know what size the widget should be: the QVBoxLayout decides that, based on the parent window size and stretch factors.
Therefore, I don't know what values I should give to QPropertyAnimation::setStartValue and setEndValue, for the show animation (when hiding, it should work to simply use the current height).
It sort-of works to simply give a very excessive value (such as 2000 px, when you expect it to rarely be larger than 400), since we're animating the maximum height, but that has issues. Namely, the finished signal is emitted after the full animation duration, even if the animation stopped (visually) long ago, as the widget reached its allotted size.
When hiding, the issue is instead that the animation is delayed: from 2000 px to the current height(), nothing happens; after that, it collapses quickly.
I then considered animating the stretch factors instead, but couldn't find a way to, since they're not exposed as properties.
As a last resort, it might be possible to subclass the layout and create a property that adjusts the stretch factor of the last two items, but that feels like a huge hack in several ways.
How can I animate this in a nice way?
Just in case somebody's going to ask for a code example, I wrote a simple test application. If you weren't going to ask, you can probably skip looking through it.
#include <QApplication>
#include <QVBoxLayout>
#include <QPushButton>
#include <QTextEdit>
#include <QPropertyAnimation>

QTextEdit *topTextEdit = nullptr;
QTextEdit *bottomTextEdit = nullptr;

void toggleButtonClicked() {
    QPropertyAnimation *anim = new QPropertyAnimation(bottomTextEdit,
                                                      "maximumHeight");
    anim->setDuration(1200);

    if (bottomTextEdit->isVisible()) {
        anim->setStartValue(1000);
        anim->setEndValue(0);
        QObject::connect(anim, &QPropertyAnimation::finished, [] {
            bottomTextEdit->hide();
            topTextEdit->append("Animation finished");
        });
    }
    else {
        bottomTextEdit->show();
        anim->setStartValue(0);
        anim->setEndValue(1000);
        QObject::connect(anim, &QPropertyAnimation::finished, [] {
            topTextEdit->append("Animation finished");
        });
    }

    anim->start(QAbstractAnimation::DeleteWhenStopped);
    topTextEdit->append("Animation started");
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    topTextEdit = new QTextEdit;
    bottomTextEdit = new QTextEdit;

    QPushButton *toggleButton = new QPushButton("Toggle");
    QObject::connect(toggleButton, &QPushButton::released,
                     &toggleButtonClicked);

    QVBoxLayout *vbox = new QVBoxLayout;
    vbox->addWidget(toggleButton);
    vbox->addWidget(topTextEdit, 10);
    vbox->addWidget(bottomTextEdit, 6);

    QWidget *widget = new QWidget;
    widget->setLayout(vbox);

    bottomTextEdit->setMaximumHeight(0);
    bottomTextEdit->hide();
    widget->show();

    return a.exec();
}

Answer: I ended up going with the subclassing route, since I couldn't think of anything else, and this question didn't see a lot of activity.
The subclass (must be in a header file or you'll get undefined reference to vtable errors):
class EVBoxLayout : public QVBoxLayout {
    Q_OBJECT
    Q_PROPERTY(int lastStretch READ lastStretch WRITE setLastStretch)

public:
    EVBoxLayout() {}
    int lastStretch() const { return this->stretch(this->count() - 1); }
    void setLastStretch(int newStretch) {
        this->setStretch(this->count() - 1, newStretch);
    }
};

After implementing that, replace the QVBoxLayout with an EVBoxLayout, and create the animation using
QPropertyAnimation *anim = new QPropertyAnimation(vbox, "lastStretch");

There are several points to consider for this to work:

For the animation to be smooth, you should probably use very large stretch factors; since they are integers, an animation from e.g. 1 to 5 will be very choppy. I went with a 1000:600 ratio, so my animation is from 1 to 600 for the bottom widget, which I want to be the smaller one.
Make sure to set the minimum height of the widget to 1 (not 0!), or the animation may begin part-way.
Make sure to animate the stretch factor from 1, not from 0, or there will be a flicker when the animation begins.

The solution feels hacky, but it looks and works great in practice.
For completeness, here's the full test program, updated to use this fix:
main.h:
#ifndef MAIN_H
#define MAIN_H

#include <QVBoxLayout>

class EVBoxLayout : public QVBoxLayout {
    Q_OBJECT
    Q_PROPERTY(int lastStretch READ lastStretch WRITE setLastStretch)

public:
    int lastStretch() const { return this->stretch(this->count() - 1); }
    void setLastStretch(int newStretch) { this->setStretch(this->count() - 1, newStretch); }
};

#endif // MAIN_H

main.cpp:
#include "main.h"

#include <QApplication>
#include <QVBoxLayout>
#include <QPushButton>
#include <QTextEdit>
#include <QPropertyAnimation>

QTextEdit *topTextEdit = nullptr;
QTextEdit *bottomTextEdit = nullptr;
EVBoxLayout *vbox = nullptr;

void toggleButtonClicked() {
    QPropertyAnimation *anim = new QPropertyAnimation(vbox, "lastStretch");
    anim->setDuration(250);

    // Without this, the scrollbar may appear (and then disappear again)
    // during animation.
    bottomTextEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    if (bottomTextEdit->isVisible()) {
        anim->setStartValue(600);
        anim->setEndValue(1);
        QObject::connect(anim, &QPropertyAnimation::finished, [] {
            bottomTextEdit->hide();
            topTextEdit->append("Animation finished");
            bottomTextEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        });
    }
    else {
        bottomTextEdit->show();
        anim->setStartValue(1);
        anim->setEndValue(600);
        QObject::connect(anim, &QPropertyAnimation::finished, [] {
            topTextEdit->append("Animation finished");
            bottomTextEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        });
    }

    anim->start(QAbstractAnimation::DeleteWhenStopped);
    topTextEdit->append("Animation started");
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    topTextEdit = new QTextEdit;
    bottomTextEdit = new QTextEdit;
    bottomTextEdit->setMinimumHeight(1);

    QPushButton *toggleButton = new QPushButton("Toggle");
    QObject::connect(toggleButton, &QPushButton::released,
                     &toggleButtonClicked);

    vbox = new EVBoxLayout;
    vbox->addWidget(toggleButton);
    vbox->addWidget(topTextEdit, 1000);
    vbox->addWidget(bottomTextEdit, 1);

    QWidget *widget = new QWidget;
    widget->setLayout(vbox);

    bottomTextEdit->hide();
    widget->show();

    return a.exec();
}

I'll wait another day or so to accept this as an answer, in case someone comes along with something less hacky (such as a way to calculate the exact final size from the stretch factors).


Network Administration and Auditing Tools

Question: We're a small company (~50) who outsource the bulk of our IT to an... average quality provider.  I am taking on the role of day-to-day IT (think of things that can be fixed in 15 mins or less only).  I'm looking for some tools that can make my life easier.  Most of our computers are on the LAN, though we do have a couple of remote employees and people do travel quite frequently.
I would like reco's on tools that can help me figure out which PC's are running what versions of Windows (mostly Vista, 7), up-to-date on patches etc., possibly tie into a virus-scanner for a high-level overview of how many threats have been detected, cleaned etc., and then possibly to simplify remote access (RDC is fine when the computer is local, but sometimes is a pain for people outside the office).
Not sure if such a thing exists, but thought this would be the place to ask.
For those who are going to say "Get better IT", "Don't try to do it yourself" etc., I DO have an IT background, but have not made it my focus.  My primary reason for taking this task on and looking to audit this stuff is to build a business case about what we do well / don't do well, so that I can justify an increase level of spending and awareness of the importance of a well designed IT infrastructure.
Answer: This is a hard question to answer because of all of the unknowns about your environment (including why your IT vendor is failing).  You may have a difficult to manage environment, and\or unreasonable expectations of your IT department for dollars spent.
In your question, you ask for very 'point of problem' tools, while also asking for management tools.  These are really different area, and you need to understand the differences.  Are you going to be the helpdesk guy?  or the IT manager?
I suggest you may want to buy the time of a consultant experienced with information systems design (as opposed to providing tech support) to look over your IT, and get advice on how to proceed with all of your goals.
Generally:

You'll need an up to date inventory of computers.  I've used Open Audit for this purpose on larger networks than yours with regular (daily, weekly, on logon, etc your choice) updates.  Simple to set up, simple to use. Rich detail.  There are lots of other choices including Spiceworks. YMMV.  To underline, manual inventories dont work.
Microsoft Group policies. Many problems are caused by users with too many rights on their computers.  In particular is the ability to adjust Internet Explorer security settings to the point that anything can gain a foothold on a computer.  But the advantages of GPO's dont end here (software updates, who can install software, etc), and you should research this on your own.
Command line.  You need to become facile at the command line with native microsoft tools, like - ping.exe, route.exe, ipconfig.exe, tasklist.exe, netstat.exe and others.  You may want to install tools from  Sysinternals like psinfo.exe.
Laptops. Do your laptop users have unreasonable business needs for uptime?  if so, you may want to just punt these users to a third party.
Remote Access.  This should be pretty straight forward.  If your current vendor cannot create a secure solution, you should be able to find someone who can.  Lots of low cost VPN solutions.  You want to do this before your users start implementing their own solutions....
Comment: Thanks for the thorough answer.  Our vendor is failing partly due to their work ethic, and partly due to years of unspecified expectations on our end.

We can't lock down computers (just not how we operate - I know, I know) - I agree it may be worthwhile to bring in a consultant for suggestion.  Again, thanks for the tips.  I'd upvote you if I could.
Comment: @McB If you don't have specifications for the vendor ow do you expect to be successful at detemining wether or not you could do  better job at it or not?
Answer: To answer the part about finding out what your environment consists of you could try out Spiceworks. It's a network crawler that will go out and scan the PCs on the LAN and report back OS versions, software versions along with other things. One thing i will note is that it does require the windows firewall to be disabled so it can scan the PC on your network.
Here is a Link to Spiceworks
Comment: Looks very interesting, will give it a shot. Thanks
Comment: I had tried Spiceworks a long time ago.  They left a disfavorable impression, but I don't renember exactly why; it was either upsell attempts or spam...
Answer: Microsofts online systemcenter https://www.systemcenteradvisor.com/  is quite good for this along with microsofts intune product.
Comment: This doesn't help his situation with monitoring and reporting on desktops.
Comment: thats what intune is for correct.
Answer: Your question is mixing services (remote access) with management (how do I tell what versions of windows I have).  These are 2 completely seperate entities (and remote desktop solutions will require some level of management)
What you should bring in is an operations consultant or at the very least take a look at ITIL, MOF or COBIT.  Each one of these is a framework in order to manage IT.  There is no good answer to what tools you need until you can define what it is exactly you need to manage and these framewrorks help define that.  As an example you need (as mentioned by someone else) an inventory - unless you have leased machines that get refreshed every so often - then the inventory of hardware is only based on expiration date and location (which an automated tool isn't going to help you with).  Once you have decent processes you can then decide on what tools will meet the specific needs.
Answer: To find out which machines are up-to-date on patches, use secunia.com's excellent product. I am not related to them, just a satisfied user.
Answer: My favorite toolset is VBScript / Powershell, and using them to leverage WMI.  (Scriptomatic2 is my preferred means of discovering what's available.)
Microsoft has a great section of tutorials called the Script Center.  There's also tons of code (submitting by the MS Scripting Guys and Community submissions) in the Script Center Repository.


web deploy parameterization in website project

Question: I have tried web deploy parameterization using web application project(.NET 4.5.1) and it was successful. I have followed the steps mentioned in
http://msdn.microsoft.com/en-us/library/ff398068.aspx
But this method is not working for website project.!!!
Is this method is not applicable for website project?
Comment: I didn't know that web deploy even _worked_ for web site "projects". Can you deploy your project when you don't use parameters?
Comment: Project can be deployed successfully. But when tried to deploy the website project, the wizard is not prompting for the parameter configured in "parameters.xml". I tried the same in web application project, there it's prompting for the parameters..!!! Tried same method to deploy both packages, opened IIS, right click on the website>Deploy>Import Application. Please let me know if have done anything wrong...! @john Thanks for the comment...!
Comment: Good luck. You may be able to just compare the details of the two packages to get an idea of what the difference really is. But the ultimate solution is to simply never use web site "projects". Pretend they are just a horrible mistake that Microsoft made - which happens to be the truth.
Comment: This is a very big project and it's had to convert to web application... :( I will compare the packages. Please update me, If you get any clue..!!! Thanks @JohnSaunders
Comment: Still I am not able to figure it out, please help me...!!!
Answer: "Web.config" parameterisation is not possible in "website project" type in Visual Studio. See the Thread I posted in asp.net forum and the answer.
http://forums.asp.net/t/1998657.aspx?Web+deploy+parameterization+in+website+project
Please vote for the suggestion http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/6210039-web-deploy-parameterization-in-website-project


Form object with @RequestPart parameter results in 404

Question: I am trying to create an URI where both a MultipartFile and a form object (bean) are required.
The method worked with the following code:
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void create(@RequestPart MultipartFile file,
                   @RequestPart String form) {
    // ...
}

And the following curl command:
curl -X POST http://localhost/files \
  -F file=@E:\path\to\file \
  -F form={"x":0,"y":0,"width":512,"height":512}

But as soon as I try to replace the string by a bean, I get a 404 response.
Modified code, not working, with a bean:
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void create(@RequestPart MultipartFile file,
                   @RequestPart ClipForm form) {
    // ...
}

Adding the Content-Type header for each part in curl does not seem to help:
curl -X POST http://localhost/files \
  -F file=@E:\path\to\file;type=multipart/form-data \
  -F form={"x":0,"y":0,"width":512,"height":512};type=application/json

I am probably missing something that makes Spring think the request is not mapped to this method, but so far I cannot get what.
Comment: Shouldn't `type` be `Content-Type` in your curl string?
Comment: No, `type` is used to specify the Content-Type of parts in case of mutipart request. See [cURL manpage](https://curl.haxx.se/docs/manpage.html#-F).
Comment: in your request mapping you do not specify '/files' part - how it's supposed to be mapped?
Comment: also use -vv to view the actual content-type of the whole message(not the boundaries)
Comment: @BorisTreukhov the "/files" mapping is done by the encapsulating `@RestController`. Using `curl -v`, I see that I correctly get a global Content-Type to `multipart/form-data` with a correct boundary.
Answer: For whatever reason, quoting everything in the curl command and using bash made this working.
curl -X 'POST' \
     -F 'file=@E:\path\to\file;type=multipart/form-data' \
     -F 'form={"x":0,"y":0,"width":512,"height":512};type=application/json' \
     'http://localhost/files'

I guess a character was misinterpreted by the Windows cmd.

EDIT
If you want it to get working in the Windows cmd, you will need to use double quotes and escaped double quotes. It will not use the single quote like bash.
curl -X "POST" ^
     -F "file=@E:\path\to\file;type=multipart/form-data" ^
     -F "form={\"x\":0,\"y\":0,\"width\":512,\"height\":512};type=application/json" ^
     "http://localhost/files"


Sending a file in e-mail message body using Views Send

Question: I have a drupal site that holds thousands of client details. What I want to do is to create an emailer to send out campaigns to the clients.
So far I have a view set up to filter clients by company and using Views Send I can send all selected an email.
What I would like to do is to send a file in the email. Either that or be able to paste the data from the file into the email. The file is stored in my drupal site within a content type.
Does anyone know how I would be able to do this? To be able to select from a list which file to send in the e-mail message body?
Answer: take a look at the Entity Email Module:

The Entity Email module lets users create their own email templates
which can be used to send emails. Emails sent can also be recorded in
the DB if needed. Emails can be sent programmatically or by the mean
of the Rules module.
Main features:
Built on top of the amazing entity API
Allow token substitution
Templates can also contain attachments (PDF, TXT...)
Rules module support, so email actions can be triggered by any Rules
Supports the MimeMail module for HTML emails.
Build with the fields API Emails sent> can be recorded in DB

I don't know that it will integrate with Views on it's own, but you may be able to manually make it work the way you want.