wait until something == something in javascript

Question: I am writing a script that presses a add to cart button then waits until the cart item count = the current item count
Right now I cant seem to get out of the if statement I added even after the if statement becomes false.
here is what I have attempted:
  $("#add-remove-buttons :input")[0].click();
  let cart_count = $("#items-count").text();
  if (cart_count !== `${request} items`){
    setInterval(function() {
      let cart_count = $("#items-count").text();
      console.log(cart_count, `${request} items`);
    }, 50);
  }
  if (cart_count == `${request} items`) {
    chrome.runtime.sendMessage({finished:"done_after1"});
  }

This was the result in the console:

as you can tell it console.logged the 1 items 2 items  then it went to 2 items 2 items  and that is when it is supposed to stop and send the message. But for some reason it kept on console logging
I also tried this code:
$("#add-remove-buttons :input")[0].click();
let cart_count = $("#items-count").text();
while (cart_count !== `${request} items`){
  let cart_count = $("#items-count").text();
  console.log(cart_count, `${request} items`);
}
chrome.runtime.sendMessage({finished:"done_after1"});

So it was supposed to exit the while loop after the while loop was no longer true. But for some reason when I tested this that page just froze and I couldn't even right click to inspect the console. For some reason the page always freezes when I try this while loop.
If anyone knows whats wrong here I would really appreciate if you could help me out by telling me the problem. Thank You! <3
Comment: `presses a add to cart button then waits until the cart item count = the current item count` - so it should keep pressing add to cart until the numbers match? seems like your code presses the button ONCE only - so if that press doesn't make them match, they never will
Answer: Just move the if into the setInterval - you basically have to execute the script after the change happens:
$("#add-remove-buttons :input")[0].click();
let cart_count = $("#items-count").text();
if (cart_count !== `${request} items`){
  setInterval(function() {
    let cart_count = $("#items-count").text();
    console.log(cart_count, `${request} items`);
  }, 50);
  if (cart_count == `${request} items`) {
    chrome.runtime.sendMessage({finished:"done_after1"});
  }
}

However then don't forget to also use stopInterval.
Also using a timer to wait for something is not ideal. It would be better to use an event that is triggered when something is changed.
Comment: `stopInterval()` doesn't stop a particular interval, it doesn't stop ANY interval - you need to save the intervalId ... e.g. `let intervalId = setInterval(.....` and then stop it using `stopInterval(intervalId)`
Comment: Also there is no `stopInterval`. It is **`clearInterval`**
Comment: I put   stopInterval() right above the chrome sendMessage inside the if statement and I still got the infinite loop, maybe it wont == because that car_count is  text and  the request items is a string?
Comment: I also tried   cart_count.toString() and it still wont work. It doesn't seem to even be going into the if statement, could you also edit your answer so I can see were to exactly put that and if it will work
Comment: can you clarify your question? If the above code does not work then you need to post more details about what you're doing
Comment: @charlietfl it doesn't matter If I can't even get it to go to the if statement
Answer: Since #items-count doesn't seem to be an INPUT/TEXTAREA etc (i.e. something you can use the change event with, then you can use MutationObserver as follows
Note: I'm assuming that
$("#add-remove-buttons :input")[0].click();

needs to be clicked until the values match - your original code seems to click it once and once only
I'm also using non-jquery for the handling of #items-count element - because it's simpler in my opinion
function handler(node) {
    let check = first => { // when triggered by mutation event, the argument "first" will be undefined
        let cart_count = node.textContent;
        if (cart_count === `${request} items`) {
            chrome.runtime.sendMessage({finished:"done_after1"});
            return true; // stop observing
        } else { // didn't match
            if (first) { // this is the first call - add a MutationObserver
                new MutationObserver((mutationList, observer) => {
                    if(check()) { // call with no argument, because MutationObserver is already set up
                        observer.disconnect(); // condition is met, so stop observing
                    }
                }).observe(node, {
                    childList:true
                });
            }
            // condition is not met, so click the add button
            $("#add-remove-buttons :input")[0].click();
        }
        return false; // keep observing
    };
    check(true);
}
handler(document.querySelector('#items-count'));

However, if #items-count is an element that emits change events - it's even simpler
function handler(arg) { // when triggered by change event, arg will be defined
    let cart_count = $("#items-count").text();
    if (cart_count === `${request} items`) {
        if (arg) { // trigger by change event
            $("#items-count").off('change', handler);
        }
        chrome.runtime.sendMessage({finished:"done_after1"});
    } else {
        if (!arg) { // first call
            $("#items-count").change(handler);
        }
        $("#add-remove-buttons :input")[0].click();
    }
}
handler();

Comment: Error in event handler for runtime.onMessage: ReferenceError: arg is not defined
Comment: Not part of code in question or answer. So not sure how it relates to anything
Comment: Could I email you my entire file? becuase this doesnt seem to be working my email is firstname.lastname@example.com
Comment: Did you just tweet me?
Comment: Error in event handler for runtime.onMessage: ReferenceError: handler is not defined//  and maybe ;)
Comment: again, nothing to do with the code in the question or answer
Answer: You are not re-checking the value within the interval, so the message only has one chance to be sent, which will happen sometime before the interval executes.
Maybe try something more like this...
$("#add-remove-buttons :input")[0].click ();
let cart_count = $("#items-count").text ();

if (cart_count === `${request} items`) {
    chrome.runtime.sendMessage ({ finished: "done_after1" });
} else {
    let interval = setInterval (function () {
        let cart_count = $("#items-count").text ();

        if (cart_count == `${request} items`) {
            chrome.runtime.sendMessage ({ finished: "done_after1" });
            clearInterval (interval);
        }

        console.log (cart_count, `${request} items`);
    }, 50);
}

Comment: hmm it works but there is just one error for some reason after it gets the url, the cart_count is supposed to update with each url, but for some reason request stays to 2 and when it goes to the 3rd url it is supossed to update to 3 but it just stays at 2 not giving allowing it to do the setInterval
Comment: Your code examples and original post makes no mention of changing URLs, so I'm not sure what you mean.
Comment: may I send you my two files via email? my email is firstname.lastname@example.com
Comment: I don't know about that. I think PasteBin or JSFiddle would be better and fairer to the other people helping on this issue.
Comment: Well I have some private code, that I worked really long on and I don't really want to show it all
Comment: How would I do   if  > or == to becuase  >== doesnt work and neiter does >== or >=
Comment: Assuming `cart_count` is a string like "1 items", use `parseInt` to convert it to an actual integer, then compare to `request` using >=, like `if (parseInt (cart_count) >= request) { ... }`. Assuming `request` is also an integer of course, otherwise, you will have to parse it as an integer as well.


Difference between screen and window property?

Question: In my Web application , am in need to use the browser window's Height & Width. So I used Screen.Width , Screen.Height properties in JavaScript to get the Width & Height. While am surfing I got another property as Window.Width , Window.Height. Can anyone tell me , which property gives me the Size of Browser window.....Screen (or) Window ?
Comment: Check this link http://stackoverflow.com/questions/9895202/what-is-the-difference-between-window-screen-and-document-in-javascript?rq=1
Comment: Issa Qandil- Thank's for the Link. But my question is What does WINDOW  refers to ? What does Screen refers to ? either my Monitor size (or) Browser window size ?
Answer: screen is actually window.screen since window is the context for globals.
A window object (obtained through document.defaultView) returns information about both the window and the viewport. To get the application window size use window.outerHeight, to get viewport size use window.innerHeight.
The screen object refers to the actual monitor window or desktop size. Note that if you have a multi-mon setup then you will have multiple screen objects. A window object belongs to a single screen, though not very window belongs to the same screen. I do not know what happens when a browser window spans multiple screens.
From all this, you can determine that if you are running a full-screen browser then window.outerHeight == window.innerHeight == screen.height.
Source: https://developer.mozilla.org/en-US/docs/DOM/window.screen and https://developer.mozilla.org/en-US/docs/DOM/window
Comment: When a browser window spans multiple screens the window.screen object depends on where the most of is placed. For example if you have more than half of your browser on Monitor A and the rest on Monitor B then window.screen will be of Monitor A.
Answer:
window.screen.height
window.screen.width
height/width of the screen or monitor in pixels
window.screen.availHeight
window.screen.availWidth
height/width of the screen or monitor, in pixels, minus permanent or semi-permanent user interface features displayed by the operating system, such as the Taskbar on Windows or device status bar on smart phones
window.innerHeight
window.innerWidth
height/width of the content area of the browser window including, if rendered, the horizontal/vertical scrollbar
window.outerHeight
window.outerWidth
height/width of the outside of the browser window
Answer: What is the difference between window, screen, and document in Javascript? is pretty much this same question. To paraphrase the accepted answer and add some info that I feel it could use:
window in the root object. Any variables or functions you define are in some way children of the window object. So if you do var something="blah" in a script tag, you can later access that variable in 3 ways - something, window.something or window["something"].
screen is one of the children of window that is created by the browser. however, for the same reason that you can access window.something as something, you can access it either as window.screen or screen. This contains the properties of the actual screen, and it is where I would go to get the details you want (unless you have access to a framework like jQuery or Prototype, in which case they can probably give you this information without worries about browser compatibility).


Por que "a < 0 || b < 0" não dá o mesmo resultado que "a || b < 0"?

Question: Estava fazendo um teste e vi que esses dois códigos não davam o mesmo resultado. Por quê?

function tudoPositivo(num1, num2, num3) {
  // Escreva aqui seu código
  if (num1 < 0 || num2 < 0 || num3 < 0) {
      return 'Tem negativo!'
  } else {
      return 'Tudo positivo!'
  }
}

function tudoPositivo(num1, num2, num3) {
  // Escreva aqui seu código
  if (num1 || num2 || num3 < 0){
    return "Tem negativo!"
  } else {
    return "Tudo positivo!"
  }
}
Comment: isso depende dos valores que está passando para as funçoes. No segundo exemplo, é uma expressão onde, tecnicamete, "num1" deveria ser um boolean (true/false), mas se passar um número, vai entender zero como false e qualquer outro número como true
Comment: Olá João. É simplesmente confusão, o que leva a erro de uso, o que está entre os operadores || não são diretamente entendido pelos próximos, ou seja, funciona como `if ( ||  || ) {}`, em resumo, o operador de comparação `<` esta dentro da "terceira" condição.
Comment: Recomendo começar pelo básico do JavaScript aprendendo com o site mdn: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics e indo diretamente ao ponto dos operadores https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators
Answer: Em ambos os casos você está usando o operador || com três operandos. Se algum desses operandos for avaliado como "verdadeiro", a expressão como um todo também o será*, e o código entrará no if.
Mas os códigos não são equivalentes porque os operandos não são os mesmos.

No primeiro código os operandos são:

num1 < 0
num2 < 0
num3 < 0

Ou seja, para entrar no if, basta que algum dos valores seja um número negativo.
Já no segundo código, os operandos são:

num1
num2
num3 < 0

Repare que agora não estamos mais vendo se num1 ou num2 são menores que zero. O que está sendo avaliado é o próprio valor dessas variáveis.
E aí caímos nas regras de truthy e falsy: neste caso, somente os valores null, undefined, ±0, NaN e strings vazias são considerados falsos. Qualquer outro valor é considerado verdadeiro.
Por exemplo, se num1 ou num2 for um número positivo, a condição será verdadeira e entrará no if.

* Na verdade a expressão a || b retorna o valor de a (caso este seja um valor truthy) ou de b (caso a seja um valor falsy).


Images are uploaded to a different directory than shown in the background:URL style

Question: We've just had to take over the hosting for a Drupal site and I've moved the site across and everything seemed OK. BUT, whenever I try to upload a new image it gets saved in a different directory to where it should.
So the background:URL("") inline style is looking for the image here:
/sites/default/files/styles/segment_background_image/public/file.jpg
When the file is actually saved here:
/sites/default/files/file.jpg
I know absolutely nothing about Drupal and reading other peoples issues is just hours of not understanding a word. Any help would be hugely appreciated.
EDIT: To be more specific, the image doesn't display on the site because the inline style is looking in the wrong directory. It's an inline style, background:url("path"), where the path is different to where it is actually saved.
Answer: That's all correct, you don't need to change anything.
Images under /sites/default/files/styles are derivatives, auto-generated by the system from image styles when first requested.
Comment: The 403 makes sense, image style urls have a token appended to them. The 500 will be the key to fixing this though - check the server logs, they will tell you what's specifically going wrong. It's commonly file permissions
Comment: Sorry, I should have been more specific:
The image doesn't display on the site because the inline style is looking in the wrong directory. It's an inline style, background:url("path"), where the path is different to where it is actually saved.
Comment: Given that you have an actual image style with the name segment_background_image, Drupal will create that image from your uploaded image once you first request it.
Comment: Unfortunately, that doesn't appear to be happening. I've loaded the the page, cleared caches, done what I can to get it to request the image, but it's just just in the files folder
Comment: What response do you get for the image when you visit it directly? 403? 404? 500?
Comment: The console shows 500 on the page, accessing the image directly gives 403 in the console and the page shows "You are not authorized to access this page."
Answer: It was all to do with the new server and it's PHP.ini. Not enough memory, upped that and all of my problems were solved.
Thanks for helping though, confirmed that Drupal was working as it should!


Social network hosting - which Linux OS to use?

Question: So I am looking to get my first hosting (still not sure on VPS or dedicated). it is a social network with photo sharing. Question is the OS. Everywhere i see the options are:
CentOS, Debain, Fedora, Ubuntu.
My website is in MySQL and PHP. So i assume I need a linux install? And which OS to choose? I have never seen linux in my life, always used windows so I have no preference on the linux OS. ideally I prefer a stable, secure, easy to use with nice GUI and that can make my life easy hosting my website along with easy to manage/update. Which one to go for?
Answer: Since you're new to Linux (welcome!) I would start by the bare minimums, so start with a VPS server and if you see you're growing out of it you can always swutch to a dedicated hosting.
Those four Linux distributions are divided in package management, I'll give you a brief introduction to each so you can get up to speed fast.

CentOS: It's based on RedHat Enterprise Linux, which is the Enterprise version of RedHat Linux, it's what the majority of servers are using right now, but there community behind it is not as strong as other distros
Debian: It's one of the oldest Linux distributions, completely open source and maintained by the community, you'll have lots of help in this one but it tends to be a bit behind in features and new software
Fedora: It's the bleeding edge of RedHat Linux, it's maintained by the Fedora community and RedHat, although it's cool to play with it it's not recommended for production unless you know very well what are you doing
Ubuntu: It's a spinoff based on Debian and maintained by Canonical (another big Linux company like RedHat), it's getting lots of traction lately and also very heavily maintained by the community since any Debian answer will also work here

On my personal experience I would either stick to Ubuntu or CentOS, since you're completely new to the Linux world I would try Ubuntu first and see how you manage (it gives you lots of help and easiness), then when you start getting more skills you can always switch to another distro if you prefer.
Answer: If you do not have that much knowledge about linux, then do not jump head first into it, and have a web facing server, that your trying to manage. You'll be taking on too much at first.
If you only need MySQL, and PHP, then find a service that gives you just that - It will help you get started. Then, as time goes on, and your site grows, build a server on some old cheap hardware at home, maybe a £100 server off of ebay, or something and then attempt to 'host' your site on that box. That experience is better earned at home without the pressure of paying someone a monthly fee :)
Ubuntu server is nice for new comers, it's harder to break :)
Comment: virtual machines are great for this, incidentally
Answer: And what comes to GUI not all distro's deliver it as default witch is good.
GUI (aka. desktop (like gnome or kde) eats lot of resources what is away from other usage.
If you feel uncertain to use command like i suggest you to check out web-interfaced management software like ebox or landscape. You should be able to get both of them to work with ubuntu. ebox is free but uses your servers resources and landscape is commercial product witch should be bit more lightweight for your server since it runs on canonical's servers but it is costing a bit.


month or specified date-range wise grouping

Question: Want to group my data by month-wise or specified date-range. Have nearly 3 months of data with non-unique dates (YYYY-MM-DD), already in pandas 'date' format, like
Col1 Col2 Date       Val
12   23   2018-11-20  4
13   78   2018-09-21  4
14   82   2018-10-28  5
15   22   2018-11-10  8
17   35   2018-10-23  9

Want to separate them in Nov(11), Oct(10), Sept(09) wise.
Thanks in advance.
Comment: What is expected output from sample data?
Answer: Here the best is create dictionary:
df['Date'] = pd.to_datetime(df['Date'])

d = dict(tuple(df.groupby(df['Date'].dt.month)))
print (d)
{9:    Col1  Col2       Date  Val
1    13    78 2018-09-21    4, 10:    Col1  Col2       Date  Val
2    14    82 2018-10-28    5
4    17    35 2018-10-23    9, 11:    Col1  Col2       Date  Val
0    12    23 2018-11-20    4
3    15    22 2018-11-10    8}

print (d[9])
   Col1  Col2       Date  Val
1    13    78 2018-09-21    4

Or:
d = dict(tuple(df.groupby(df['Date'].dt.strftime('%b'))))
print (d)
{'Nov':    Col1  Col2       Date  Val
0    12    23 2018-11-20    4
3    15    22 2018-11-10    8, 'Oct':    Col1  Col2       Date  Val
2    14    82 2018-10-28    5
4    17    35 2018-10-23    9, 'Sep':    Col1  Col2       Date  Val
1    13    78 2018-09-21    4}

print (d['Nov'])
   Col1  Col2       Date  Val
0    12    23 2018-11-20    4
3    15    22 2018-11-10    8

It is not recommended, but possible create DataFrames by groups:
for i, g in df.groupby(df['Date'].dt.strftime('%b')):
    globals()['df_' + str(i)] =  g

print (df_Nov)
   Col1  Col2       Date  Val
0    12    23 2018-11-20    4
3    15    22 2018-11-10    8

If need aggregate by months:
df.groupby(df['Date'].dt.month).sum()

Or:
df.groupby(df['Date'].dt.strftime('%b')).sum()

Comment: Tried the 1st one. Perfect! Thank you so much. Will be very handy in various cases also.
Comment: Thanks. My explanation was may not be good. I just want to split the dataframe into parts, say 'df_nov', 'df_oct', 'df_sept' from the main dataframe. The one you have suggested summing up the values of all the other columns with respect to these three months (which might be useful later on).


Cannot make C# View static for passing data from controller to view?

Question: Im trying to pass a string from a Controller to a view and Im not quite sure what Im missing. I cannot make the action method in the controller static because the View then errors with

an object reference is required for the non-static field.

How do I fix this? I would appreciate a detailed explanation, or links to your sources so I can learn.
My controller (LC) has:
...
public ActionResult Action()
{
    LC vm = new LC();
    vm.LicenseTable = DataPull(); //setting a variable in the controller
    return View("LicenseView", vm); //return a view named 'LicenseView'
}
...

my lcview.cshtml:
@using iw.Models //yes I screwed up and put a controller in the models folder
@model LC

    //
@LC.LicenseView
 //calling the Model the the View name FAILS

@LC.Action()
 //Fails because of error below

Error:

An object reference is required for the non-static method LC.Action()
Comment: The "@model LC" declares the object type used as the model, but when you need to access the actual object you use the "model" keyword instead.
Comment: In your cshtml, use @Model.Action()
Comment: `@Model.Action()`
Comment: If your Controller is called LC, are you instantiating a new LC Controller in your Action method and making it a type of ViewModel?
Answer: It looks like you are trying to call the action method named Action of your controller name LC.
You need to use Html.Action as it looks like you want to call the action and render view in the p element:

@Html.Action("Action","LC")

We specify the controller name and action name in this method and it will return the view which will be rendered as html.
Comment: when I try this I get an error that says: `requires receiver of type urlhelper`
Answer: As mentioned in my comment, in your cshtml, use

@Model.Action()

The "@model LC" declares the object type used as the model, but when you need to access the actual object you use the "model" keyword instead.
EDIT
Are you trying to display the LC.LicenseTable string in the HTML?
Use the following:

@Model.LicenseTable

Comment: When I try this I get: `NullReferenceException: Object reference not set to an instance of an object.`
Comment: Are you trying to display LC.LicenseTable in your html? I've updated my answer to show how to do this


Ways to state relationships like "A explains x% the variation in B" but when variation is not present like for non-parametric tests

Question: Example:
Income explains 70% of the variance in expenditure.
Variation in driving speed can be explained by drivers' age.
How does one make such statements if the test used is a non-parametric one? I was told before that non-parametric tests such as the Spearman and Kruskal-Wallis does not test for variances, hence it is not right to mention "variance" when interpreting.
Comment: I changed the title to make more salient this interresting aspect about nonparametric tests and the idea of interpreting/stating relations like in terms of ratios of variance but then *without* the variance. This edit is a very subjective thing (I changed the title because while reading your post I thought your question is much more interresting than what I expected from the title; I expected a lame beginners question about correlation/causation). You can change it back or improve it further if you like.
Comment: In logistic regression relationships are often expressed in terms of odds ratio "A increases the odds of B with a factor x".
Answer: You're right that effect size statistics for nonparametric tests usually can't be expressed in terms of variance explained.
Spearman correlation is equivalent to Pearson correlation on the ranks of the data.  I suppose you could convert this, by squaring rho, to "variance of the ranks of y explained by the ranks of x", but I suspect relying the audience to understand rho is a better approach.
For Wilcoxon-Mann-Whitney, an easily understandable effect size statistic is Vargha and Delaney's A, which is simply the probability of an observation in one group being larger than an observation from the other group.  This could also be used for pairs of groups in Kruskal-Wallis.
There are other effect size statistics used for nonparametric tests that can be difficult to interpret in words.  For example, there is an epsilon-squared used for Kruskal-Wallis. It's a useful statistic, but not easy to interpret in words.
There is also an "eta-squared" used for Kruskal-Wallis, which is supposed to be more related to the usual eta-squared for an anova on the ranks of the y variable.  (eta-squared is the same as the r-squared from an anova).  But I'm not that enamoured with this statistic.
Likewise there is an "r" commonly used for Wilcoxon-Mann-Whitney, but it doesn't have great properties for an effect size statistic.  It's better to use Vargha and Delaney's A, Cliff's delta, or rank biserial correlation.


Download bytes docx api rest

Question: O código mostra um método que é chamado pelo navegador para gerar um PDF. Os bytes foram gerados pelo Jasper. O código funciona normalmente.
@GetMapping("/relatorios/teste")
public ResponseEntity<byte[]> relatorio() throws Exception{
    byte[] relatorio = lancamentoService.relatorio();

    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE)
        .body(relatorio);
}

OBS1: Meu problema é quando tenho os bytes de um docx! Já tentei fazer algo similar ao PDF, mas ainda não obtive êxito, tentei diversos códigos encontrados pela net e nada.
OBS2: Os bytes docx eu gero usando o Apache POI.
Comment: Está usando Spring Boot?
Answer: Sugiro algumas alterações no seu esquema de download, a segunda não é obrigatória mas eu recomendo mesmo assim:

Utilize MediaType.APPLICATION_OCTET_STREAM já que você trabalha com vários formatos, esse tipo é considerado um dado arbitrário segundo a RFC2046 e vai servir nesse caso.
Adicionar no header a propriedade para evitar cache no-cache (não obrigatório)

E por fim atualizar seu código para construir o ResponseEntity desta forma:
@GetMapping("/relatorios/teste")
public ResponseEntity<byte[]> relatorio() throws Exception {
    return new ResponseEntity<>(lancamentoService.relatorio(), getConfiguredAttachmentHeaders(), HttpStatus.OK);
}

private HttpHeaders getConfiguredAttachmentHeaders() {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setCacheControl(CacheControl.noCache().getHeaderValue());
    httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return httpHeaders;
}

Download bytes docx api rest


Density of pixels in android

Question: If I have android device with 5 inches diagonal screen size and 2.3 inches screen width and its screen supports 1080*1920 pixels what is the nearest type of its screen density? How can solve this question?
Answer: You should use sp for font sizes and dp for anything else. See this SO post regarding screen density, terminology, and proper uses: Difference between px, dp, dip and sp in Android?
Also, here is a link to the android developer's API guide for supporting multiple screens in your applications: http://developer.android.com/guide/practices/screens_support.html
Answer: You can find out device display info reading DisplayMetrics from Activity
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);

int dpi = dm.densityDpi;

dm.densityDpi will give you device dpi bucket expressed in dots-per-inch
You can also get other display metrics like:
float density       - The logical density of the display - scaling factor
float scaledDensity - A scaling factor for fonts displayed on the display.
int widthPixels     - The absolute width of the display in pixels.
int heightPixels    - The absolute height of the display in pixels.
float xdpi          - Physical pixels per inch of the screen in the X dimension.
float ydpi          - Physical pixels per inch of the screen in the Y dimension.

However, for some devices xdpi and ydpi metrics are returning wrong numbers and you cannot rely on them. Since API 17 you can also use getRealMetrics(). It should give you accurate values for xdpi and ydpi.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(dm);

Density of pixels in android


How to use external data?

Question: I'm building the model using the internal data to predict the health situation of the customer. I've just found about 100 new "external data" in the form of region data. Based on this new information, I create a first new variable "Diabetes" i.e over 100 people in Lazio, 14.1 of them have the diabetes; this number in Milan is 15, ...
There are still 100 variables like this, for example here: "Hypertension", which is also linked to "Region", like "Diabetes", i.e if two prospects have the different value for "Diabetes", they will have also different value for "Hypertension", and vice versa. My questions are:

Should I add "Hypertension" into the model?
Does "Hypertension" add the new information into our model with respect to the variable Diabetes?
How can I use all of the 100 new variables in the most effective way?
Answer: You can bring in the external data, and you may want to consider a multilevel or hierarchical model when you do so, given then many of your variables will be grouped by region. A good explanation of multilevel models can be found here.
The typical example is estimating test performance in schools - you have individual characteristics of each of the students, but then you also have school-specific characteristics - this would seem to be a good analogy for the problem you've described.

How to use external data?


Estimates of the derivatives of the fundamental solution of heat equations in $\mathbb{R}^n$

Question: Let
$$n_t(z)=\frac{1}{(4\pi t)^{n/2}}e^{-\frac{1}{4t}\|z\|^2}.$$
And the differentiation w.r.t. $x$, denotes as $D_x^{r}$ is defined as
$$\frac{\partial^{|r|}}{\partial x_1^{r_1}\cdots\partial x_n^{r_n}}.$$
The claim is
$$|D_x^{r}(y-x)|\le C_{r,t}\,n_{t/2}(y-x).$$
Could anyone show me explicitly how? Special attention to $t/2.$
Thanks
Answer: Hint:

Show (e.g. by induction) that for any fixed $t$, $r$, the derivative
$$\frac{\partial^{|r|}}{\partial_{z_1}^{r_1} \cdots \partial_{z_n}^{r_n}} n_t(z)$$
is of the form
$$p_{t,r}(z) n_t(z)$$
for some polynomial $p_{t,r}$.
Recall that $$z \mapsto p_{t,r}(z) n_{R}(z)$$ is bounded for any $R>0$ since the exponential function $e^{-|z|^2/2R}$ decays faster than any polyomial that
Write $$p_{t,r}(z) n_{t}(z) = \left( p_{t,r}(z) \frac{n_t(z)}{n_{t/2}(z)} \right) n_{t/2}(z)$$ and conclude from step 2 that term in the brackets is bounded (in $z$).


Show that h fulfill the linearity requirements

Question: I have a problem, I am uncertain of how to solve:

Is it enough to show:
$L_1$: $g(f(v_1)+f(v_2)) =$ $g(fv_1)+g(fv_2)$
$L_2$: $k*g(f(v)) = $ $g(kf(v))$
And if so, should I find the mapping matrices for $ g$ and $f$ or is there a smarter way?
Answer: You know that $f$ and $g$ are linear and so proving $gf$ is linear can be done without using their matrices.
$$gf(v_1+v_2)=g(f(v_1)+f(v_2))=g(f(v_1))+g(f(v_2))$$
$$gf(kv)=g(kf(v))=kg(f(v))$$
Note that $g(v_1)+g(v_3)=v_1$ and $g(v_1)-g(v_3)=2v_3$. You can use linearity to then find that  $g(v_1)=\frac{1}{2}v_1+v_3$ and $g(v_3)=\frac{1}{2}v_1-v_3$.
Now all you have to do is equate $gf(av_1+bv_2+cv_3)$ to $av_1+bv_2+cv_3$ and solve for $a,b,c$.
By linearity $f(av_1+bv_2+cv_3)=(4a-2b+2c,c,-2a+b-c)$.
Applying $g$ I now get
$$(a-b/2+c/2,c,6a-3b+3c)$$
To equal $(a,b,c)$ we need $6a=b=c$.
Comment: Its probably easier not to. I'll add something above.
Comment: I'll edit the answer to show this but I type very slowly!
Comment: Yes - that's right for the middle part since $g$ maps$v_2$ to itself. The others are more complicated though- remember $g(v_1)=\frac{1}{2}v_1+v_3$ and so you have to do that to $(4a-2b+2c)v_1$ but you then need to add the result of $g$ acting on the other two components - its long winded to explain!
Comment: Yeah, I know I need to prove those two requirements, but my question was how I should do it? I mean, how can I justify that what you have written right there is true, when I have no formula for the functions?
Comment: The proof is complete. Look at the first equation - the first step uses linearity of $f$ which you are given. The next step uses linearity of $g$ which you are also given.
Comment: Hmm, I see thank you. What about the other part of the question, about finding two fixvectors for h? Aren't I going to need matrices for that part?
Comment: I don't understand how you can say that g(v1)+g(v3)=v1. You don't have any numbers or coordinates for v1 or v3. Also, when you write gf(av1 + bv2 + cv3) do you mean g(f(av1 + bv2 + cv3))?
Comment: I have assumed that the notation (1,0,1) means $v_1+v_3$ since we've been told the $v_i$ are the basis.
Comment: Re the $gf$ query - yes, that is what $gf$ is defined to mean.
Comment: Sorry for bothering you so much, but I really don't quite get it. How am I supposed to find out what f(av1 + bv2 + bv3) is? We are mapping from V -> V, meanwhile f is only shown mapping from V -> R^3, if you know what I mean.
Comment: That's totally fine sir take as long as you need to! I'm just so happy that you are this generous and willing to help a slow-minded like me :)
Comment: Yeah, I think I'm finally starting to understand the entire thing. One last thing though. I don't get how you are applying g. It seems like you are dividing the first part (4a-2b+2c) with 4, doing nothing to the middle part (c) and multiplying the last part (-2a+b-c) with -3. Can you explain how that happens?
Comment: You'll probably get more confidence if you first check my final answer. Can you find the result of applying $f$ and then $g$ to $v_1+6v_2+6v_3$. You should find you get  $v_1+6v_2+6v_3$ i.e. it is fixed.
Comment: I, unfortunately, need to say "no" to that question. I simply don't see what neither f nor g is doing to the vector $v_1 + 6v_2 +6v_3$ and I don't understand why the solution (a,b,c) needs to be 6a=b=c.
Comment: I'm adding another answer to try to explain better.
Answer: Are you happy that $f(v_1)=4v_1-2v_3$ and $f(v_2)=-2v_1+v_3$ and $f(v_3)=2v_1+v_2-1v_3$?
Good. So now consider $f(av_1+bv_2+cv_3$).
By linearity, this will be:-
$$a(4v_1-2v_3)+b(-2v_1+v_3)+c(2v_1+v_2-1v_3)$$
Good. So now you have got to line -4 of my previous answer.
$f(av_1+bv_2+cv_3)=(4a-2b+2c,c,-2a+b-c)$.
We now have to do this process again for $g$.
You should get $(a-b/2+c/2,c,6a-3b+3c)$
We now require $g(4a-2b+2c,c,-2a+b-c)$. Let's do $g(4a-2b+2c)v_1$ first. It is $$(2a-b+c)v_1+(4a-2b+2c)v_3$$
Now for $g(cv_2)$. Easy! It's just $cv_2$.
Finally you need to work out $g((-2a+b-c)v_3)$.
Now we must equate $$(a-b/2+c/2,c,6a-3b+3c)=(a,b,c)$$ since we are looking for a fixed vector.
For the first coefficient we have $a-b/2+c/2=a$ and therefore $b=c$. This also deals with the coefficients of $v_2$.
For the final coefficient we have $6a-3b+3c=c$ and this gives $c=6a$.
Comment: You'll need to include the $a$s etc. So the first one should be $4a-2b+2c$.
Comment: I'll type it into the new answer.
Comment: That's good but it's minus the last term
Comment: Now add our last three answers and it should come to the last but one line of my previous answer. Is that OK?
Comment: Yes - let's write it as $(a-b/2+c/2,c,6a-3b+3c)$.
Comment: Now this must equal $(a,b,c)$ if $( a,b,c)$ is to be a fixed vector.
Comment: Yes you've got the right idea. See the end of my second answer.
Comment: You can apply $gf$ to these vectors and see if they are really fixed as a check. But I'm going off line now! Glad you've got it sorted.
Comment: Yes, because (4,0,0)=4 $v_1$ and (0,0,-2)=-2 $v_3$. $(-2,0,0)=-2v_1$ and (0,0,1)=$1v_3$.
Comment: Yes, because $f(av_1 = af(v_1) = a(4v_1-2v_3)$. And so on.
Comment: $(4a-2b+2c)v_1 +(cv_2) + (-2a+1b-1c)v_3$.
Comment: Yes, I've edited my comment now, and I think it's correct.
Comment: I'm will try. $g(v_1)=1/2v_1+v_3 =(2a-b+c)+(-2a+b-c)=0$? That can't be right, am I supposed to add before I mupltiply?
Comment: $g((-2a+b-c)v_3) =(-a+b/2 -c/2)v_1-(-2a+b-c)v_3$
Comment: $((2a-b+c)+(-a+b/2-c/2)v_1) = a-b/2+c/2$.
$((4a-2b+2c)+(2a-b+c)v_3) = 6a-3b+3c$.
$v_2=c$
Comment: Ahhh, Okay I understand now. So any coefficients that make the equation $6a=b=c$ true is a fixvector. So for example, $v_1,6v_2,v_3$ and $2v_1,12v_2,12v_3$ are both fixvectors?
Comment: Yes but they must be added i.e. $v_1+6v_2+6v_3$ and $2v_1+12v_2+12v_3$ etc.
Comment: And if the basis is $a=(v_1,v_2,v_3)$ then the vectors would be (1,6,6) and (2,12,12) with respect to the basis $a$?
Comment: Yes, that's correct.
Comment: I see! Thank you so much for your patience, generosity and general professionalism in helping me. It means a lot. Have a good day sir, and take comfort in knowing you made a guy in need very happy :)


Whats wrong with my contact form?

Question: Could someone please take a look at my website's code and tell me why my contact form isnt working?
Here are the relevant portions of code:
From the contact.html file:

Contact Form

    <form action="#" id="contact-form">

 Contact form submitted!

            We will be in touch soon.

            <fieldset>

                <input type="text" value="Enter Your Name:">
                *This is not a valid name.
                *This field is required.

                <input type="text" value="Enter Your E-mail:">
                *This is not a valid email address.
                *This field is required.

                <input type="tel" value="Enter Your Phone:">
                *This is not a valid phone number.
                *This field is required.

                <textarea>Enter Your Message:</textarea>
                *The message is too short.
                *This field is required.

                    Clear
                    Send

            </fieldset>
    </form>

Also from the contact.html file:

I think this is the piece of code that links to a javascript file which in turn calls "mailhandler.php".
Comment: What is wrong with it? what is the error? client side or server side error? what backend are you using? where is the form supposed to post to?
Comment: Im sorry I dont have much experience with web development. I am editing a template I found.
Comment:       Another line of code  from the same form. I think it uses this file
Comment: from the script.js file:mailHandlerURL:'bin/MailHandler.php',
      ownerEmail:'email@example.com',
Comment: Please me, i am facing same problem... I have added ownerEmail, php file, mailHandlerURL. changed action too.. not working. please help to activate this form. Thanks
Answer: <form action="some script"  METHOD="POST"   ENCTYPE="multipart/form-data"></form>

action="php or asp or pl script for processing form"
Answer: You didn't specify where the form should post to - what is the name of the script that you want to post this form to?
Now it says:
form action="#"

And it should say something like:
form action="contact.php"

Comment: I added another bit of code from the contact.html file. Do you think there could be something else wrong?

Whats wrong with my contact form?


Mysql bug, ghost column

Question: I delete a column in mysql called "clanName" and i see this:

I can't edit it, and that column doesn't exists.
I restart mysql and Xampp and continue...
Any ideas?
Comment: How did you delete it?
Comment: In the structure panel, i press "Delete"
Comment: Maybe a phpmyadmin bug,try another client like heidisql.
Comment: I will not change the database, I do not send querys generated problems, so here I leave as well. (Google traductor, i'm spanish)
Comment: Can you access the DB with a desktop client like (if on OS X) [Sequel Pro](http://sequelpro.com)?
Answer: There is a tab called 'Operations.' Click on that tab and duplicate this table. There is an excellent chance that your duplicated version will no longer contain the empty column.
If this works, you can then rename the original version by appending the word 'BACKUP' to the name. Then rename your newly duplicated copy to the original table's name and test. If everything works with your project, you may wish to delete the old (and broken!) backup copy.
Good luck, please let me know if this works for you. If it does not please export a copy of the database table and post it here on StackOverflow. I will be happy to examine it further.
Comment: I solve the "bug" creating a new column, this repleace the old and bugged column :), but Thanks
Comment: Thank you very much!  I am really glad you have been successful. Please feel free to let me know if you need any other help.

Mysql bug, ghost column


Como criar um diretório em Python dentro de um servidor?

Question: Usando a função mkdir é possivel criar um arquivo em qualquer diretório dentro das pastas do computador:
Import os
diretorio = "C:\\Users\\CRIACAO 2\\Desktop\\teste"
os.mkdir(diretorio)

Porém quando tento cria-la dentro do endereço de um servidor, o programa não é capaz de encontrar o caminho indicado:
Import os
diretorio = "\\servidor\ARABRINDES 1TB\Artes"
os.mkdir(diretorio)

FileNotFoundError: [WinError 3] O sistema não pode encontrar o caminho especificado: '\servidor\ARABRINDES 1TB\Artes\andrei'

Como posso resolver esse problema?
Answer: O seu problema é que você está usando uma contrabarra só, e caminhos para servidor começam com duas contrabarras \\...
Explicando melhor, o Python interpreta strings que tem contrabarras de forma especial. Por exemplo, '\t' é o tab, '\n' é a quebra de linha e '\\' é uma barra só!
Você pode ver que esse é o caso através da mensagem de erro:
FileNotFoundError: [WinError 3] O sistema não pode encontrar o caminho especificado:
'\servidor\ARABRINDES 1TB\Artes\andrei'

Para resolver, use quatro barras, ou seja, duas para cada barra:
diretorio = "\\\\servidor\\ARABRINDES 1TB\\Artes"

Ou melhor ainda, use raw strings sempre que for escrever um caminho:
diretorio = r"\\servidor\ARABRINDES 1TB\Artes"

Colocando esse r antes da string faz com que o python não processe caracteres especiais dentro dela. Ela sai exatamente como está escrita!
Leia a documentação aqui: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
Comment: Muito obrigado! O erro era exatamente isso e consegui resolve-lo.
Answer: Tive um problema parecido, esse erro aconteceu porque está executando o comando para um caminho relativo e não um caminho absoluto. O correto seria passar por parâmetro todo o caminho do servidor.
Espero ter ajudado.
Comment: Não é o caso, o caminho `\\servidor\ARABRINDES 1TB\Artes` é absoluto - inclui o nome do servidor, o compartilhamento e todo o caminho para chegar na pasta.
Comment: Obrigado pela correção, acabei confundindo o problema que tive.


Java how to set subclass tag (field) with a superclass method

Question: I have a class,
public class Jo{
    public int objCount = 0;
    private int i = 0;
    public class Property{
        String Tag = new String();
        Jo data;
    }

    public Property propertyArray[] = new Property[12];

    public void add(String St, Jo Obj){
        propertyArray[objCount] = new Property();
        propertyArray[objCount].Tag = St;
        propertyArray[objCount].data = Obj;
        objCount++;
    }
}

and a subclass,
public class Js extends Jo{
String data = new String();
public Js(String St){
    this.data = St;
}

}
I need to set the Tag field of the subclass when I call the add method like this.
Jo first = new Jo();
first.add("firsttag", new Js("first string"));

But it's not working.
Comment: AFAIK, you cannot do that
Answer: You can't do that because the property Tag is a member of the inner class Jo and therefore can only be accessed by the outer class Jo. To make the property Tag accessible to the subclass, you have to remove the inner class and add the Tag property as a property of the class Jo. But, remember, if the Tag property is declared as:
 private String tag; // note tag not Tag with a capital-letter

Then, the tag property will not be accessible to the subclass Js. You will have to create a setter for tag in Jo that can be called in Js.
Comment: I created the inner class to create an array to keep multiple properties. Are there any other ways to do it? (except ArrayList)
Answer: @floydian: Your code works fine so retry running it once again.You should be able to set the tag field of the sub-class using the add method unless the field is marked private. Refer the oracle docs for nested classes tutorial http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html


Change Text color on tap in SwiftUI

Question: I have defined a List of Text inside SwiftUI in the following way.
struct SampleView: View {
    private let list: [String] = ["Tapping each line should change its color from grey to black", "First Line", "Second Line", "Third Line."]

    var body: some View {
        ScrollViewReader { value in
            List {
                ForEach(Array(zip(list, list.indices)), id: \.0) { eachString, index in
                    Text(eachString)
                        .bold().font(.largeTitle)
                        .foregroundColor(.gray)
                        .onTapGesture {
                            self.foregroundColor(.black)
                        }
                }
            }.listStyle(.plain)
        }.frame(maxHeight: .infinity)
    }
}

struct SampleView_Preview: PreviewProvider {
    static var previews: some View {
        SampleView()
    }
}

I need to be able to change the foregroundColor of a particular TextView whenever the user taps on it.
CustomString is a class that I defined that conforms to Hashable. I can't get it to conform to ObservableObject at the same time which means I can't change its value inside the onTapGesture block.
I also can't remove the index from the loop as I'll need that too.
TIA.
Comment: Please take the [tour](https://stackoverflow.com/tour) and read [How to Ask](https://stackoverflow.com/help/how-to-ask) to improve, edit and format your questions.

Without a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) it is impossible to help you troubleshoot.
Answer: Don't take it personal at all, just keep in mind that Stackoverflow is a great way to share between developers, but all the basics are much more clear in the documentation and samples from Apple. They are incredibly well done by the way.
https://developer.apple.com/tutorials/swiftui
And for your problem, you must declare a state variable with your color, so when the color changes, the view is regenerated.
I have not tested your code, because you don't provide a copy/paste ready to run playground or view class, but you see the principle.
One sure thing is that if you need each text cell to update independently, you should make a "TextCell" subview or whatever, that has it's own color. Not at the highest level. In your code, I presume all cells will get the same color, since it is defined at top level of your List.
Happy new year :)
...
@State var color: Color = .gray

var myString: [CustomString]
...

ScrollViewReader { value in
    List {
        ForEach(Array(zip(myString, myString.indices)), id: \.0) { eachString, index in
        Text(eachString.text)
        .foregroundColor(color)
        .onTapGesture {
            self.color = .black
        }
    }
}

Comment: Thank you for your input. I have updated my question to make it minimally reproducable. I have also tried out your solution which unfortunately has not worked. Creating an `@State` variable changes the color of every other `TextView` before that. All these `Text` are actually created inside a `ForEach` loop.
Comment: That was anticipated in my answer. I wrote that you need to move the @State in a custom view of your own containing the text, and use it in the loop.

Change Text color on tap in SwiftUI


What is the purpose of 0-length midi notes?

Question: I have several midi files that contain notes with 0 duration. There will be a note_on event, then the next event for the same note says note_off and the time attribute is 0. Is there a purpose to these 0-length midi notes?
Comment: One could suspect a lame editing software, which instead of delete a note, just put its length to zero…
Comment: Do you know what sound these notes are intended to trigger?
Comment: To elaborate on topo Reinstate Monica's comment, are the 0-length notes for unpitched percussion instruments such as snare drums?
Comment: @Tom_C That was my thought! I just wan't sure if somehow a 0-length note would get played for some microsecond, like a grace note or something...
Answer: Many percussion instruments have a fixed-length sound and ignore note-off messages, but MIDI files must not omit note-off messages. So the timing of these messages does not matter.
Comment: Presumably they are "one-shots" where the whole sample is played no matter how long the midi note, hence taking no notice of the note off.
Comment: Thanks! Can I please ask you to say a little more about what you mean when you say some percussion instruments ignore note off messages? I'm not sure I follow yet...


Deploying play! 2.0 application on an apache server with a reverse proxy

Question: I'm trying to deploy my play! 2.0 application on an Ubuntu 11.10 server and I have been running into error after error and hope someone can help me here. I am try to deploy my Play! application using a reverse proxy on Apache 2. I have enabled the apache proxy modules and configured the proxy.conf file in mods_enabled. The vhost for my domain looks like this:
<Directory /var/www/stage.domain.com>
    AllowOverride None
    Order Deny,Allow
    Deny from all
</Directory>

<VirtualHost *:80>

    DocumentRoot /var/www/stage.domain.com/web

    ServerName stage.domain.com
    ServerAdmin email@example.com

#    ProxyRequests Off
#    ProxyPreserveHost On
     <Proxy *>
        Order allow,deny
            Allow from all
     </Proxy>
#    ProxyVia On
#    ProxyPass /play/ http://localhost:9000/
#    ProxyPassReverse /play/ http://localhost:9000/

    ErrorLog /var/log/ispconfig/httpd/stage.domain.com/error.log

    ErrorDocument 400 /error/400.html
    ErrorDocument 401 /error/401.html
    ErrorDocument 403 /error/403.html
    ErrorDocument 404 /error/404.html
    ErrorDocument 405 /error/405.html
    ErrorDocument 500 /error/500.html
    ErrorDocument 502 /error/502.html
    ErrorDocument 503 /error/503.html

    <IfModule mod_ssl.c>
    </IfModule>
    <Directory /var/www/stage.domain.com/web>
        Options FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
    <Directory /var/www/clients/client2/web7/web>
        Options FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>

    # Clear PHP settings of this website
    <FilesMatch "\.ph(p3?|tml)$">
        SetHandler None
    </FilesMatch>
    # mod_php enabled
    AddType application/x-httpd-php .php .php3 .php4 .php5
    php_admin_value sendmail_path "/usr/sbin/sendmail -t -i -email@example.com"
    php_admin_value upload_tmp_dir /var/www/clients/client2/web7/tmp
    php_admin_value session.save_path /var/www/clients/client2/web7/tmp
        # PHPIniDir /var/www/conf/web7
    php_admin_value open_basedir /var/www/clients/client2/web7/:/var/www/clients/client2/web7/web:/va$

    # add support for apache mpm_itk
    <IfModule mpm_itk_module>
      AssignUserId web7 client2
    </IfModule>

    <IfModule mod_dav_fs.c>
          # Do not execute PHP files in webdav directory
      <Directory /var/www/clients/client2/web7/webdav>
            <FilesMatch "\.ph(p3?|tml)$">
          SetHandler None
        </FilesMatch>
      </Directory>
      # DO NOT REMOVE THE COMMENTS!
      # IF YOU REMOVE THEM, WEBDAV WILL NOT WORK ANYMORE!
      # WEBDAV BEGIN
      # WEBDAV END
    </IfModule>
#       <Location /play/>
#               ProxyPass http://localhost:9000/
#               SetEnv force-proxy-request-1.0 1
#               SetEnv proxy-nokeepalive 1
#       </Location>
        ProxyRequests Off
        ProxyPass /play/ http://localhost:9000/
        ProxyPassReverse /play/ localhost:9000/
        ProxyPass /play http://localhost:9000/
ProxyPassReverse /play http://localhost:9000/

#       SetEnv force-proxy-request-1.0 1
#       SetEnv proxy-nokeepalive 1
</VirtualHost>
This vhost file was generated by ispconfig and I have not touched anything that was there before just added onto. As you can see by the commented out parts I have tried a lot of different things based on random tutorials I have found but all of them have ended up in Internal Server Error, 503 and most often a '502 Bad Gateway`.
I can start play and it does connect successfully to my database. I can get a page to show up when there is an error and the play! stack trace error pages comes up but where everything is fine I get one of the errors above.
My application.conf file looks like this:
db info
.......
application.mode=PROD
logger.root=ERROR

# Logger used by the framework:
logger.play=INFO

# Logger provided to your application:
logger.application=DEBUG

http.path="/play/"
XForwardedSupport="127.0.0.1"

And my hosts file looks like this (I have never changed or added anything to the host file):
127.0.0.1       localhost
127.0.1.1       matrix

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Any insights onto what I might be doing wrong or if theres anything I can try please let me know! Thanks!!
Edit
Again the reverse proxy will work (I checked with sending to to google.com). Its when there is a successful connection to Netty. It's like Netty refuses the connection to the page.
Edit 2
output from apachectl -S
_default_:8081         127.0.0.1 (/etc/apache2/sites-enabled/000-apps.vhost:10)
*:8090                 is a NameVirtualHost
         default server 127.0.0.1 (/etc/apache2/sites-enabled/000-ispconfig.vhost:10)
         port 8090 namevhost 127.0.0.1 (/etc/apache2/sites-enabled/000-ispconfig.vhost:10)
*:80                   is a NameVirtualHost
         default server 127.0.0.1 (/etc/apache2/sites-enabled/000-default:1)
         port 80 namevhost 127.0.0.1 (/etc/apache2/sites-enabled/000-default:1)
         port 80 namevhost domain.com (/etc/apache2/sites-enabled/100-domain.com.vhost:7)
         port 80 namevhost domain.com (/etc/apache2/sites-enabled/100-domain.com.vhost:7)
         port 80 namevhost domain.com (/etc/apache2/sites-enabled/100-domain.com.vhost:7)
         port 80 namevhost domain.com (/etc/apache2/sites-enabled/100-domain.com.vhost:7)
         port 80 namevhost domain.com (/etc/apache2/sites-enabled/100-domain.com.vhost:7)
         port 80 namevhost stage.domain.com (/etc/apache2/sites-enabled/100-stage.domain.com.vhost:7)
         port 80 namevhost domain.com (/etc/apache2/sites-enabled/100-domain.com.vhost:7)
Comment: Please can you provide the output from `apachectl -S`?
Comment: @AlexLeach updated in question
Answer: I've found the best way to proxy incoming connections is to do so using mod_rewrite. Can't guaratee anything, but something like what's below might work for you. Of course you'll need to enable mod_rewrite in the server settings.
<Location /play>
    Order deny,allow
    Allow from all
</Location>
RewriteEngine on
RewriteRule ^https?://%{SERVER_NAME}/play/?(.*)$ http://localhost:9100/$1 [P,L]

Another thing you'll need to make sure of, is that any virtual server listening on port 80 is a name-based virtual host. apachectl -S should tell you whether there's multiple hosts listening on port 80.
Comment: The problem isn't with the proxy (it works) its more with connecting to port 9000 either as `localhost:9000` in lynx or `stage.domain.com:9000` / `stage.domain.com/play` in the browser
Answer: Start with the basics in your vhost:
ProxyPreserveHost On
ProxyPass /play http://localhost:9000/play
ProxyPassReverse /play http://localhost:9000/play

And you can add other directives once you have this portion working.
At the very least, these lines should proxy the main page. I imagine, you can get to http://localhost:9000/play without issue? To troubleshoot further, enable logging for mod_proxy: http://httpd.apache.org/docs/current/logs.html#permodule
Comment: if you can't connect to localhost:9000, then the Play server doesn't sound like it's listening, or accepting connections on that port. Check that port's actually being used, with `sudo netstat -tulpn | grep 9000`. For the proxy to work, I think you might need to provide application.conf with the IP address of the proxy server, as seen from the client. Quoting http://www.playframework.org/documentation/1.1/production: ""Play will change the request.remoteAddress from the proxy's IP to the client's IP. You have to list the IP addresses of your proxy servers for this to work.""
Comment: That's an IPv6 port, and your Apache process is proxying the connection through to the IPv4 localhost port. In firefox, you should be able to access this with the address `http://[::1]:9000`, but that won't help your proxy issues. Either reconfigure the proxy to point to ::1, or update your play app to listen on IPv4.
Comment: I've updated my question. I cannot get localhost:9000/play to work. It returns `Bad Gateway` in the browser and in lynx if I type `localhost:9000` the connection is refused and is aborted.
Comment: (Sorry, wrong sub-post)
Comment: That gives me this: `tcp6       0      0 :::9000                 :::*                    LISTEN      15847/java ` It looks like it is listening but it just get disconnected via jetty
Comment: The proxy works fine. I've created a new virtual server and I've gotten play to work just fine. Thanks for your help
Comment: If you start your play application with:

-Djava.net.preferIPv4Stack=true

It will listen on an IPV4 address.


Question in the proof of Set Point Difference by One from a Compact has Measure Zero

Question: I am reading the top voted proof here given in To show that the set point distant by 1 of a compact set has Lebesgue measure $0$. Granted a great proof, I can not prove the first line of inequality:
$$m(B_\epsilon(x_0) \cap B) \geq \frac{1}{2^n} m(B_\epsilon(x_0)).$$
I can see this from a picture drawn in 2D as the quadrant of $B_\epsilon(x_0)$ is obviously contained in $B_\epsilon(x_0 \cap B)$. But how does one show this rigorously using properties of measure? How would one use, say, scaling factors of Lebesgue measures in $\mathbb{R}^n$? I see that this inequality is the same as
$$
m(B_\epsilon(x_0) \cap B) \geq m(B_\frac{\epsilon}{2}(x_0)).
$$
But then what?
Answer: The crucial claim here is that, since $x_0$ is on the boundary of $B_1(y_0)$, we can fit an orthant $\tilde{B}_\epsilon(x_0)$ of $B_\epsilon(x_0)$ inside $B_\epsilon(x_0) \cap B_1(y_0)$ (we'll look at this claim carefully in a bit). An orthant is an intersection of a quadrant with a sphere, so there are $2^n$ rotated copies of $\tilde{B}_\epsilon(x_0)$ inside $B_\epsilon(x_0)$. Using the translation- and rotation-invariance of the Lebesgue measure is what thus allows us to say that
$$
m(\tilde{B}_\epsilon(x_0)) = \frac{1}{2^n} m(B_\epsilon(x_0)),
$$
which renders
$$
m(B_\epsilon(x_0))
\geq m(B_\epsilon(x_0) \cap B_1(y_0))
\geq m(\tilde{B}_\epsilon(x_0))
= \frac{1}{2^n} m(B_\epsilon(x_0)).
$$
Now, we'll show that we can chose an orthant $\tilde{B}_\epsilon(x_0) \subseteq B_\epsilon(x_0) \cap B_1(y)$.
By translation and rotation invariance, we can assume without loss of generality that $x_0 = (0, \dotsc, 0)$ and $y_0 = (1/\sqrt{n}, \dotsc, 1/\sqrt{n})$.
We choose this so that we can use the positive orthant
$$
\tilde{B}_\epsilon(0)
= \{\mathbf{x} \in B_\epsilon(0) : x_i \geq 0 \text{ for all } i\}.
$$
And any $\epsilon < 2/\sqrt{n}$ (in the original proof, they choose $\epsilon < 1/2$, but I think that this is actually a mistake - correct me if I'm wrong!).
One of the ways of showing that $\tilde{B}_\epsilon(0) \subseteq B_1(y)$ is to show that the $[0, \epsilon]^n \subseteq B_1(y)$, since $\tilde{B}_\epsilon(0) \subseteq [0, \epsilon]^n$.
To to this, we need only show that $B_1(y)$ contains the vertices of $[0, \epsilon]^n$, each of which have $k$ entries with value $\epsilon$ and $n-k$ entries with value $0$s. Thus, for any such vertex $v$, we have
\begin{align*}
d(v, y_0)^2
&= k (\epsilon - 1/\sqrt{n})^2 + (n-k) \cdot (0- 1/\sqrt{n})^2 \\
&= k\epsilon^2 - \frac{2k\epsilon}{\sqrt{n}} + 1 \\
&\leq 1,
\end{align*}
where in the last line we use the fact that $\epsilon < 2/\sqrt{n}$.
Hence, $v \in B_1(y_0)$, and so we are done.


Why is assignment slower when there's an implicit conversion?

Question: If there was similar questions please direct me there, I searched quiet some time but didn't find anything.
Backround:
I was just playing around and found some behavior I can't completely explain...
For primitive types, it looks like when there's an implicit conversion, the assignment operator = takes longer time, compared to an explicit assignment.
int iTest = 0;
long lMax = std::numeric_limits<long>::max();
for (int i=0; i< 100000; ++i)
{
    // I had 3 such loops, each running 1 of the below lines.
    iTest = lMax;
    iTest = (int)lMax;
    iTest = static_cast<int>(lMax);
}

The result is that the c style cast and c++ style static_cast performs the same on average (differs each time, but no visible difference). AND They both outperforms the implicit assignment.
Result:
iTest=-1, lMax=9223372036854775807
(iTest = lMax) used 276 microseconds

iTest=-1, lMax=9223372036854775807
(iTest = (int)lMax) used 191 microseconds

iTest=-1, lMax=9223372036854775807
(iTest = static_cast<int>(lMax)) used 187 microseconds

Question:
Why is the implicit conversion results in larger latency? I can guess it has to be detected in the assignment that int overflows, so adjusted to -1. But what exactly is going on in the assignment?
Thanks!
Comment: I would guess your benchmarking is flawed.
Comment: Try altering the order of the tests. Maybe it's always the first one that takes longest. Also it looks like 100000 is too small here.Make the tests longer.
Answer: If you want to know why something is happening under the covers, the best place to look is ... wait for it ... under the covers :-)
That means examining the assembler language that is produced by your compiler.
A C++ environment is best thought of as an abstract machine for running C++ code. The standard (mostly) dictates behaviour rather than implementation details. Once you leave the bounds of the standard and start thinking about what happens underneath, the C++ source code is of little help anymore - you need to examine the actual code that the computer is running, the stuff output by the compiler (usually machine code).
It may be that the compiler is throwing away the loop because it's calculating the same thing every time so only needs do it once. It may be that it throws away the code altogether if it can determine you don't use the result.
There was a time many moons ago, when the VAX Fortran compiler (I did say many moons) outperformed its competitors by several orders of magnitude in a given benchmark.
That was for that exact reason. It had determined the results of the loop weren't used so had optimised the entire loop out of existence.

The other thing you might want to watch out for is the measuring tools themselves. When you're talking about durations of 1/10,000th of a second, your results can be swamped by the slightest bit of noise.
There are ways to alleviate these effects such as ensuring the thing you're measuring is substantial (over ten seconds for example), or using statistical methods to smooth out any noise.
But the bottom line is, it may be the measuring methodology causing the results you're seeing.
Comment: @DevSolar, from C++11 1.9: The semantic descriptions in this International Standard define a parameterized nondeterministic abstract
machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained
below.
Comment: I used that phrase because no implementation was specified. Hence it should be considered a question about C++ itself rather than some implementation of it. I'll try clarify.
Comment: "A C++ environment is best thought of as a virtual machine for running C++ code." -- Err, no it is not, because it *is* not...
Comment: Though admittedly I misremembered the quote, so I've changed the answer to use the better phrase "abstract machine".
Comment: I understand the concept of the standard wording. But while it helps *defining* the language, there is nothing "virtual" or "abstract" about a specific implementation. That is why I have a problem with the VM terminology. Next thing we're calling directly executable machine code "bytecode", and the CPU a JIT compiler... ah, forget it. Have a nice day! ;-)
Comment: It is the benchmark I guess. When the execution time hits seconds level, the diff is gone. I need to play with the assembly I guess. BTW -O0 was used so the loop is not optimized by the compiler (at least my compiler), otherwise there wouldn't be the execution time difference. Thanks for the answer!
Comment: Thanks for the effort, and +1 to you.
Answer: #include <limits>

int iTest = 0;
long lMax = std::numeric_limits<long>::max();

void foo1()
{
  iTest = lMax;
}

void foo2()
{
  iTest = (int)lMax;
}

void foo3()
{
  iTest = static_cast<int>(lMax);
}

Compiled with GCC 5 using -O3 yields:
__Z4foo1v:
    movq    _lMax(%rip), %rax
    movl    %eax, _iTest(%rip)
    ret

__Z4foo2v:
    movq    _lMax(%rip), %rax
    movl    %eax, _iTest(%rip)
    ret

__Z4foo3v:
    movq    _lMax(%rip), %rax
    movl    %eax, _iTest(%rip)
    ret

They are all exactly the same.
Since you didn't provide a complete example I can only guess that the difference is due to something you aren't showing us.


How to change labels in the Intersection Matrix in Complex Upset R?

Question: I'm using ComplexUpset in R and I would like to know if changing the labels of the intersection matrix is possible. I attempted using
upset(
themes=upset_modify_themes(
        list(
            'intersections_matrix'=scale_x_discrete("A"="label A", "B"="label B")))

and I got :
Scale for x is already present.
Adding another scale for x, which will replace the existing scale

How can I change the labels. The names of the columns isn't something I could describe in one word.
Answer: Use labeller argument of the ComplexUpset::upset() function:
library(ComplexUpset)
movies = as.data.frame(ggplot2movies::movies)
movies[movies$mpaa == '', 'mpaa'] = NA
movies = na.omit(movies)
genres = colnames(movies)[18:24]

upset(
    movies, genres,
    min_size=200,
    labeller=ggplot2::as_labeller(c(
        'Drama'='DRAMA LABEL',
        'Comedy'='COMEDY LABEL'
    ))
)


checking array value with if statement always returns (output) false (else)

Question: I've following array:
Array
(
    [0] =>  class="amount">€39,00
    [2] =>  class="subscription-details">
    [4] => für
    [5] => 1
    [6] => month
)

I want to check if the sixth element of the value is "month".
I use this code:
print_r($test[6]); //Output month

if($test[6] == 'month'){
    echo 'Alex'; //should output
}else{
    echo 'Ecke'; //will output
}

Why this code will output "Ecke" and not "Alex"?
Edit:
var_dump($test[6]) outputs = string(12)
var_export($test[6]) outputs = 'month'
var_export($test) =

array (
  0 => ' 'class="amount">€39,00',
  2 => ' 'class="subscription-details">',
  4 => 'für',
  5 => '1',
  6 => 'month',
)

Comment: Use var_dump() rather than print_r(), that way you can tell if there are any invisible characters such as spaces in your array values
Comment: I think `var_export` for the entire array might be even better cause this allows to copy/paste the code and make a simple test :)
Comment: yes.. I edit it :p
Comment: Can you do `var_dump($test);`
Comment: The var_export show the issue.. I have to check 'month' and than it works fine.
Comment: It looks like the `` tag has been hidden by the browser and this is why you have missed it. Good luck :)
Answer: It does output Alex. Here is the simplest test case which almost repeats your code as I understand it.
<?php
$test = [
    0 => 'class="amount">€39,00',
    2 => 'class="subscription-details">',
    4 => 'für',
    5 => 1,
    6 => 'month',
];

var_dump($test[6]);
var_export($test[6]);

if (trim(strip_tags($test[6])) == 'month') {
    echo PHP_EOL.'Alex'.PHP_EOL; //should output
} else {
    echo PHP_EOL.'Ecke'.PHP_EOL; //will output
}

When I run the script I get
string(12) "month"
'month'
Alex

Can you please show result of the var_export for your array. Most likely you have leading or trailing spaces in the word month. You might want to trim the string before comparing it with 'month'.
Update: I think you've answered your own question when provided var_dump results. The value in $test[6] is not a month but month
I've updated the test for this and added strip_tags function. This is just for fun and to show that you can easily remove extra tags.
Comment: I edit my question.. Your answer doesn't work for me.
Comment: Thank you for the tip var_export()
Answer: Well, this seems to be a problem...
var_dump($test[6]) outputs = string(12)

month is not 12 characters long. You probably have some non-printable characters in that string apart from month


Copiar texto para a área de transferência usando VueJS?

Question: No retorno de uma requisição está vindo a linha digitável de um boleto e atribuo essa linha digitável à uma variável, porém o que eu quero fazer agora é copiar essa linha digitável à área de transferência, para que o usuário possa colar(ctrl + V) em qualquer outro lugar.
Já achei vários exemplos eu JS puro, porém no projeto em questão está sendo utilizado VueJS e não achei nada que me ajudasse.
Exemplo em JS puro:
var copyTextareaBtn = document.querySelector('.copiar');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.textarea');
  copyTextarea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'sim!' : 'não!';
    alert('Texto copiado? ' + msg);
  } catch (err) {
    alert('Opa, Não conseguimos copiar o texto, é possivel que o seu navegador não tenha suporte, tente usar Crtl+C.');
  }
});

Existe uma maneira de eu utilizar o código acima no VueJS??
Obs.: link original do código do exemplo acima aqui
Answer: Dá para adaptar facilmente para o VueJS

var vue = new Vue({
    el: "#app",
    methods: {
      copy: function() {
        var copyTextarea = this.$refs.copiar

        copyTextarea.select();

        try {
          var successful = document.execCommand('copy');
          var msg = successful ? 'sim!' : 'não!';
          alert('Texto copiado? ' + msg);
        } catch (err) {
          alert('Opa, Não conseguimos copiar o texto, é possivel que o seu navegador não tenha suporte, tente usar Crtl+C.');
        }
      }
    }
})

<textarea class="textarea" ref="copiar">Vamos copiar este texto?</textarea>

<button @click="copy">Copiar</button>

O único detalhe é o uso de do refs para poder acessar o elemento dentro da instância do vue
Comment: Tentei o código que você fez acima, porém está dando erro: `copyTextarea.select() is not a function`, pode ser o Quasar Framework interferindo?? Pois vi que ele adiciona várias `div`'s no HTML...
Comment: Sim, no meu caso coloquei `ref="linhaDigitavel"` tanto no HTML quanto na função
Comment: Está exatamente assim dentro da função
Comment: https://jsfiddle.net/capha10u/
Comment: O problema é que não estou usando somente o Vue, e sim o Quasar, o que altera bastante o HTML do Vue, mas vou dar uma complementada lá...
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/72932/discussion-between-leonardoebert-and-denis-rudnei-de-souza).


I don't get a merge commit with GIT and keep having conflicts

Question: We're having trouble with merging with GIT. We created a feature branch from origin/master and are now trying to update the feature branch with the latest changes from origin/master.
I expect (and want) this merge to result in a merge commit. It doesn't. Why and how can we fix this?
The merge results in a number of conflicts. When all conflicts were fixed, I expected to see a merge commit (commit with two parent commits). No such luck.
I also expected a single commit which contains the conflict resolutions. However, there are a lot of commits added to the history. It looks more like a rebase than a merge. How is this possible?
I want later merges to have a merge base that won't cause conflicts that we've already seen earlier. So we tried to merge again from origin/master, hoping to get an actual merge commit this time. Again no such luck.
We're still getting merge conflicts and after resolving those there is still no merge commit. I fear we have to keep fixing the same issues indefinitely. That's not want I want (I know of rerere). I want the repository to reflect that we did a merge.
How can resolving conflicts from a git merge origin/master end up in multiple commits looking like a rebase result? I feel that if that didn't happen, I would not have further issues.
For the record, our team uses the Gerrit code-review tool. This causes us to have quite a lot of (small) merge commits in our repository as changes are typically not fully rebased when reviewed and merged. I feel this info shouldn't be relevant, but just to be sure.
Comment: Did you add and commit the files with the conflicts after you had resolved the merge commits?
Comment: We used "git mergetool". After resolution, the files were automatically added to the staging area. We did the "git commit" when there were no more changes. We have ui.color set to true. Everything was green before the commit, nothing was red.
Comment: Its not possible for me to visualize what kind of commit -history you have. If you are open to it, can you paste the output of `git log --graph --decorate --pretty=oneline --abbrev-commit` till some commits in your question?
Comment: I can do that but it results in 396 lines (out of a total of 10000). Should I use something like www.wetransfer.com? Or copy/paste in a new answer to this question?
Comment: Yeah, just share it via a service - like pastebin or as a gist and add the link to your question.
Comment: Please take a look at http://pastebin.com/ppszv6rz. As this is a closed source project, I had to remove quite some text but that shouldn't matter for this discussion. I've annotated the branches relate to the merge. Thanks for taking the time.
Answer: Problem found. git merge --squash will always result in a non-merge commit (with only a single parent commit). The reason why we specified this was because if we didn't and we pushed the merge commit to our Gerrit server, we got A LOT of new changes in Gerrit which need manual review and approval. I'm not yet entirely sure why this is not always the case but Gerrit created new reviews for all the commits that were already in the repository but we now added to the branch's history... Colleagues thought that these reviews were actual new commits. That isn't the case. They were the same changesets, but now listed under a new branch.
The problems is now that we require to manually approve every commit that has become part of the merge target branch's history. But that's for a different stackoverflow question. ;-)
Answer: As far as I see the problem
stay in the feature branch. install meld or do the git merging with master branch.
do a
git fetch.

(git merge origin/master) (Think you already completed this).
after fixing conflicts check
git status

if you have changes there then add all the files and do a commit. then push it to the remote.
do a git fetch again
after that try go into master branch and merge master with that feature


Lang Sylow Theorem

Question: STATEMENT: Let $P$ be a $p$-Sylow subgroup of $G$ and H is a $p$-subgroup of G. Suppose first that $H$ is contained in the normalizer of $P$. We prove that $H\subseteq P$. Indeed, $HP$ is then a subgroup of the normalizer, and $P$ is normal in $HP$. But
$$(HP:P)=(H:H\cap P)$$
So if $HP\neq P$, then $HP$ has order a power of p, and the order is larger than $|P|$, contradicting the hypothesis that $P$ is a Sylow group. Hence $HP=P$ and $H\subseteq P$.
QUESTION: How does Lang get to the conclusion that $HP$ must have order a power of $p$ greater than $|P|$?
Comment: its not clear, what is $H$ ?
Comment: $H$ is a $p$-subgroup of $G$.
Answer: If $H$ normalizes $P$, then $HP$ is a subgroup and $|HP|=|H||P|/|H \cap P|$, whence $HP$ is a $p$-group. Since $P \subseteq HP$, $|P| \leq |HP|$.
Answer: if $H$ and $P$ are Sylow subgroups then $H \cap P$ also has order a power of $p$. since the order of $H$ is also a power of $P$ then $(HP:P)=(H:H\cap P)$ is a power of $p$.
Answer: Note that $HP=\{hp|h\in H p\in P\}$ is a subgroup provided $H\subseteq N(P)$. This set clearly has power dividing $|H||P|$.

Lang Sylow Theorem


Find the matrix of a linear map using change of basis

Question: I'm supposed to solve this task using the theory behind change of basis. So, I'm given a linear operator $\varphi :{ R }^{ 3 }\rightarrow { R }^{ 3 }$ that maps
$\begin{pmatrix} 1 \\ 1 \\ 0 \end{pmatrix}\mapsto \begin{pmatrix} 2 \\ 1 \\ -1 \end{pmatrix},\quad \begin{pmatrix} -1 \\ 2 \\ 1 \end{pmatrix}\mapsto \begin{pmatrix} -1 \\ 0 \\ 3 \end{pmatrix},\quad \begin{pmatrix} 0 \\ 1 \\ 1 \end{pmatrix}\mapsto \begin{pmatrix} 1 \\ 1 \\ 2 \end{pmatrix}$.
I'm supposed to find the matrix of this map in the standard basis $f$ that is the set of columns of the identity matrix of $dim=3$
Let $e$ and $e'$ be:
$e=\begin{pmatrix} 1 & -1 & 0 \\ 1 & 2 & 1 \\ 0 & 1 & 1 \end{pmatrix},\quad e'=\begin{pmatrix} 2 & -1 & 1 \\ 1 & 0 & 1 \\ -1 & 3 & 2 \end{pmatrix}$
Then we can find the transition matrix from $e$ to $e'$:
$e'=eS\quad \Rightarrow \quad S={ e }^{ -1 }e'$
Then we can use elementary operation with rows of the augmented matrix to calculate ${ e }^{ -1 }e'$
$\left( { e }|e' \right) \quad \rightarrow \quad \left( { E }|{ e }^{ -1 }e' \right) \quad \rightarrow \quad S$
Well, I don't know what to do next. I was told to recall that the $j$-th column of the matrix $A$ of the operator $\varphi$ in the basis $f$ is the coordinate column of $\varphi({f}_{j})$ in the basis $f$. Here $f$ denotes the standard basis, i.e. ${f}_{1}=(1,0,0)$,  ${f}_{2}=(0,1,0)$ and ${f}_{3}=(0,0,1)$, but I don't see how this is supposed to help me.
Answer: Let $A$ be the map from the standard basis to the standard basis. Let $e,e'$ be the matrices given in the question. Then
we have $e'=A e$, so you want to compute $A=e' e^{-1}$.
Comment: I understand why $A$ is the matrix of $\varphi$, but I'm not sure I really get why $A$ (given by the equation above) is the matrix of $\varphi$ in the standard basis. I would be really glad if you participate on this a little bit. Seems like there is something important about images of linear functions that I completely or partially missed.
Comment: The matrix $e'$ gives $\phi$ in terms of the domain basis $e$. You want the representation of $\phi$ using the standard basis for the domain. So you need a map that takes a point in the standard basis and gives the representation in the $e$ basis.The matrix $e$ maps from the $e$ basis to the standard basis, so the other way around is given by $e^{-1}$. Hence the map is $e' e^{-1}$ (that is, apply $e^{-1}$ to get the representation in the $e$ basis and then use the $e'$ matrix to compute the value of $\phi$). (It is a little confusing.)


Uninstall Amplify CLI with Curl

Question: I have installed Amplify CLI with curl and npm, I which to keep one, so I'm uninstalling curl just because in my personal case npm is easier for me to update, this is the command I used to install it:
curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL

How can I uninstall it? I'm using macOS
Thanks
Answer: You have to clean up manually seems to me which isnt that hard though.
Binary is located in $HOME/.amplify/bin/amplify. Then depending on your shell you can remove the custom path and configuration added by the  installation script.
# Add to $PATH
SOURCE_STR="# Added by Amplify CLI binary installer\nexport PATH=\"\$HOME/.amplify/bin:\$PATH\"\n"
add_to_path () {
  command printf "\n$SOURCE_STR" >> "$1"
  printf "\n$yellow Added the following to $1:\n\n$SOURCE_STR$reset"
}
SHELLTYPE="$(basename "/$SHELL")"
if [[ $SHELLTYPE = "fish" ]]; then
  command fish -c 'set -U fish_user_paths ~/.amplify/bin $fish_user_paths'
  printf "\n$yellow Added ~/.amplify/bin to fish_user_paths universal variable$reset."
elif [[ $SHELLTYPE = "zsh" ]]; then
  SHELL_CONFIG=$HOME/.zshrc
  if [ ! -r $SHELL_CONFIG ] || (! `grep -q '.amplify/bin' $SHELL_CONFIG`); then
    add_to_path $SHELL_CONFIG
  fi
else
  SHELL_CONFIG=$HOME/.bashrc
  if [ ! -r $SHELL_CONFIG ] || (! `grep -q '.amplify/bin' $SHELL_CONFIG`); then
    add_to_path $SHELL_CONFIG
  fi
  SHELL_CONFIG=$HOME/.bash_profile
  if [[ -r $SHELL_CONFIG ]]; then
    if [[ ! $(grep -q '.amplify/bin' $SHELL_CONFIG) ]]; then
      add_to_path $SHELL_CONFIG
    fi
  else
    SHELL_CONFIG=$HOME/.bash_login
    if [[ -r $SHELL_CONFIG ]]; then
      if [[ ! $(grep -q '.amplify/bin' $SHELL_CONFIG) ]]; then
        add_to_path $SHELL_CONFIG
      fi
    else
      SHELL_CONFIG=$HOME/.profile
      if [ ! -r $SHELL_CONFIG ] || (! `grep -q '.amplify/bin' $SHELL_CONFIG`); then
        add_to_path $SHELL_CONFIG
      fi
    fi
  fi
fi

Uninstall Amplify CLI with Curl


Probability of an independent Poisson process overtaking another

Question: I have asked this question before in another fashion on other stackexchanges, so sorry for the somewhat repost.
I have asked my professor and a couple of PhD students about, without a definitive answer. I will first state the problem, then my potential solution and the problem with my solution, so sorry for the wall of text.
The problem:
Assume two independent Poisson processes $M$ and $R$, with $\lambda_R$ and $ \lambda_M$ for the same interval, subject to $\lambda_R>\lambda_M$. What is the probability that at any point in time, as time tends to infinity, that the aggregate output of process $M$ is larger than the aggregate output of process $R$ plus $D$, i.e. $P(M>R+D)$. To illustrate with an example, assume two bridges $R$ and $M$, on average $\lambda_R$ and $\lambda_M$ cars drive over the bridge $R$ and $M$ respectively per interval, and $\lambda_R>\lambda_M$. $D$ cars have already driven over bridge $R$, what is the probability that at any point in time more cars in total have driven over bridge $M$ than $R$.
My way of solving this problem:
First we define two Poisson processes:
$$M(I) \sim \operatorname{Poisson}(\mu_M\cdot I ) \\
R(I) \sim \operatorname{Poisson}(\mu_R\cdot I ) \\$$
The next step is to find a function that describes $P(M>R+D)$ after a given number of intervals $I$. This will happen in case $M(I)>k+D$ conditional on the output of $R(I)=k$, for all non-negative values of $k$. To illustrate, if the aggregate output of $R$ is $X$ then the aggregate output of $M$ needs to be larger than $X+D$. As shown below.
$$P(M(I))>R(I)+D)=\sum_{k=0}^n \bigg [P(M(I) >k+D\cup R(I)=k) \bigg]$$
$$n\rightarrow \infty$$
Due to independence this can be rewritten as the product of the two elements, where the first element is 1-CDF of the Poisson distribution and the second element is the Poisson pmf:
$$P(M(I)>R(I)+D)=\sum_{k=0}^n \bigg [\underbrace{P(M(I)> k+D)}_{1-\text{Poisson CDF}}\cdot \underbrace{P(R(I)=k)}_\text{Poisson pmf} \bigg]$$
$$n\rightarrow \infty$$
To create an example, assume $D=6$, $\lambda_R=0.6$ and $\lambda_M=0.4$, below is the graph of that function over $I$:

The next step is to find the probability of this happening at any point in time, lets call that $Q$. My thought is that this is equivalent to finding 1 minus the probability of $M$ never being above $R+D$. I.e let $N$ approach infinity what is $P(R(N)+D \geq M(N))$ conditional on this also being true for all previous values of $N$.
$P(R(I)+D \geq M(I))$ is the same as $1-P(M(I)>R(I)+D)$, lets define that as function g(I):
$$g(I)=1-P(M(I)>R(I)+D) $$
As $N$ tends to infinity, this can also be rewritten as the geometrical integral over function $g(I)$.
$$Q=1-\exp \bigg (\int_0^N \ln(g(I)) \:  dI \bigg )$$
$$Q=1- \exp \bigg ( \int_0^N \ln(1-P(M(I)>R(I)+D)) \: dI \bigg ) $$
$$N\rightarrow \infty$$
Where we have the function of $P(M(I)>R(I)+D)$ from above.
$$Q=1-\exp \bigg (\int_0^N \ln \bigg (1-\sum_{k=0}^n \bigg [\underbrace{P(M(I)> k+D)}_{1-\text{Poisson CDF}}\cdot \underbrace{P(R(I)=k)}_\text{Poisson pmf} \bigg] \bigg ) \, dI \bigg ) $$
$$N\rightarrow \infty$$
$$n\rightarrow \infty$$
Now to me this should give me the final value of $Q$, for any given $D$, $\lambda_R$ and $\lambda_M$. However, there is a problem, we should be able to rewrite the lambdas as we want as the only thing that should matter is their proportion to each other. To build on the example from before with $D=6$, $\lambda_R=0.6$ and $\lambda_M=0.4$, this is effectively the same as $D=6$, $\lambda_R=0.06$ and $\lambda_M=0.04$, as long as their interval is divided by 10. I.e. 10 cars every 10 minutes is the same as 1 car every minute. However, doing this produces a different result. $D=6$, $\lambda_R=0.6$ and $\lambda_M=0.4$ yields a $Q$ of $0.5856116$ and $D=6$, $\lambda_R=0.06$ and $\lambda_M=0.04$ yields a $Q$ of $0.9998507$. The immediate realization is that $1-(1-0.5856116)^{10}=0.9998507$, and the reason is actually fairly simple if we compare the graphs of the two outcomes, the graph below shows the function for $D=6$, $\lambda_R=0.06$ and $\lambda_M=0.04$.

As can be seen the probability does not change, however it now takes ten times as many intervals to get to the same probability. As $Q$ is dependent on the interval of the function this naturally has an implication. This obviously means that something is wrong, as the result should not depend on my starting lambda, especially because there is no starting lambda that is correct $0.04$ and $0.06$ is as correct as $0.4$ and $0.6$ or $1$ and $1.5$ etc, as long as the interval is scaled accordingly. Therefore, while I can easily scale the probability, i.e. going from $0.4$ and $0.6$ to $0.04$ and $0.06$ is the same as scaling the probability with a factor of 10. This obviously produce the same result, but as all of these lambdas are equally valid starting points, then this is obviously not correct.
To show this impact I graphed $Q$ as a function of $t$, where $t$ is a scaling factor of the lambdas, with starting lambdas of $\lambda_M=0.4$ and $\lambda_R=\lambda_M\cdot 1.5$. The output can be seen in the graph below:

This is where I am stuck, to me the approach looks fine and correct, but the result is obviously wrong. My initial thought is that I am missing a fundamental re-scale somewhere, but I can't for the life of me figure out where.
Thank you for reading, any and all help is greatly appreciated.
Additionally, if anyone wants my R-code please let me know and I will upload it.
Comment: I did some pretty extensive cleanup of your MathJax code. If you take a look you'll see a few things about standard and proper usage. (More work could be done; maybe later.)
Comment: Awesome! Thank you very much, I was unaware of that, is there a specific guide I should follow?
Comment: I edited some extra things in line with what you did.
Comment: @nonein There's a teeny bit in the editing help, but beyond that there's math.SE's [MathJax basic tutorial & quick reference](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference#). Guides on writing mathematics in LaTeX (which are easy to google) often help if you're trying to find something not covered in the quick reference there (though it's now got a pretty comprehensive coverage of MathJax's subset).
Answer: Let the collective times of the processes be $T = (0=t_0 \lt t_1 \lt t_2 \lt \cdots).$  Because these are independent Poisson processes, almost surely exactly one of them is observed at each of these times.  For $i\gt 0,$ define
$$B(i) = \left\{\matrix{+1 & \text{if } R(t_i)=1 \\ -1 & \text{if }M(t_i)=1}\right.$$
and accumulate the $B(i)$ into the process $W:$ that is, $W(0)=0$ and $W(i+1)=W(i)+B(i)$ for all $i \gt 0.$ $W(i)$ counts how many more times $R$ has appeared than $M$ just after time $t_i.$

This figure shows realizations of $R$ (in red) and $M$ (in medium blue) as "rug plots" at the top.  The points plot the values of $(t_i, W(i))$.  Each red point represents an increase in the excess $R(t_i)-M(t_i)$ while each blue point shows a decrease in the excess.
For $b=0, 1, 2, \ldots, $ let $\mathcal{E}_b$ be chance at least one of the $W_i$ is less than or equal to $-b$ and let $f(b)$ be its probability.

The question asks for $f(D+1).$

Let $\lambda=\lambda_R+\lambda_M.$  This is the rate of the combined processes.  $W$ is a Binomial random walk, because
$$\Pr(B(i) = 1) = \frac{\lambda_R}{\lambda}\text{ and } \Pr(B(i)=-1) = \frac{\lambda_M}{\lambda}.$$
Thus,

The answer equals the chance that this Binomial random walk $W$ encounters an absorbing barrier at $-D-1.$

The most elementary way to find this chance observes that
$$f(0)=1$$
because $W(0)=0;$ and, for all $b \gt 0,$ the two possible next steps of $\pm 1$ recursively yield
$$f(b) = \frac{\lambda_R}{\lambda} f(b+1) + \frac{\lambda_M}{\lambda} f(b-1).$$
Assuming $\lambda_R \ge \lambda_M,$ the unique solution for $b\ge 0$ is
$$f(b) = \left(\frac{\lambda_M}{\lambda_R}\right)^b,$$
as you can check by plugging this into the foregoing defining equations.  Thus,

The answer is $$\Pr(\mathcal{E}_{D+1})=f(D+1)=\left(\frac{\lambda_M}{\lambda_R}\right)^{D+1}.$$


Modulos vs Classes em JavaScript

Question: Estou começando a trabalhar com Classes em JavaScript. Mas vejo que algumas pessoas utilizam e recomendam a construção de um projeto separado por módulos. Como eu ainda não possuo experiência em trabalhar nesses formatos, gostaria de saber:
Quais são as vantagens de se trabalhar utilizando módulos e não classes no JavaScript?
Alguma das formas é melhor ou é apenas uma questão de escolha do programador?
Answer: Antes do ES6 introduzir a sintaxe para classes no JavaScript, havia uma grande discussão de qual seria a melhor maneira para simular esse comportamento de linguagens orientada a objetos em JavaScript que é uma linguagem que apesar de ter objetos, usa prototipação e não classes.
Modules pattern que provavelmente é o que você está comparando a classes, é uma forma de iniciar um escopo, para que você possa ter variáveis apenas acessíveis dentro deste escopo e acessar elas pelos métodos da sua instância.
Nos dias de hoje é possível usar a sintaxe de class no ES6, caso a plataforma que você esteja usando não suporte você, pode usar projetos que transpilam seu código como o Babel, para dar suporte a este novo recurso do JavaScript. Por baixo dos panos a class vai criar algo similar ao modules pattern para te dar recursos similares a lingaugens que não fazem uso de protótipos.
Sabendo disso, é escolha do desenvolvedor optar pelo que será compatível com o projeto, ou melhor dará os recursos que se deseja utilizar para o tal.
Comment: Valeu pela dica! ;)
Answer: Módulos e Classes são conceitos diferentes que não são necessariamente alternativos. Ou seja usar Classes não quer dizer que "então não se usa modulos" e vice versa.
O que é um módulo?
É possível através de ferramentas de desenvolvimento e/ou em ambiente Node.js (JavaScript versão servidor) criar módulos. Cada módulo é um ficheiro diferente onde todas as variáveis declaradas ficam restringidas ao escopo desse módulo. Ou seja nada é automaticamente exportado para o espaço global.
Isto é muito útil para criar componentes estanques e que podem facilmente ser modificados, usados noutros projetos e fáceis de ler/perceber o que fazem.
A única porta de contacto com o resto da aplicação é via module.exports em Node.js (nativo e muito usado), ou export em JavaScript do futuro que através das ditas ferramentas como Webpack, Babel, Browserify permitem já hoje usar essa sintaxe.
Quando se usam classes uma das vantagens é também reduzir o numero de variáveis que são exportadas para o escopo global. Esta boa ideia é talvez a única coisa em que módulos e classes têm em comum. De resto é muito comum ter classes declaradas dentro de módulos, uma ou mais.
Um exemplo de uma aplicação React.js:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (

Welcome to React

          To get started, edit src/App.js and save to reload.

    );
  }
}

export default App;

Este módulo exporta uma Classe. E importa classes de outros módulos. A linha import React, { Component } from 'react'; importa exatamente duas classes diferentes de um mesmo módulo. Ou seja esse módulo react é um objeto em que muitas das suas propriedades são Classes que podem ser importadas para outros módulos.
Comment: Valeu pelo esclarecimento! ;)
Comment: @Sergio sua resposta está correta, mas quando comparando Classes com Módulos, normalmente os livros falando de Modules Pattern que é diferente de Modules System (o que você apresentou na resposta). Mas a confusão é comum.
Comment: @GabrielGartz concordo que se pode falar de módulos no contexto de "modulos vs iife vs class". Na resposta abordei mais a questão de que modulos e classes podem coexistir e que não são polos alternativos. Vou dar uma edição mais logo e deixar mais claro. Bom reparo, obrigado!

Modulos vs Classes em JavaScript


Adding a new language to install4j

Question: I use install4j for my application distribution. But I didn't get any information in case when I want add custom language (not from available list). For example ukrainian(UA). Is it possible ?
Answer: You can add a new language like that:

Edit the file resource/messages/languages and add the line
ua=Ukrainian

Add the line
languages.ua=Ukrainian

to the file resource/messages/messages_en.utf8

Copy the file resource/messages/messages_en.utf8 to resource/messages/messages_ua.utf8 and translate all messages.

We are happy to ship and subsequently maintain a new translation if you send it to us.
Comment: Thank you a lot! Of course we will send you UA translation.

Adding a new language to install4j


The associated ring to a Gorenstein Artinian ring

Question: Let $(R,\mathfrak{m},k)$ be a commutative local Noetherian ring. We also assume that $R$ is Gorenstein Artinian. Let $G(R)$ be the associated graded ring $\bigoplus_i\mathfrak{m}^i/\mathfrak{m}^{i+1}$. Is it true that $G(R)$ is also Gorenstein? If yes, do you know how to prove it? If not, do you have a conunterexample?
Comment: Related: https://math.stackexchange.com/questions/2031199/annihilators-of-powers-of-the-maximal-ideal-in-an-artinian-gorenstein-ring
Answer: Consider the ring $R=k[[x,y,z]]/(xy,xz,yz,x^3-y^2,x^3-z^2)$, this is a Gorenstein Artinian ring but its Hilbert series is $1+3t+t^2+t^3$, in particular $G(R)$ cannot be Gorenstein. The problem with Hanno's answer is that even though the end degree of $G(R)$ is one-dimensional, the socle might be bigger. For example in our case the initial form $\bar y\in G(R)$ is a socle element living in degree 1. So the claim I made in my question is false.
Comment: Interesting! My (counter)example proved good for both questions.
Comment: yes, thank you again for that example
Comment: @user113589 Thanks for pointing out that error!