Como iterar sobre um arquivo JSON para aparecer na listagem do Auto Complete?

Question: Estou fazendo um autocomplete, via AJAX, que entra no Web service, "busca no Banco" e me retorna uma String no formato JSON.
Tenho que transformar o JSON abaixo em um lista para iterar sobre ela.
No data.d obtenho a seguinte String:
"[{"IDPais":1,"Pais1":"Brasil","IDIdioma":1}]"

Ao ler o arquivo JSON com a função $.map dá erro no console.
Meu código:
$(function() {
    $("#<%=txtPais.ClientID%>").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: '<%=ResolveUrl("../ws/AutoComplete.asmx/GetListaPais")%>',
                data: "{ 'prefixText': '" + request.term + "','contextKey': '" + $("#<%=rblIdiomas.ClientID%> input:checked").val() + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function(data) {
                    response($.map(data.d, function(item) {
                        return {
                            label: item.Pais1,
                            val: item.IDPais
                        }
                    }))
                },
                error: function(response) {
                    alert(response.responseText);
                },
                failure: function(response) {
                    alert(response.responseText);
                }
            });
        },
        minLength: 1
    });
});

Comment: Ele deve ta lendo uma String, e não um JSON, então tenta fazer isso:

`var jsonObj = JSON.parse(data.d);
$.map(jsonObj, function (item) {.......`
Comment: Faz um alert na função success para ver o resultado.
Comment: @Rogerio Alencar Filho poste seu comentario como resposta, para que eu possa marcalo como correto. Outra forma de fazer em vez de usar Json.parse(data.d) seria var dados = eval(data.d)
Comment: @RogerioAlencarFilho poste sua resposta aqui por favor, pra mim marca-lá como correta.
Answer: Use JSON.parse(data.d) para transformar seu JSON em uma lista de objetos e interar sobre ela com a função $.map. O sucess do ajax deveria ficar assim:
success: function (data) {
    var dados = JSON.parse(data.d);
    response($.map(dados, function (item) {
        return {
            label: item.Pais1,
            val: item.IDPais
        }
    }));
}

Respondi a pergunta pois o amigo @RogerioAlencarFilho deixou ela nos comentários e achei interessante deixá-la aqui.


How to hide "Counter" and "Date" on certain page/node?

Question: How do I hide the "Count content views" of a certain page/node?
I want to hide the numbers of reads along with the date the page was updated without effecting other pages on the site.
Answer: You need to interact with the theming layer (template.php in theme)
As you want to alter an element within a node, you may use function template_preprocess_node(&$variables) to alter, remove or disable that element. You will need to do a conditional test first ($variables['node']->nid) and check $node->nid against the nid of your specific node page. You can then look for the element within $node.
You may also just use Drupal 7 Template (Theme Hook) Suggestions, if the element you wish to hide is a standalone element (ie not embedded in a larger render array), in which case you will copy over the base theme's node template and just comment out/alter the bit in question - for node it is node--[type|nodeid].tpl.php.
When working in the theme layer remember that your theme always has the last say so you can safely make alterations knowing that you cannot cause problems for any other modules or base themes in the process.


Adding SFTP to Windows Server 2012

Question: I need SFTP functionality on my Windows 2012 VPS server.
According to this page, one of the prerequisites is that I'm running at least Windows Server 2019 or Windows 10 (build 1809).
My hosting company says they can migrate everything to Windows Server 2022, but there will be costs and my sites will obviously be down for a little while.

Does anyone know if a SFTP server can be installed on Windows Server 2012?
Does anyone have experience doing this? Any recommendations?
Would this be greatly simplified if I used plain ol' FTP? I don't think our data is particularly sensitive.
Comment: Considered Filezilla Server? It's not integrated, but it works for us and does not seem to need any particular Windows version.
Comment: @tsc_chazz: I can check that out, thanks. Is it very difficult to configure on Windows? I'm actually a developer and not so much an admin guy.
Comment: @tcs_chazz: Looks like the current version says *The 64bit versions of Windows 8.1 and 10 are supported.* So I don't know if Windows 2012 is.
Comment: @JonathanWood Server2012R2 is equal to win8.1. Stuff that works on 8.1 probably works on 2012R2. Anyway, consider upgrading, [win2012R2 is EOL in october next year.](https://learn.microsoft.com/en-us/lifecycle/products/windows-server-2012-r2)
Comment: @JonathanWood yes, Win 8.1 and Server 2012 R2 share a code base, and I've used it on that platform. But vidarlo is correct - it's time and past time to consider an update.
Comment: @vidarlo: Thanks for the info and the link. But that page seems indicates Extended Security Updates extends critical/important support until 2026.
Comment: Are you prepared to pay hundreds of dollars per year for ESU? ESU is not free upgrades. It's a paid service for those who ***can't*** move right now. To be blunt: you are *not* in that situation. Upgrade.
Answer: Q:  SFTP server can be installed on Windows Server 2012?
A: Of COURSE you can! FileZilla is an excellent choice.  So is WinSCP.  The latter also has a great NuGet package for programming SFTP with C#/ASP.NET.  You have many other options as well, both "paid" and "open source".
PS: Please do NOT use FTP.  SFTP is really the most prudent choice, even if you "don't think your data is particularly sensitive...."
Comment: Those are *clients*, not *servers*.
Answer: You definitely can install OpenSSH at Windows 2012 [R2] server and it configures like on any other platform (e.g. Linux) and works as expected.
Comment: As stated in my OP, Microsoft specifically says Windows Server 2019 or later is a prerequisite for installing OpenSSH. I don't know
Comment: I belive Microsoft says about this prerequisites for OpenSSH server included in Windows server 2019 (and Windows 10) as 'Furure on demand'. You can install open ssh server on any previous version of Windows Server from  downloaded installation package anyway...

Adding SFTP to Windows Server 2012


Let $V_1$ be the variance of the estimated mean from a stratified random sample of size $n$ with proportional allocation.

Question: Let $V_1$ be the variance of the estimated mean from a stratified random sample of size $n$ with proportional allocation. Assume that the strata sizes are such that the allocations are all integers.Let $V_2$ be the variance of the estimated mean from a simple random sample of size $n$.
Show that the ratio $\frac{V1}{V2}$ is independent of $n$.
We define the estimator $\bar y_{st}=\sum_{h}w_h \bar{y}_h$, where $w_h=\frac{N_h}{N}$.
We know this is an unbiased estimator of the population mean.
For proportional allocation,
$n_h=nw_h $
$V(\bar y_{st})=V_1=\frac{1}{n}\sum w_h \sigma^2_h$ (If we assume SRSWR is applied to sample from each strata)
Again, $V_2=V(\bar y)=\frac{\sigma^2}{n}$
Now, $\frac{V_1}{V_2}=\sum w_h \frac{\sigma^2_h}{\sigma^2}=\frac{1}{N}-\sum \frac{w_h(\bar Y_h- \bar Y)^2}{\sigma^2}$
Now, how can I proceed from here?
Answer: $V(\bar{y}_{st}) = V(\sum_h w_h \bar{y}_h) = \sum_hV(w_h\bar{y}_h)$ (by independence of the estimates for different strata). For any non-random $a$ and random variable $X$ with finite variance we have $V(aX) = a^2 V(X)$, so $$V_1 = V(\bar{y}_{st}) = \sum_hw_h^2V(\bar{y}_h) = \sum_hw_h^2\sigma_h^2/n_h,$$
because $V(\bar{y}_h) = \sigma_h^2/n_h$.
We also have $V_2 = \sigma^2/n$.
Hence
$$\frac{V_1}{V_2} = \frac{\sum_hw_h^2\sigma_h^2/n_h}{\sigma^2/n}.$$
We have two different formulations for $w_h$: $w_h = n_h/n$ and $w_h = N_h/N$. Using both we have
$$\frac{V_1}{V_2} = \frac{\sum_h(N_h/N)(n_h/n)\sigma_h^2/n_h}{\sigma^2/n} = \frac{\sum_h(N_h/N)\sigma_h^2}{\sigma^2},$$
which does not depend on $n$.
Comment: I have done exactly the same thing. So, is this the correct solution?
Comment: I'm not sure I understand your comment. Are you saying what you wrote in your original question is the same as my solution, or that you have done the same thing yourself since posting your original question? Our solutions differ: in your description of the question you have $V_1 = V(\bar{y}_{st}) = 1/n \sum_h w_h \sigma_h^2$, whereas I have put $V_1 = V(\bar{y}_{st}) = \sum_h w_h^2 \sigma_h^2/n_h$, which is not the same, as an example of where our solutions differ.
Comment: I agree with your statement that $V_1/V_2 = \sum_h w_h \sigma_h^2 / \sigma^2$, and stating that none of the terms in this sum depend on $n$ because $w_h = N_h/N$ and $\sigma_h, \sigma$ are constants finishes the proof.
Comment: Of course @Alex the two expressions of $V(\bar y_{st})$ are same because you did not use $n_h=nw_h$ due to proportional allocation
Comment: Quite right, not sure how I missed that


Variable selection in logistic regression model

Question: I'm working on a logistic regression model, I have 417 independent variables to try, but running a model with all of them is too much (for Rstudio), what would be a good criteria to discard some variables beforehand?
Thanks for your answers! The aim of this work is to develop a predictive model to detect which costumers are more likely to become uncollectible accounts in a utility company.
Comment: What is the purpose of your model ? Prediction or inference ?
Comment: Use LASSO regression (`glmnet` package)
Comment: are you using glmnet and sparse matrices (assuming your data is sparse .. eg categorical data)
Answer: As mentioned by @DemetriPananos, theoretical justification would be the best approach, especially if your goal is inference. That is, with expert knowledge of the actual data generation process, you can look at the causal paths between the variables and from there you can select the variables which are important, which are confounders and which are mediators. A DAG (directed acyclic graph) sometimes known as a causal diagram can be a great aid in this process. I have personally encountered DAGs with as many of 500 variables, which were able to be brought down to less than 20.
Of course, this might not be practical, or feasible in your particular situation.
Other methods you could use are:

Principal Components Analysis. PCA is a mathematical technique which is used for dimension reduction, by generating new uncorrelated variables (components) that are linear combinations of the original (correlated) variables, such that each component in accounts for a decreasing portion of total variance. That is, PCA computes a new set of variables and expresses the data in terms of these new variables. Considered together, the new variables represent the same amount of information as the original variables, in the sense that we can restore the original data set from the transformed one. Total variance remains the same, but is redistributed so that the first component accounts for the maximum possible variance while being orthogonal to the remaining components. The second component accounts for the maximum possible of the remaining variance while also staying orthogonal to the remaining components, and so on. This explanation is deliberately non-technical. PCA is therefore very useful where variables are highly correlated, and by retaining only the first few components, it is possible to reduce the dimension of the dataset considerably. In R, PCA is available using the base prcomp function.
Partial Least Squares. PLS is similar to PCA except that is also takes account of the correlation of each variable with the outcome. When used with a binary (or other categorical) outcome, it is know as PLS-DA (Partial Least Squares Discriminant Analysis). In R you could use the caret package.

It is worth noting that variables should be standardised prior to PCA or PLS, in order to avoid domination by variables that are measured on larger scales. A great example of this is analysing the results of an athletics competition - if the variables are analysed on their original scale then events such as the marathon and 10,000m will dominate the results.

Ridge Regression. Also known as Tikhonov Regularization, this is used to deal with variables that are highly correlated, which is very common in high dimension datasets. In ordinary least squares, where the sum of squared residuals is minimised, ridge regression adds a penalty, so that we minimize a quantity which is the sum of the squared residuals, plus a term usually proportional to the sum (or often a weighted sum) of the squared parameters. Essentially, we "penalize" large values of the parameters in the quantity we seeking to minimize. What this means in practice is that the regression estimates are shrunk towards zero. Thus they are no longer unbiased estimates, but they suffer from considerably less variance than would be the case with OLS. The regularization parameter (the penalty) is often chosen by cross validation, however, the cross validation estimator has a finite variance, which can be very large and can lead to overfitting.
LASSO regression. Least Absolute Shrinkage and Selection Operator (LASSO) is very similar to ridge regression - it is also a regularization method. The main difference is that, where ridge regression adds a penalty that is proportional to the squared parameters (also called L2-norm), the LASSO uses the absolute value (L1-norm). This means that Lasso shrinks the less important variables' coefficients to zero, thus removing some variables altogether, so this works particularly well for variable election where we have a large number of variables. As previously mentioned, regularization introduces bias with the benefit of lower variance. There are also methods to reduce or eliminate this bias, called debiasing.
Elastic net. This is a compromise between ridge regression and LASSO and produces a model that is penalized with both the L1-norm and L2-norm. This means that some coefficients are shrunk (as in ridge regression) and some are set to zero (as in LASSO). In R I would suggest the glmnet package which can do ridge regression, LASSO and elastic net.
Comment: @Acccumulation Re: your second point - indeed, I was thinking about that while writing it but then it slipped my mind - thanks !I will update. Re: Your first point, this is an area of active research that I am proud to be part of in my day job. Certainly it is very important for intervention and inference in general. There is some emerging evidence that it is also important for prediction in some circumstances. As far as this question in concerned, we don't actually know if the OP's goal is prediction or not.
Comment: These will help with overfitting but I don't think ridge regression or other similar tehniques will help you with rulinging out some irrelevant variables explicitly. Maybe the OP would like to have just 10 or 100 dimensions to the model. Well PCA is great at this.
Comment: Distinguishing between confounders and actual causes is important for intervention, but I'm not clear on how it's important for prediction. Also, might want to mention that PCA and similar methods are sensitive to scaling, so features are often normalized before applying PCA.
Answer: Theoretical justification beyond all else.  Aside from that, LASSO or similar penalized methods would be my next suggestion.
Answer: Sounds like regularization models could be of use to you (Lasso especially, since your problem seems to be centered around picking variables, as opposed to Ridge and Elastic net).
However, these can be difficult to set up. They are included in Stata 15 if you have access to that. In R, it's often a bit more handywork but hopefully someone can chime in with whether and how R supports users with regularization techniques.
There are other techniques to manually pick and choose variables based on their behaviors, but with over 400 variables (assuming your have no preconceived hypothesis about any of these), I'd say doing the work to understand regularization models is probably easier than manual selection.
Comment: In R use the `glmnet` package.


$\chi^2$ test and sparsely populated bins

Question: Which article should I reference as a source of the following claim?:
The $\chi^2$ test is not recommended when too many sparsely populated bins exist in a given histogram.
Please rephrase the above sentence if it is not clear.
This article (page 328) by W. Cochran states something along that lines, but it's pretty old (1952) and it's not at all conclusive.
Answer: The recommendation that all the expected values meet or exceed 5 for a chi-squared test is very old and very well-known.  You may not have to substantiate it with a citation.  It is also somewhat arbitrary, and this is also pretty well known.  There won't be a 'bright line' anywhere separating conditions under which the test works just fine vs. breaks down--there can't be.  Again, any research statistician will know this or immediately intuit it.  As a result, I doubt there will be much research substantiating the 5 rule of thumb.  If you wanted to cite something anyway, the Cochran paper may be sufficient.
If you want to pursue this for your own edification, you may want to read Campbell (2007) and the various papers that cite it.  This is not quite the same context as yours, but the underlying issue is the same.
Comment: Gaba_p you can see it yourself using the LOOK INSIDE feature on Amazon, jbowman's link will take you there. It's on p.425 as he says. It merely states "As a rule of thumb, $n$ should be large enough so that the expected frequency of each cell is at least 5". It does not cite a paper to substantiate this there or anywhere else that I see. Similar statements of the rule of thumb exist in most intro texts as Macro notes. You could simply cite that book, I think that is what he meant, not that you should buy it.
Comment: Statistical Concepts and Methods, Bhattacharya and Johnson, p. 425.  On Amazon for $171.50 despite the 1977 publication date!!! http://www.amazon.com/Statistical-Concepts-Methods-Probability-Statistics/dp/0471072044#reader_0471072044
Comment: Right, I was just expressing surprise about the price.  LOOK INSIDE will take you there.  If you can't get there for some reason, and really want to see the page for yourself (quite reasonable if you're going to cite it!) I'll post a screenshot of the top half of the page, where the quote that @gung cites is.
Comment: +1. If one wants a citation for this, it would probably be found most readily in a introductory textbook intended for non-statisticians.
Comment: I think Macro is right.  The rule is probably mentioned in many introductory books.  You might also look at van Belle's "Statistical Rules of Thumb" book.  I know I have seen it many times and I think it goes back to results of Cochran from before the 1952 survey paper that was found.  I don't know if Cochran made the recommendation directly or someone else did based on his results.  But this may be difficult to track down.  Books on the history of statistics might say something about this and statistics encyclopedias under the chj square test item or even in a biography of Cochran.
Comment: @jbowman could you put your comment in the form of an answer and if you can, copy/paste the lines(s) in that book that address the issue? I don't have access to that book and I can't pay $172 for one single reference. Thanks!
Comment: I did try the _Look Inside_ feature but it will only let me see up to page 6, after that it jumps to the index (this might be due to the fact that I'm accessing from outside the US) A screenshot would be great @jbowman, the quote by gung is fine but I'd really like to see the text if it's not too much trouble for you.
Comment: Try looking at the table of contents, then scroll down to the entry for page 424, click on it, and that should take you to the page before; then you can scroll to page 425.  I don't know about outside the U.S., though, so I'll post the screenshot too.
Comment: Nope, if I do that it takes me to the end of the book.
Answer: Here's a screen capture of the first half of the relevant page from Bhattacharya and Johnson, Statistical Concepts and Methods, in response to a request in comments to @gung's answer:


Is there a way to verify that UI element is located in a certain part of the screen in Playwright?

Question: I am new to Playwright and just recently started trying to implement tests with it.
My question is, is there a way to test that some web element is in certain location on the web page? For example, if I have an .svg logo on my web page, would I be able to test that it appears on the top left part of the screen with playright? Would I be able to test that the a certain button is located at the right bottom of a certain web container?
I couldn't find any examples online with regards to those specifics. I am using TypeScript for my tests.
Comment: Yes, you can. Refer to this : https://playwright.dev/docs/other-locators#css-matching-elements-based-on-layout
Answer: Playwright has visual comparison testing which you might want to look into.  It checks how the page being tested looks compared to a golden file (the correct expected output).  It tests visual elements.  Here is the example from the Playwright docs:
import { test, expect } from '@playwright/test';

test('example test', async ({ page }) => {
  await page.goto('https://playwright.dev');
  await expect(page).toHaveScreenshot();
});

You can see more about how this works in the Playwright docs or on this tutorial about visual regression testing which I found helpful.


Can't get drush to work after moving to Acquia Dev Desktop

Question: I installed Acquia Dev Desktop. Most things work but drush does not. I get an error:
Drush was not able to start (bootstrap) the Drupal database.
Because I had previously installed php and mysql on my local, I removed those old versions and adjusted my ~/.bash_profile to ensure I was loading the Acquia Dev Desktop version of php, mysql, and drush. To test, I run "which php", "which mysql", and "which drush" all of which returned the Acquia Dev Desktop version.
To test mysql, from my drupal site directory I entered the mysql cli with "mysql". I ran "show databases" and confirmed the Acquia Dev Desktop Database is in this Mysql server.
To test the php, from my drupal site directory I ran "php -r 'phpinfo();'". I confirmed the PHP version/config loaded is the Acquia Dev Desktop version.
I see in drush looks for aliases in ~/.acquia/DevDesktop/Drush/Aliases/aliases.drushrc.php
I inspected that file and see the alias configured as loc.mysite.dev. I tried my drush commands using that alias. "drush @loc.mysite.dev status". This made no difference.
My drupal install is setup like a multisite. Maybe that is an issue though I always use multisite and have no issue with this same site and drush in a vagrant box (not using Acquia Dev Desktop). I am running my drush commands from my site directory (sites/mysite.org) which is where my settings file is (sites/mysite.org/settings.php).
Here are some drush debug outputs
This is the issue after installing Acquia Dev Desktop https://gist.github.com/maestrojed/78ff27cfae1f65821ce8
This is the issue after installing Acquia Dev Desktop AND my attempts to get drush to use the correct Acquia Dev Desktop versions of Drush and PHP. https://gist.github.com/maestrojed/45c1635f5d1d88d4bd9e
I have to use Acquia Dev Desktop and I don't think I can live without drush. I am happy to provide any other info to help debug. Any tips are greatly appreciated! Thanks.
- See more at: https://forums.acquia.com/acquia-products-and-services/dev-desktop/cant-get-drush-work#sthash.bZJBgcc0.dpuf
Answer: Use the console coming with ADD - launch the console from the ADD client. Using that console everything is correct setup. You might of course get everything to work inside your "Bash" (which it think you are using since you talk about the "which" command), but it kind of removes the whole point of using ADD - that everything is working out the box.
PS! I use Git Bash for my Git work and the ADD (cmd) console for Drush work. Then I don't have to think ;-)
Comment: "Use the console coming with ADD - launch the console from the ADD client. Using that console everything is correct setup"  That was not my experience. I installed ADD, I launched Terminal from the little icon in ADD. Drush did not work. My first debug link shows the output after a fresh ADD install and launching console from ADD.
Comment: Hm, for some reason I missed your reply/comment. I know it's an old question now, but I though I should explain why it didn't work for you: You weren't using the Drush coming with ADD. Probably you had Drush installed before and it was earlier in the path than the Drush coming with ADD. I can says this because your debug output says "Drush version : 6.5.0". Already in 2014 ADD switched to Drush 7 ...
Answer: When using Acquia and Acquia Dev Desktop the settings.php is autogenerated by Acquia. If you review that settings.php file you will noticed there are no databases credentials but instead an Acquia config file is included within a conidtional. That conditional and file are:
// <DDSETTINGS>
// Please don't edit anything between <DDSETTINGS> tags.
// This section is autogenerated by Acquia Dev Desktop.
if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) && file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/cld_devcloud_mysite_dev_mysite_org.inc')) {
  require $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/cld_devcloud_mysite_dev_mysite_org.inc';
}
// </DDSETTINGS>

This included file contains the database connection info. It seems that Drush doesn't include this file. I assume because when run by drush the conditional is not satisfied.
I added my own additional include to the bottom of settings.php to include a local file if it exists.
/**
 * Include a local settings file if it exists.
 */
$local_settings = dirname(__FILE__) . '/local.settings.php';
if (file_exists($local_settings)) {
  include $local_settings;
}

I added the exact same content from the cld_devcloud_mysite_dev_mysite_org.inc file into this local.settings.php file.
Now drush works. My conditional is satisfied. Site continues to run fine locally in Acquia Dev Desktop.
Seems drush should load those Acquia includes and it must for most people as I didn't find many others with this issue. Not sure why my setup acted differently.
maestrojed
Answer: Maestrojed's own answer identifies the settings file, and hansfn has already pointed out you may need to launch the terminal session via DevDesktop itself.
Other things you can do:

First, check drush status (which'll show if it has the correct db name)
Run drush commands with the --verbose switch, which'll show bootstrap status (but beware the bootstrap debug messages can be misleading)
Try using Drush to launch a MySQL console – drush sqlc
if you're using a Drupal 8 composer setup (recommended), install the latest version of Drush with composer, rather than relying on the version that comes with DevDesktop (run composer require drush/drush).  One odd situation I had was the drush updb command connecting to a different database to everything else (I found this out by adding the --verbose option), and upgrading fixed that.
beware of a ~/.my.cnf file forcing the wrong username
Answer: Drush is not picking up the acquia site settings.
Add the acquia settings to your .bash_profile or path so drush can access them.
export DEVDESKTOP_DRUPAL_SETTINGS_DIR="$HOME/.acquia/DevDesktop/DrupalSettings"


Como usar multithreading com requests?

Question: Olá, estou desenvolvendo um checker de disponibilidade de troca de nomes pra um jogo, mas ele é muito lento, lí sobre o módulo multithreading mas achei confuso de usar, não faço a mínima ideia de como impletamenta-lo no meu código, alguem pode me mostrar o caminho?
Aqui meu código
import faster_than_requests as requests
from bs4 import BeautifulSoup

available_summoners = []
summonertxt = [line.rstrip('\n') for line in open("names.txt", 'r')]

for summoner in summonertxt:
    url = 'http://www.lolnames.gg/pt/br/'+summoner
    request = requests.get2str(url)
    html = BeautifulSoup(request,"lxml")
    if 'card bg-success text-white' in request:
        print(summoner +' Disponivel!')
    else:
        print(summoner +' Não Disponivel')

Comment: a pagina ao acessar a url http://www.lolnames.gg/pt/br/  retorna Bad Request (400), esse txt é compos extras ou tentativa de dar resposta 200 ?
Comment: https://pt.stackoverflow.com/a/541236/112052
Answer: Para realizar essa tarefa você pode criar um objeto de Thread utilizando o módulo threading.
Para criar uma Thread, você deve passar a função a ser chamada no parâmetro target e depois você pode passar os argumentos dessa função no parâmtro args dentro de uma tupla ou lista.
Após ter criado o objeto, execute a thread com o método start. Veja o exemplo abaixo:
def func(url):
    print("Obtendo a resposta de", url)

Thread(target = func, args = ("<sua_url>", )).start()

Agora que já sabe como criar uma Thread e executá-la, basta colocar o seu código dentro de uma função para ser executada numa Thread. Veja abaixo como seu código pode ficar:
from threading import Thread
import faster_than_requests as requests

def validate_summoner(url):

    request = requests.get2str(url)

    if 'card bg-success text-white' in request:
        print(summoner + ' Disponivel!')
    else:
        print(summoner + ' Não Disponivel')

available_summoners = []
summonertxt = [line.rstrip('\n') for line in open("names.txt")]

for summoner in summonertxt:
    url = 'http://www.lolnames.gg/pt/br/' + summoner
    Thread(target = validate_summoner, args = (url, )).start()

Comment: Continua lento, de que forma posso aumentar o numero de threads no meu código?
Comment: Talvez essa lentidão seja por culpa do servidor, então quanto a isto não dá para fazer nada se você não for o dono do servidor. E não tem como criar novas threads nesse caso, porque cada thread é responsável por uma requisição na url com um `summoner`. Logo, o número de threads criadas aí no código é o número de summoners que você possui na lista `summonertxt`.

Como usar multithreading com requests?


How to call an image with local path from JSON in JS?

Question: I have a JSON on say www.website.com/cardata that contains the image as following:
"image": "data/models/peugeot-2008-138twf_600X400_.jpg

When calling the image within the code how do I specify that this image is in fact something like:
website.com/data/models/peugeot-2008-138twf_600X400_.jpg?

Thanks
Comment: You should prefix your image with a `/` otherwise it won't always work. For example it would work on `x.html` but not `y/z.html` due to the fact that you are telling it to look in the current directory.
Answer: Just add it in front of the string: (If I got you right)
yourImageElement.src = 'website.com/' + jsonObject.image


Form Ajax submission: erratic behavior

Question: I'm experiencing a weird behavior with an ajax form submit that I cannot find an answer to.
This is my first attempt at making an ajax form so bear with me if I'm making a rookie mistake somewhere.
namespace Drupal\MYMODULE\Forms;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

class InputForm extends FormBase {

  public function getFormID() {
    return 'authForm';
  }
  /**
   * Implements \Drupal\Core\Form\FormInterface::buildForm().
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#prefix'] = '

';

    $form['key'] = array(
        '#type' => 'textfield',
        '#title' => t('Key'),
        '#size' => 10,
        '#name' => 'key',
        '#required' => TRUE,
        '#attributes' => ['id'=>'key','name'=>'key','class'=>array('input-sm')]
    );

    $form['code'] = array(
        '#type' => 'textfield',
        '#title' => t('code'),
        '#name' => 'code',
        '#required' => TRUE,
        '#attributes' => ['id'=>'code','name'=>'code','class'=>array('input-sm')]
    );

    $form['form_submit'] = array(
        '#type' => 'submit',
        '#value' => t('submit'),
        '#name' => 'submit',
        '#ajax' => [
            'callback' => '::test',
            'prevent' => 'submit',
            'progress' => []
        ]
    );
    return $form;
  }
  public function validateForm(array &$form, FormStateInterface $form_state) {

      if (strlen($form_state->getValue('key')) < 10) {
        $form_state->setErrorByName('key', $this->t('Key is too short'));
      }

  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Handle submitted form data.
  }

  public function test(array &$form, FormStateInterface $form_state) {
    if($form_state->hasAnyErrors()) {
        $form_state->setRebuild(TRUE);

        return($form);
    }

    $response = new AjaxResponse();
    $response->addCommand(
        new HtmlCommand(
            '#testdiv',
            '
HELLO
'
        )
    );
    return $response;

  }

}

So the erratic behavior is in the validation of the form. What is happening is when I click the submit button (with no values in the input fields) the ajax fires and through var dumping I know the $form_state->hasAnyErrors() returns true but the form rebuild that is returned is not modifying the form highlighting the fields with errors as expected.
So after spending a couple hours trying to sort out this issue I got frustrated and mashed the submit button over and over again in a rage and low and behold it did what it's supposed to do after about eight clicks.
So then I tried to narrow down how many times it would take hitting the button before it would work correctly and it would always happen at random clicks. Sometimes after 2, sometimes after 3... sometimes after 10.
I'm stumped as to why it doesn't happen each and every single time the button is clicked rebuilding the form properly with errors.
Of Note:

Have tried removing the prevent key
Have tried with Bartik theme with same results
Have tried setting an ID on the submit button but then ajax doesn't fire
Have confirmed that the form does have errors
Have input values into the fields (key value shorter than 10) and the same
behavior happens in the validateForm() function

If anyone could point me to what I could be doing wrong I'd very much appreciate it. Thanks in advance!
Edit for visual example:
Gif showing behavior
Answer: What you can see in the Gif looks more like the validation of the form in javascript not in ajax.
Normally you decide in the submit button by including the option 'wrapper' => 'ajax-wrapper-id', if you want to use the wrapper method and return in the ajax callback the new version of the form or parts of it, or use the response method and build an ajax response in the callback. Doubt that you can mix it like this.
If you use the wrapper method you don't need to rebuild the form, because it is already rebuilt, when it reaches the ajax callback.
Comment: I appreciate the comment but I'm a bit confused.

wrapper: The HTML 'id' attribute of the area where the content returned by the callback should be placed. Note that callbacks have a choice of returning content or JavaScript commands; 'wrapper' is used for content returns.
Comment: Gah... wrong button pushed.

So the form should not pass validation at all given the two fields are required. If I use the wrapper (a div above the form) where the 'content' gets returned does the form then get placed into that div when it fails validation?

I assumed the form wouldn't even post to the ajax since the fields were empty but it does and seems like it must make that ajax call before I can send it back with errors which seems awkward.
Comment: Yes, the required fields are checked in javascript. If you want to get started with ajax, use the wrapper option in the submit button, put the complete form in a div container `$form['#prefix'] = '';` and `$form['#suffix'] = '';` and return in the ajax callback the complete form `return $form;`. That's all you have to do and works for 90 % of all use cases.
Comment: The required fields are the issue. The client side validation (is the field empty? is so, highlight field and stop all else) is the problem I'm trying to solve. The fields are required and SHOULD highlight and show the tooltip EVERY time the submit button is clicked... but it doesn't. If I remove the #ajax from the submit, it works as expected, but with ajax submit enabled, this functionality becomes erratic. It also seems this is not something new either http://drupal.stackexchange.com/questions/184700/how-can-i-enable-javascript-form-validation-for-ajax-submit-buttons
Comment: Yes, this seems obvious. You have to control, what the click triggers, an ajax request or the client side validation.
Answer: HTML 5 Validation
THIS is the validation that is showing up in the gif. For whatever reason, when doing the ajax call it (HTML5 Validation) would sometimes fire and sometimes not.
My personal solution: Disable HTML5 clientside validation and handle that myself.
$form['#attributes']['novalidate'] = 'novalidate';

Hopefully this helps some future reader.

Form Ajax submission: erratic behavior


Preparing multiple "series data" for machine learning

Question: I think I can explain this best with an example.
I have a data set of strings such as: ATGGTCCCGTAATGCTGTGCCGA
And I have multiple "series data" for each of these strings, where a value is given for each character in the string, such as:
Series data1: 1, 3, 3, 5, 1, 2, 3, 1, 4, 2, 3, 5, 1, 2, 3, 5, 1, 5, 4, 1, 4, 4, 1
Series data2: 0.2, -1, -1, -1, 0, 0.3, 0.4, 0.5, 0.1, 0, 0, -1,-4, -3, -2, -1, 0, 0, -1, -3, 0.2, 0.1, 0.5
(I currently only have two series but I will probably add 2 or 3 more "series data"s in a later stage which I would like to compare.)
Which looks like this when plotted (POSITION means position in the string):

My question is: What methods are there of analyzing/transforming the series data, so that I can append that information as a feature of the string, in such a way that a machine learner can recognize patterns within and between the "series data"?
Of course I can make a data set that looks like this:

string  |   Series 1        |   Series 2
ATGGT.. |   1, 3, 3, 5, ..  |   0.2, -1, -1, -1, ...
TTGTA.. |   1, 2, 5, 2, ..  |   0, 0.3, 0.5 , 0.1, ...
etc..

But I doubt a machine learner will be able to make sense of this.
I'm currently thinking of counting peaks/valleys in the data using certain thresholds and perhaps counting correlating peaks/valleys between series (also using some kind of threshold), for example

string  |   Series1_peaks   |   Series2_peaks   |   Series1_2_peaks
ATGGT.. |   7               |   4               |   2
TTGTA.. |   3               |   2               |   0
etc..

I think a typical machine learner would be able to make much more use of this.
However, I'm wondering if there are different approaches to this problem that I hadn't thought about yet. Perhaps specific algorithms already exists to analyze such series data?
Some details on the data:
The strings are actually small DNA sequences. The length can differ greatly, ranging from a few hundred to a few thousand characters.
Note: I added the time-series tag because I thought certain algorithms used in that field might be applicable here. I don't have experience with time-series analysis though.
Comment: Is series data real valued?
Comment: The series data is obtained by calculations done on the chemical properties/interactions of the molecule, or for instance derived by checking the ordering/abundance of the characters. I suppose this would make the values nominal instead of real (since they aren't "physically measured" but obtained using computer models)?
Answer: Since your data is nominal, your choice of line plot to describe your data can be misleading. Distances between and within your series should not be interpreted as a metric for similarity.
You can then treat this as a sentence in a new language and as a result, you can try and analyse it using existing work in text mining for finding patterns of interest.
n-grams could be useful.


Melodic line for voice soloist with divisi. Why?

Question: In Schubert's "Nachthelle", for tenor solo and male chorus, there is a section in the soloist's melodic line that have, apparently, divisi (upper melodic line, in the photo). Why? Is of soloist's choice to sing one way or another? Below is a shapshot of that section. Thanks.
P.S. Please someone creates "divisi" tag.

Edited: here is the link of the original file (public domain), in the IMSLP: link here
Comment: I checked the link. The PDF it leads to is no help. It seems to be taken from a book--I wonder whether the beginning or ending of that book has an explanation for those extra notes.
Comment: No less a piece than Beethoven's Ninth has such an _ossia_ right at its most dramatic moment, where the Baritone Soloist comes in with "O Freu - - nde, nicht die - se Töne!" You can find it on page 12 of [this on-line score](http://www.free-scores.com/PDFSUP/beethoven-ludwig-van-symphony-d-minor-125-presto-1220.pdf). I think that nowadays no singer would be foolhardy enough to choose the lower voice...
Answer: I wouldn't call it divisi unless two instruments were playing it. Without seeing more of the piece, my first guess is that you're right and the lower pitch version is for singers that don't feel comfortable with the high Bb.
Another possibility is only if this section is repeated. It's possible that the singer is supposed to sing it one way the first time and the other way on the repeat.
A third possibility is that versions of the score are inconsistent at this part, and the editor decided to notate both versions for editorial completeness (this is especially likely if it's a critical edition).
In any of these cases though, I would usually expect a bit more explanation, such as, in the first possibility, the word "ossia."  As written, it's definitely more mysterious than it needs to be. I'd look around and see if there's an editorial explanation in the preface, or an explanatory footnote, or something like that.
Comment: In this context it's definitely an *ossia* to avoid an extreme high, since the Bb is out of reach of many male voices who might be called upon to perform this piece. But I agree that it should be notated much more explicitly. As it is we don't even know whether this is editoral discretion or originally allowed by Schubert.


Magento forget Password soap API

Question: everyone I am new here.
 I stuck with Magento API.I am creating Magento API for my e-commerece site.I have created all API but for forget password API I am not getting any solution. I have used default forget password controller but it didn't send me an email with change password link check my code and please help me to set this forget password API.I have also search all the documents but getting any answer. I have also post my code so please refer it and let me know that where is I have mistake.

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$email = $_REQUEST['email'];
require_once ('../app/Mage.php');
Mage::app();
$customer = Mage::getModel('customer/customer')
            ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
            ->loadByEmail($email);
//print_r($customer);

if ($customer->getId()) {
            try {
                $newResetPasswordLinkToken =  Mage::helper('customer')->generateResetPasswordLinkToken();
                $customer->changeResetPasswordLinkToken($newResetPasswordLinkToken);
                $customer->setStoreId(Mage::app()->getStore()->getId());
                $customer->sendPasswordResetConfirmationEmail();
    $response['response'] = "success";
      $response['message']="Password Reset Link Has Been Sent to Your Email Please Check, Your Mail Box!";
      echo json_encode($response);

            } catch (Exception $exception) {
                Mage::log($exception);
            }
        }else{
      $response['response'] = "failed";
      $response['message']="Please Enter a Valid Email!";
      echo json_encode($response);
  }
?>
Answer: Recently i worked on forget password magento api it work fine but only difficult i find that i have to save my forget password file name to index.php. make one api folder and save it with name of index.php
 <?php

if(!empty($_REQUEST['email']))

{
$yourCustomerEmail=$postcode = $_REQUEST['email'];
$customer = Mage::getModel('customer/customer')
        ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
        ->loadByEmail($yourCustomerEmail);
//echo $customer->getId();
        if ($customer->getId()) {

        try {
            $newResetPasswordLinkToken =  Mage::helper('customer')->generateResetPasswordLinkToken();
            $customer->changeResetPasswordLinkToken($newResetPasswordLinkToken);
            $customer->sendPasswordResetConfirmationEmail();
$result = array('action'=> 'send','statuscode'=> '200');
             echo json_encode($result);
            } catch (Exception $exception) {
//echo "Exception";
                Mage::log($exception);
        }
    }
    else
    {
$result = array('action'=> 'failed','statuscode'=> '300');
echo json_encode($result);
    }

}
else
{
$result = array('action'=> 'failed','statuscode'=> '300');
echo json_encode($result);
}
        ?>

Magento forget Password soap API


Moving DC from physical to virtual

Question: Thanks for taking the time to read this.
I am looking for your opinion or advice on the subject.
We have a physical server that is our DC, running AD, DNS, DHCP, and is also the file server. The file server alone takes up 1TB of space. This server is running Server 2008R2, so after the conversion it would need to be upgraded to 2012R2 and then 2016/2019.
I am looking to move this to virtual, and wondering the best process. Does it make more sense to try and convert this using the VMWare converting tool and upgrading the OS afterwards? OR do I just spin up a new VM running Server 2016/2019 and start from scratch?
Concerns: If I convert the server using the tool, I'm afraid it will take up a ton of space, which I might not have enough free space to even do this, and I'm concerned about how long the conversion will take. During this process if someone saves files or modifies files on the server, they will not be in the VM, right?
If I spin up a new server, I'd have to copy everything over, but I'm concerned about getting the new server ready and prepared without conflicting with the old one. Things like DHCP, and AD. I would need the new server to be the same server name and same IP as the old server so that my devices know where to check in for DNS, DHCP, AD etc.
What advice opinions does the community have on the best way to do this.
Thank you in advanced!!
Comment: Tools like that should not be  used on a domain controller. A far better option would be to setup a new domain controller on the virtual server guest, and demote the domain controller on the existing 2008 R2 server.
Answer: If you still have 2008R2, the hardware might be rather old, too, and possibly not ideal for virtualization. If there's any chance to get a new server, I'd recommend installing a new Windows Server 2016/2019 as the Hyper-V host.
The problem with both converting and upgrading an existing DC is that if anything goes wrong, you might end up loosing your entire domain. It's much safer to install a clean VM, join it do the domain, make it a second DC, let it synchronize, and move the FSMO roles.
After that, you can decide whether to retire the old server or upgrade it to be a backup DC. It's recommended to have at least two domain controllers, and having them on separate hardware minimazes the risk of both going down at the same time.
Comment: Thank you! We actually did buy a new server to move the DC to and virtualize, as we needed another server for another project, so I tried to kill 2 birds with one stone and buy a nice beefy host to support both the new server and migrating the DC. In addition, I can promote the new DC to be the main DC and have the old one retire or be a backup? If so, all devices running DHCP would update to receive the new primary DC, but anything set static would need a manual update to get the new DNS servers, right?
Answer:
I would need the new server to be the same server name and same IP as
  the old server so that my devices know where to check in for DNS,
  DHCP, AD etc.

Not required. You can deploy another AD DS + DHCP + DNS host with a new name and new IP. Reduces the chance of conflicts and makes the revert plan easier.

All DCs are in a group and in DNS.
DHCP responds to broadcasts, IP is less important. Because it is broadcast, only run one at a time; shut down old DHCP before starting new.
DNS server IP could be tricky. Run both while advertising the new one with domain policy, DHCP options, and reconfiguring static hosts.

Demote old server when the new one is working.

The ease of adding a new DC makes P2V style conversion plus upgrade unnecessary. New installs are safer and cleaner.
Comment: or keep the old running until you got a snother dc, its almost a good Thing to have atleast two dc

Moving DC from physical to virtual


Assumptions on domain of a meromorphic function

Question: I'm studying complex analysis from Ash's book:
The argument principle for meromorphic stated here is:

4.2.6 Definition
For $f$ meromorphic on $\Omega$, let $Z(f)$ denote the set of zeros of $f$, and $P(f)$ the set of poles of $f$. If $z\in Z(f)\cup P(f)$, let $m(f,z)$ be the order of the zero or pole of $f$ at $z$.
4.2.7 Argument Principle for Meromorphic Functions
Suppose $f$ is meromorphic on $\Omega$. Then for any closed path (or cycle) $\gamma$ in $\Omega \backslash(Z(f)\cup P(f))$ such that $\gamma$ is $\Omega$-homologous to $0$, we have $$n(f\circ \gamma, 0) = \sum_{z\in Z(f)}n(\gamma,z)m(f,z) - \sum_{z\in P(f)}n(\gamma, z)m(f,z).$$

How do I know the sum on $Z(f)$ is well defined? Must that set be countable? Is $\Omega$ always defined to be connected for a meromorphic function?
Answer: If $[a,b]$ is the domain of $\gamma$, then the set$$\left\{z\in\mathbb{C}\,|\,n(\gamma,z)\neq0\right\}\cup\gamma\bigl([a,b]\bigr)$$is compact. Therefore, by the identity theorem, you can have $n(\gamma,z)\neq0$ for finitely many zeros of $f$ only.
Answer: Let $\Omega$ be a bounded subset of $\Bbb{C}$: then by Bolzano-Weierstrass, an infinite number of zeroes would imply that $f$ vanishes everywhere, and thus you couldn't even define $\gamma$, which exists by hypothesis, hence the contradiction. Thus the concerned sum is actually finite.
On the other hand, if $\Omega$ is not bounded, $Z(f)$ could be infinite but then the subset on which the winding number is not zero would again be finite by the same compactness argument (remember a simple closed curve cuts two region, one of which is unbounded and formed by the points on which $n(\gamma, z)=0$).


Flutter and ReceivePort: Bad state: Stream has already been listened to

Question: I have a class with this code in it:
class GeofenceManager {
  ReceivePort geofencingMessagePort = ReceivePort();

  Stream<String> get events {
    return geofencingMessagePort.map((event) => event.toString());
  }
  ...

And in my UI I have a StreamBuilder like this:
  @override
  Widget build(BuildContext context) {
    super.build(context);
    var geofenceManager = Provider.of<GeofenceManager>(context);
    return StreamBuilder(
      initialData: "Waiting ...",
      stream: geofenceManager.events,
      ...

But it's not working. When I run the app I get this error:
Bad state: Stream has already been listened to.

The first build of the UI works, but if I second build is triggered I get the error. I've tried using asBroadcastStream() but it's not solved the problem.
So I'm a bit stuck, any idea how to fix this?
Answer: Ok, got it working by adding a StreamController and listening to the port rather than exposing it. So my code now looks like this:
class GeofenceManager {
  ReceivePort geofencingMessagePort = ReceivePort();
  StreamController<String> _eventController = StreamController<String>.broadcast();

  Stream<String> get events {
    return _eventController.stream;
  }

  GeofenceManager._() {
    IsolateNameServer.registerPortWithName(_geofencingMessagePort.sendPort, 'geofencing_send_port');
    _geofencingMessagePort.listen((message) {
      _eventController.add(message);
    });
  }

  ...

This works but I'm not sure it's the best solution. Any thoughts?
Answer: Stream.asBroadcastStream(..) should work. Make sure not to call geofencingMessagePort .asBroadcastStream(..) multiple times, because that leads to re-subscribing to a single-subscription ReceivePort under the hood. See the documentation

The returned stream will subscribe to this stream when its first subscriber is added

Unfortunately you can't use the getter like in your example
Stream<String> get events {
  return geofencingMessagePort.asBroadcastStream();
}

because every access to events results in calling asBroadcastStream() which in turn attempts to re-subscribe to the single-subscription only geofencingMessagePort.
Instead, you can assign the broadcast stream to a separate field:
ReceivePort _geofencingMessagePort = ReceivePort();
Stream<String> _eventController = _geofencingMessagePort.asBroadcastStream().map((event) => event.toString());
Stream<String> get eventController => _eventController;


Trouble understanding a theorem, algebraic geometry

Question: That is right, I do not understand the claim. Book: William Fulton, Introduction to Algebraic Geometry, page 9, proposition 1 and for those who do not have the book my problem is that he states the following:
Let f and g be polynomials over two variables and let V(f) and V(g) be standard sets of zeros, and f and g have no common factor. Then $V(f) \bigcap V(g)$ is finite.
My trouble: Why is this set nonempty??? Any help would be great, or equivalent a book or link, reference, anything where a classification of affine subsets of $A^2$ is precisely made, because it is a very hard task, you have the case of some disjoint curves what Fulton did not consider at all.
Comment: It can be empty: if $f=x$ and $g=x-1$ (relatively prime) then $V(f)$ and $V(g)$ are parallel lines so (assuming we're working in affine space, I don't have the book to check) $V(f)\cap V(g)=\varnothing$. But why does that worry you? The empty set is finite...
Comment: This is the Bezout theorem. https://en.wikipedia.org/wiki/B%C3%A9zout%27s_theorem
Answer: The answer depends on what your ambient space is, either projective or affine. In projective space the intersection will be non-empty. In affine space the intersection may be empty to take a simple example. The curves $x=0$ and $x=1$ have no point of intersection on affine plane, they are parallel lines. But the projective curves $x=0$ and $x=z$ have and intersection at infinity, $[0,1,0]$.
Answer: If the intersection is empty, then it is finite, since the empty set is a finite set.  So you don't have to consider that possibility separately.  And in fact, it can be empty: for instance, if $f=x$ and $g=x+1$.


Degree of $\mathbb C(t)$ as a field extension over $\mathbb C$

Question: Is it true that for an indeterminate $t$, $\mathbb C(t)$ is a field extension over $\mathbb C$ of uncountable degree? Why or why not?
Thanks.
Comment: Can you show that the elements $1/(t-\alpha)$ are independent as $\alpha$ runs through the complex numbers?
Comment: Ah I see. For each finite subset of these functions, the linear independence equation and Hausdorffness imply that there exists an open ball around each alpha such that the corresponding function must be bounded, making its coefficient zero. Thanks!
Answer: (Using the comment from @GerryMyerson)

The set $\{1 /(t-λ): λ ∈ ℂ\}$ is infinite and linearly independent in $ℂ(t)$

Suppose that $λ_{1}, …, λ_{d}$ are distinct and $α_{1}, …, α_{d} ∈ ℂ$ are such that
$$
α_{1} \frac{1}{t-λ_{1}}+⋯+α_{d} \frac{1}{t-λ_{d}}=0
$$
Multiplying up we get
$$
p(t):=\sum_{i=1}^{d} α_{i} \prod_{j ≠ i}\left(t-λ_{j}\right)=0 .
$$
However $\prod_{j ≠ i}\left(λ_{i}-λ_{j}\right) ≠ 0$ since the $λ_{i}$'s are distinct and $0=p\left(λ_{i}\right)=α_{i} \prod_{j ≠ i}\left(λ_{i}-λ_{j}\right)$, so $α_{i}=0$ for all $1 ⩽ i ⩽ d$. The claim follows.


binomial limit when limit approches to infinity

Question: $\displaystyle \lim_{n\rightarrow\infty}\binom{n}{x}\left(\frac{m}{n}\right)^x\left(1-\frac{m}{n}\right)^{n-x}$
solution i try
$\displaystyle \lim_{n\rightarrow\infty}\left(\frac{m}{n}\right)^x\left(1-\frac{m}{n}\right)^{n-x}=\lim_{n\rightarrow\infty}(\frac{m}{n}+1-\frac{m}{n})^n=1$
I have edited my post
This is wrong how i find right answer. Help me
Answer: If $x=0$, the limit is $\exp(-m)$.
if $x>0$,
\begin{align}
\lim_{n \to \infty} \left( \frac{m}{n}\right)^x \left( 1-\frac{m}n\right)^{n-x} &=\lim_{n \to \infty}\left(\frac{m/n}{1-m/n}\right)^x \lim_{n \to \infty} \left( 1 - \frac{m}{n}\right)^n\\
&=0\cdot e^{-m} \\
&=0
\end{align}
Edit to answer the edited question:
\begin{align}
\lim_{n \to \infty} \binom{n}{x} \left( \frac{m}{n} \right)^x \left( 1-\frac{m}{n}\right)^{n-x} &= \lim_{n \to \infty} \frac{n!}{x!(n-x)!} \frac{m^x}{n^x} \left( 1-\frac{m}{n}\right)^{n-x} \\
&=\lim_{n \to \infty} \frac{n!}{(n-x)!n^x} \frac{m^x}{x!}\left( 1- \frac{m}{n} \right)^{n-x} \\
&=\frac{m^x}{x!} \lim_{n \to \infty} \left(1-\frac{m}n \right)^{n}\\
&=\frac{m^x}{x!} \exp(-m)
\end{align}
Comment: @ Siong Thye Goh please see it i have edited it
Answer: Assuming $x$ is a natural number less than $n$, then we see that
\begin{align}
\binom{n}{x} \left(\frac{m}{n}\right)^x\left(1-\frac{m}{n}\right)^{n-x} =&\ \frac{n!}{x!(n-x)!}\left(\frac{m}{n}\right)^x\left(1-\frac{m}{n}\right)^{n-x}\\
\text{Stirling Approximation } \sim&\ \frac{\sqrt{2\pi n} \left(\frac{n}{e} \right)^n}{x! \sqrt{2\pi(n-x)}(\frac{n-x}{e})^{n-x}}\left(\frac{m}{n}\right)^x\left(1-\frac{m}{n}\right)^{n-x}\\
=&\ \frac{1}{x!}\sqrt{\frac{n}{n-x}}\left(1-\frac{m-x}{n-x} \right)^{n-x}\left( \frac{m}{e}\right)^x\\
\rightarrow &\ \frac{1}{x!} \left( \frac{m}{e}\right)^xe^{-(m-x)}= \frac{m^x}{x!}e^{-m}
\end{align}
Answer: Note that we have
$$\binom{n}{x}\left(\frac{m}{n}\right)^x\left(1-\frac mn\right)^{n-x}=\frac{m^x}{x!}\left(1-\frac{1}{n}\right)\left(1-\frac{2}{n}\right)\cdots\left(1-\frac{x-1}{n}\right)\left(1-\frac mn\right)^{n-x}$$
Therefore, for fixed $x$, we have
$$\lim_{n\to \infty}\binom{n}{x}\left(\frac{m}{n}\right)^x\left(1-\frac mn\right)^{n-x}=\frac{m^x}{x!}e^{-m}$$
Answer: Assuming that $x>0$
$$\displaystyle \lim_{n\rightarrow\infty}\left(\frac{m}{n}\right)^x\left(1-\frac{m}{n}\right)^{n-x}$$
$$\displaystyle \lim_{n\rightarrow\infty}\left(\frac{m}{n}\right)^x\left(1-\frac{m}{n}\right)^{n} \left(1-\frac{m}{n}\right)^{-x}=$$
$$0\times e^{-m} \times 1 =0$$
Assuming $x=0$ the limit is $$1\times e^{-m} \times 1 =e^{-m}$$
Assuming $x<0$ the limit is $$\infty \times e^{-m} \times 1 =\infty$$
Comment: Please see Mohammad Raizi


Why my javascript code not process from top to bottom coding?

Question: Why my javascript code not process from top to bottom coding ?
https://jsfiddle.net/p47f6Lcy/1/
With my code when press on id="test" Why still alert before change backgroundColor and translate3d
See on my code it's should change backgroundColor and translate3d before call function test2_fn
How can i do for change backgroundColor and translate3d befire  alert ?
..

CLICK

Comment: Because the browser doesn't repaint the screen until the current JS finishes executing. So the element styles *have* been updated in the DOM, you just don't see it yet.
Comment: how can i do ? for solve this issue.
Answer: As nnnnnn mentioned in the comments:

Because the browser doesn't repaint the screen until the current JS finishes executing. So the element styles have been updated in the DOM, you just don't see it yet.

If you really want to do it, you can postpone the execution of the other function to the next cycle in the event loop. You can simply use setTimeout(test2_fn, 0).
Working fiddle
This is also a good read.
Answer: Because it uses a stack to be cleared before rendering the changes.
In order to clear the stack you need to make all statements to be executed.
I have added a little timeout 10ms so that altert could occur.

function test_fn(callback){
    document.getElementById("test").style.backgroundColor = "red";
    document.getElementById("test").style.transform = "translate3d(500px, 0px, 0px)";

}

function test2_fn(){
  setTimeout(function(){ alert("555");},10) ;
}

CLICK

Answer: the issue is that the browser doesn't repaint the page before invoking the alert.
the following might do the trick:

CLICK


Rock, Paper, Sissors java game from input file. charAt method giving grief

Question: Okay so I have been working on this program for a week and a half, and I feel like I am really close but have been hitting a wall. I have looked high and low for this and I am admittedly not very good at using java's FAQ system. I am trying to pull in a string that contains text in the form R S with player1 a space and player2 move. After this I tried to use charAt(index) and I am getting an AIOOBE every single time (it cant find any position). I have tried advancing several lines in the scanner just to get one that works and I cant. It seems that it grabs the first 2 lines as int, which are the games played and the hands per game.
import java.util.*;
import java.lang.*;
import java.io.*;

public class rPS{
    public static void main(String ... args) throws IOException{
        int count = 0;
        File myFile = new File("a.txt");
        Scanner fin = new Scanner(myFile);
        int games = fin.nextInt();
        for(int i = 0; i<games; i++){
            int rounds = fin.nextInt();
            int tie = 0;
            int p1win = 0;
            int p2win = 0;
            for(int j=0; j<rounds; j++){
                String line = fin.nextLine();
                char p1 = line.charAt(0);
                char p2 = line.charAt(2);
                if (p1 == p2)
                    tie = tie + 1;
                else if (p1 == 'R'){
                    if (p2 == 'S')
                        p1win = p1win + 1;
                    else if (p2 == 'P')
                        p2win = p2win + 1;
                }else if (p1 == 'P'){
                    if (p2 == 'S')
                        p2win = p2win + 1;
                    else if (p2 == 'R')
                        p1win = p1win + 1;
                }else if (p1 == 'S'){
                    if (p2 == 'P')
                        p1win = p1win + 1;
                    else if (p2 == 'R')
                        p2win = p2win + 1;
                }
            }
            if(p1win > p2win)
                System.out.println("Player 1");
            else if(p2win > p1win)
                System.out.println("Player 2");
            else
                System.out.println("Tie!");
        }
    }
}

Comment: Have you tried checking the string length just after you've read it in, but before you do the charAt? If it is not at least 3 then you will get an exception on your second charAt call.
Comment: Can you edit your code so it is easier to copy from the page?  Otherwise you can post a link to a Gist or a Pastebin.
Comment: Can you post a sample of the files you use?
Comment: line by line (seperated by ; not in the text) 2;2;R S;S P;1;S P
Comment: I commented out all the code below the nextLine() and had it print, to my surprise it Printed "R S" correctly and then errored saying inputmismatchException at java.util.scanner.nect and .nextint
Comment: thank you to all, papa Pearson's was the most helpful when I was able to implement it properly, if i could up vote i would :)
Answer: Try calling nextLine() without saving the return value in between reading the rounds and reading the line with the first moves.
The scanner stays just past the integer you read and when you call nextline() it returns the newline character instead of the next line like you would expect.
Comment: without saving the return value... do you mean fin.nextLine(); and then String line = fin.nextLine(); ?? I dont see a return value inbetween there. Thank you so much for the help so far
Comment: Thank you, Thank you. I tried this several times and finally figured out how to run through the code line by line and solved it by fin.nextLine() before the nested loop and printed it out until it was iterating perfect. The code worked 100% with that, Thank you all :)


Mapping and preimage

Question: Just to clarify, ∪c∈c" c , the c∈c" is below the union ∪. P(Y) is the power set of Y.
Let f : X -> Y be a map.
(a) Show that for any subset C ⊆ Y , one has
$f^{-1}$ (Y\C) = X\ $f^{-1}$(C)
(b) Show that for any collection c" ⊆ P(Y) of subsets in Y, one has
$f^{-1}$ (∪c∈c" c) = ∪c∈c" $f^{-1}$ (c)
(c) Show that for any collection c" ⊆ P(Y) of subsets in Y, one has
$f^{-1}$ (∩c∈c" c) = ∩c∈c" $f^{-1}$ (c)
My Solutions for (a) : x ∈ $f^{-1}$ (Y\C) if and only if f(x) ∈ Y and not f(x) ∈ C if and only if x ∈ $f^{-1}$ (Y) and not x ∈ $f^{-1}$ (C) if and only if x ∈ X\ $f^{-1}$(C) Can i prove LHS to RHS this way?
My Solutions for (b) : x ∈ $f^{-1}$ (∪c∈c" c) if and only if f(x) ∈ (∪c∈c" c) if and only if
f(x) ∈ c for some c∈c" if and only if x ∈ $f^{-1}$ (c) for some c∈c" if and only if x ∈ ∪c∈c" $f^{-1}$(c).  Can i prove LHS to RHS this way?
My Solutions for (c) : its pretty similar, just replace union with intersection and replace for some with for every.
x ∈ $f^{-1}$ (∩c∈c" c) if and only if f(x) ∈ (∩c∈c" c) if and only if
f(x) ∈ c for every c∈c" if and only if x ∈ $f^{-1}$ (c) for every c∈c" if and only if x ∈ ∩c∈c" $f^{-1}$(c). Can i prove LHS to RHS this way?
Comment: "Sorry for the bad representation of the mathematical terms!" It's not just bad; it's incomprehensible. What could X\f-1(C) possibly mean? There is some help on this site for formatting mathematics, maybe you can find it and read it and edit accordingly. Failing that, you could put in a few sentences like, "When I write f-1, what I mean is ...."
Comment: Hey thanks for the feedback! I checked the math jax beginner tutorial. How do you key in inverse function?
Comment: That's better. $\cup$ is \cup. $\in$ is \in. $\cup_{c\in c''}$ is \cup_{c\in c''}. $\to$ is \to. $\cap$ is \cap. $\subseteq$ is \subseteq.
Answer: You've got the right idea, but you're overusing if and only if and making it a bit messy.
For example, to show $ f^{−1} (Y \backslash C) \supset X \backslash f^{-1}(C) $ in question (a), we are only required to notice that if $ x \in X \backslash f^{-1}(C) $ then $ f(x) \notin C$, or $ f(x) \in Y \backslash C $ hence $ x \in f^{-1} ( Y \backslash C ) $ as required.

Mapping and preimage


Problema ao fazer busca (FirstOrDefault) - Linq

Question: Estou com um problema ao realizar a seguinte busca:
var estDel = bdprincipalEntities.unidades
            .FirstOrDefault(x => x.uni_codigo == uni_codigo && x.Emp_codigo == Emp_codigo);

o campo é do tipo string:
public string uni_codigo { get; set; }

Meu problema é o seguinte: quando eu faço uma busca por um campo que recebe valor "20", ou que comece com qualquer valor numérico, a busca de retorna null, mas se faço busca com "metro" da certo, não entendo oque pode ser, sendo que "20" é considerado string também
Registro existe no banco de dados:
Comment: Essa seria a minha pergunta, você quer uma busca exata ou que **contenha** o valor?
Comment: Quando você diz "que comece com qualquer valor numérico" você quer fazer algo como se fosse o "like" do SQL? Pois no seu select vai retornar apenas valores em que batam exatamente os valores que especificou tanto para uni_codigo quanto para Emp_codigo.
Comment: O Emp_codigo no banco está nulo, por curiosidade, qual o valor que você está passando no seu Emp_codigo?
Comment: Desculpa a demora, mas eu quero que retorne uma busca exata, o código tem que ser exatamente 20
Comment: O registro existe no banco de dados, vou postar uma imagem
Comment: Ah, tem razão, não me toquei disso, eu passo valor padrão que é 1, esse é o erro, poste uma resposta que eu aceito
Answer: Conforme explicado nos comentários da pergunta, o problema não está no LINQ e sim na busca efetuada, pois na linha do seu banco, conforme a imagem, a coluna "Emp_codigo" está nulo, mas está sendo passado um valor a mesma.
Desta forma, utilize o operador OR para esta consulta, nule o valor ou omita o campo de sua busca, dependendo da sua regra de negócio.


Window does not appear using tkinter GUI for Python

Question: so i have a simple problem but i have no idea what's wrong so have a look:
from tkinter import *
from time import sleep
root = Tk()
l1 = Label(root, text="Ok")
l1.pack()
sleep(5)
l2 = Label(root, text="Great")
l2.pack()
sleep(10)
l3 = Label(root, text="Nice")
l3.pack()
root.mainloop()

All i wanted to do is make a window, and then display those label's one after another so the window would pop up with just l1 and after 5s the l2 would also appear and then after another 5s l3 should show up. Instead i don't see this window at all for 10s and then it appear with all the label's at once. Can someone help me fix this ?
Comment: The main window will not be updated until the main loop is called. If you want the labels to appear one after another with delays, learn how to use `root.after()`.
Comment: How about googling a tutorial?
Comment: Can you give me an example as to how it should look like?
Answer: First of all, dont use from tkinter import *.
From this answer :

from Tkinter import * imports every exposed object in Tkinter into your current namespace. import Tkinter imports the "namespace" Tkinter in your namespace and import Tkinter as tk does the same, but "renames" it locally to 'tk' to save you typing
you want only one object of a module, you do from module import object or from module import object as whatiwantittocall
from module import * is discouraged, as you may accidentally shadow ("override") names, and may lose track which objects belong to wich module.

Now for your question, you need to use root.after(timeInMillisecond, functionToCall) and add the label in the function:
import tkinter as tk
root = tk.Tk()

button = tk.Button(root, text="Quit", command=root.destroy)
button.pack()

l1 = tk.Label(root, text="Ok")
l1.pack()

def add_label():
    l1 = tk.Label(root, text="Ok")
    l1.pack()
    root.after(500, add_label)

root.after(500, add_label)
root.mainloop()

PS : if someone with 1500+ reputation could add a tags "root.after" or something like this, it's the main point of the question


Virtual disk expansion

Question: I'm running a virtual image (which happens to be our server for a number of programs) on a machine running ESXi 5.5.0. Although the host computer has a SSD of about 200GB, the virtual image was initially given a 40GB virtual disk. Unfortunately, it is a "thick provision lazy zeroed" type disk, and cannot be expanded using ESXi's GUI system.
I recently tried using vmkfstools to expand the VMDK (vmkfstools -X 60GB myimage.vmdk). This command completed successfully but the joy was short lived when I tried to boot up:

The capacity of the parent virtual disk and the capacity of the child disk are different

I initially tried shrinking the disk I changed back to 40GB, but this didn't work. A little research has said I need to open the descriptor using vi but I'm unsure if this would work (and where the descriptor is).
Would anyone have any suggestions on how to resolve this?
Answer: Why dont you try VHDResizer? See if it works for you.
But the issue is it works for VHDs only. You can convert your VMDK to VHD and try.
Another tip: Make a copy/ backup of the Disk file before you try such operations on them.
Even if I use VMWare I prefer to use VHDs as they are cross compatible across various VM platforms.

Virtual disk expansion


SQL order of operations for logical operands

Question: I inherited some some bad SQL code (zero documentation and I'm missing the original requirements). In the where clause, it has the following:
A OR B AND C AND D OR E

From my knowledge of logical operands, my assumption is that SQL would compile this as:
A OR (B AND C AND D) OR E

Is that correct?
I have a feeling the intent was
(A OR B) AND C AND (D OR E)

and I will need to speak with those that requested this project in the first place, as I haven't seen the original requirements.
Comment: Your understanding of boolean operator precedence is exactly right: AND is stronger than OR, exactly like multiplication is vs. addition. Your guess as to the intent is probably also 100% correct (meaning that the condition is written incorrectly) but you won't know without asking those who requested the project.
Comment: If you are going to add parentheses, then the correct version would be:  `(A OR ((B AND C) AND D)) OR E`.  This is semantically equivalent to your second version.
Comment: @GordonLinoff - No, the version you propose is not equivalent to the OP's second version. And it is impossible to know what the "correct" version is, without knowing the intent (the requirement).
Comment: [Documentation for condition precedence](https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/About-SQL-Conditions.html#GUID-65B103FE-C00C-46A3-8173-A731DBF62C80), showing that you are right as `AND` has higher precedence than `OR`.
Answer: You are correct. In the absence of parenthesis this should be interpreted as:
A OR (B AND C AND D) OR E


Como saber se usuário está logado com ion-auth 2

Question: Quero restringir o acesso ao meu sistema de login, para apenas 1 para cada login, quero que meu sistema bloqueie o acesso, caso o login já esteja sendo utilizado em outro dispositivo.
Qual seria a melhor pratica pra fazer isso?
Estou utilizando Codeigniter 3, junto com o plugins Ion-Auth 2.
url do plugns https://github.com/benedmunds/CodeIgniter-Ion-Auth.
Answer: Então, o problema que você quer resolver é que o mesmo usuário não pode estar logado em duas "máquinas" ao mesmo tempo.
Usando sessões normais, que ficam no servidor - seja em memória ou no banco de dados - você só tem uma certeza: o seu usuário se autenticou no sistema. Você não tem como descobrir se ele ainda está logado ou não, a menos que ele te informe expressamente - ou seja: tenha pedido para deslogar.
Para saber se o cara ainda está logado, basta na hora do login verificar se o email/login dele está no banco de dados onde você guarda a sessão (um SELECT email FROM session WHERE email = $email já resolve). O problema é que você pode acabar travando seu usuário fora do seu sistema até a sessão vencer.
No entanto, tem uma forma de você saber se ele ainda está usando o sistema, se a aba ainda está aberta no navegador dele: você vai usar um websocket no lado cliente e do servidor. Não vou me prolongar na implementação do cliente, mas encontrei um tutorial que parece bom sobre essa parte.
Pensa em WebSocket como uma sala de chat com o servidor, seu cliente pode mandar mensagens pro servidor e o servidor pode mandar mensagens pro cliente e/ou clientes.
O problema, é que esse tutorial não tem a parte da implementação do servidor WebSocket - por que o que você já tem é um servidor web, HTTP. Uma biblioteca que encontrei para PHP é o Ratchet. Você, literalmente, vai precisar rodar um outro server - em outra porta - para receber as mensagens do cliente. No Ratchet seria algo como:

class WSAuth implements MessageComponentInterface {
    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        // recebe a mensagem do cliente com login e senha
        // faz toda a verificação para autenticá-lo
        // manda o SessionID de volta pro cliente, e guarda o cookie.
    }

    public function onClose(ConnectionInterface $conn) {
       // desloga o usuário caso o cliente tenha se conectado antes
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
      // provavelmente você deve deslogar o cara se der erro também
    }
}

Outra solução seria ficar mandando um Ajax à cada minuto pro servidor e se o cliente não mandar por 3 minutos você desloga ele.
Answer: Consultando a documentação do ion_auth você pode ver que tem um método logged_in() da própria biblioteca. Retorna TRUE caso esteja logado.
Comment: @DaniloD mas aí como ele vai saber se o cara se logou e perdeu a sessão dele? Por exemplo, se ele se logou e entrou em outro navegador ou no celular.

Acho que o que o @ClaytonEduardoMergulhão quer pode ser alguma questão de segurança mais complexa nesse caso. Seria preciso algum tipo de verificação constante da validade da sessão. A melhor maneira de manter isso seria por ``WebSockets``.
Comment: @Daniel mas a sessão é global no banco de dados, [documentação](https://www.codeigniter.com/user_guide/libraries/sessions.html#database-driver) ele poderia informar na sessão o e-mail no usuário no campo 'data'. ai logando antes de logar ele verificava se aquele e-mail tava no campo data, se tivesse é por que ele logou, mesmo que seja em um dispositivo diferente.
Comment: Essa função não retorno o que preciso, essa função vai verificar se está logado e dai mando o usuário para pagina restrita, o que quero e não deixar o usuário logar 2 vezes com mesmo login e senha
Comment: nesse caso você precisaria salvar a sessão no banco de dados e na hora de fazer um login verificar se o usuário não está na sessão do banco;
Comment: É acho que alguma coisa no que o @Daniel disse. a session do Codeigniter já gravada no banco, mais se ela expirar, é bem isso que ele falou meus usuários vão acessar por celular, tablet e computador, só não vai ser permitido o acesso com mesmo login mais de uma vez, se ele estiver logado, não pode logar com mesmo login em navegadores diferente, ou em dispositivos diferente.
Comment: @ClaytonEduardoMergulhão então, edita sua pergunta pra ela ficar mais certinha, aí preparo uma resposta explicando por alto como fazer verificação de sessão usando ``WebSockets``. Que eu nem sei bem, mas já vi na teoria. Só que não vou considerar o ion_auth, por que é mais geral que isso.
Comment: @Daniel veja se ficou melhor a pergunta?


Why does the glm() function in R give an error message when trying to fit a step function using cut()?

Question: I am working with Wage data in library ISLR. Wage includes wage and age as columns.
Why does cv.glm throw an Error for the script below that disappears when test.fit.12.1 is replaced by test.fit.12? Also, summary(test.fit.12.1) shows the same levels as Wage$tmp.
- Wage$tmp <- cut(Wage$age,12)
- #test.fit.12 = glm(wage~tmp, data = Wage)
- test.fit.12.1 = glm(wage~cut(age,12), data = Wage)
- test = cv.glm(Wage ,test.fit.12.1)$delta[1]

Error message: Error in model.frame.default(Terms, newdata, na.action =
na.action, xlev = object$xlevels): factor cut(age, 12) has new level (32.995,33]

Answer: When you run cv.glm, the data are split into parts, with a model fitted to one part and predictions calculated on the other part. The fit and predict steps both call cut and the cutpoints will typically be different. That means the levels of the factor cut(age,12) will be different in the fitting data and the prediction data. R is warning you that the levels of the factor are different, so the prediction would be meaningless
The default for cv.glm is leave-one-out cross-validation, so the prediction step is trying to run cut(age,12) on a single observation!
The way around this is to create the variable ahead of time, as in your commented-out line


Is logistic regression a specific case of a neural network?

Question: I ended up in a debate regarding logistic regression and neural networks (NNs).
Is it wrong to say that logistic regression is a specific case of a neural network?
I have seen a lot of explanation in which logistic regression is shown as a NN, like the following:

From Tess Fernandez.
Or like this:

To me there are no differences, at least on the surface.
There is a linear combination of the input, a fixed nonlinear function (sigmoid) and a classification based on the output probabilities, which is exactly a simple neural network with a single layer with a single node (at least in binary problem) and that use the sigmoid function as a nonlinear activation function.
But someone told me that it is not exactly so, because the assumptions behind this model are completely different from a neural network.
What are these assumptions? And why should logistic regression be considered different from a neural network?
I know that NN can handle more complex problems (like nonlinearly separable problems), but this puzzle me a bit.
Comment: "because the assumptions behind this model are completely different from a neural network." I'd follow up on that. What are the different assumptions? It would not be so bizarre to try out a logistic regression before moving to more complex models like deep neural nets.
Comment: Two more comments worth making: 1) If your experience is with logistic regression but not with more complicated neural networks, don't advertise yourself as a neural net guru (even if you do have expertise in logistic regression) just because logistic regression is a particular case of a neural network. $\text{//}$ 2) The same logic about a logistic regression being a neural net with no hidden layers applies to a linear regression being a neural net regression with no hidden layers (so also don't advertise yourself as a neural net guru just because you know linear regression).
Comment: See https://stats.stackexchange.com/q/362425/60613
Answer: You have to be very specific about what you mean. We can show mathematically that a certain neural network architecture trained with a certain loss coincides exactly with logistic regression at the optimal parameters. Other neural networks will not.
A binary logistic regression makes predictions $\hat{y}$ using this equation:
$$
\hat{y}=\sigma(X \beta + \beta_0)
$$
where $X$ is a $n \times p$ matrix of features (predictors, independent variables) and vector $\beta$ is the vector of $p$ coefficients and $\beta_0$ is the intercept and $\sigma(z)=\frac{1}{\exp(-z)+1}$. Conventionally in a logistic regression, we would roll the $\beta_0$ scalar into the vector $\beta$ and append a column of 1s to $X$, but I've moved it out of $\beta$ for clarity of exposition.
A neural network with no hidden layers and one output neuron with a sigmoid activation makes predictions using the equation
$$
\hat{y}=\sigma(X \beta + \beta_0)
$$
with $\hat{y},\sigma,X, \beta, \beta_0$ as before. Clearly, the equation is exactly the same. In the neural-networks literature, $\beta_0$ is usually called a "bias," even though it has nothing to do with the statistical concept of bias. Otherwise, the terminology is identical.
A logistic regression has the Bernoulli likelihood as its objective function, or, equivalently, the Bernoulli log-likelihood function. This objective function is maximized:
$$
\arg\max_{\beta,\beta_0} \sum_i \left[ y_i \log(\hat{y_i}) + (1-y_i)\log(1-\hat{y_i})\right]
$$ where $y \in \{0,1\}$.
We can motivate this objective function from a Bernoulli probability model where the probability of success depends on $X$.
A neural network can, in principle, use any loss function we like. It might use the so-called "cross-entropy" function (even though the "cross-entropy" can motivate any number of loss functions; see How to construct a cross-entropy loss for general regression targets?), in which case the model minimizes this loss function:
$$
\arg\min_{\beta,\beta_0} -\sum_i \left[ y_i \log(\hat{y_i}) + (1-y_i)\log(1-\hat{y_i})\right]
$$
In both cases, these objective functions are strictly convex (concave) when certain conditions are met. Strict convexity implies that there is a single minimum and that this minimum is a global. Moreover, the objective functions are identical, since minimizing a strictly convex function $f$ is equivalent to maximizing $-f$. Therefore, these two models recover the same parameter estimates $\beta, \beta_0$. As long as the model attains the single optimum, it doesn't matter what optimizer is used, because there is only one optimum for these specific models.
However, a neural network is not required to optimize this specific loss function; for instance, a triplet-loss for this same model would likely recover different estimates $\beta,\beta_0$. And the MSE/least squares loss is not convex in this problem, so that neural network would differ from logistic regression as well (see: What is happening here, when I use squared loss in logistic regression setting?).
Comment: (+1) Well said! Via different optimisers, I didn't mean different solutions.
Comment: @Joe I think the opening paragraph is very explicit about the answer to the question. The details and nuance are an important part of the answer: some neural networks are logistic regression, and some neural networks are not. Can you help me understand what you've found unclear?
Comment: You might want to be just a little more clear about the actual answer to the question here.  I think you are basically saying "yes, a logistic regression is a neural network with these specific details", but it's not very clear - gunes' answer  makes that much more clear, even though your answer contains much more useful information as to *why*, and *in what way* it is a special case.
Answer: Architecture-wise, yes, it's a special case of neural net. A logistic regression model can be constructed via neural network libraries. In the end, both have neurons having the same computations if the same activation and loss is chosen. This makes it a special NN, but since logistic regression is the simplest model, it's possible to train it using second-order methods, e.g. newton. Second order methods use Hessian matrix, in addition to gradients. But, this computation is not efficient for larger NNs and libraries  prefer to use gradient descent alternatives or quasi-newton methods, that are either entirely first-order or approximate second-order methods. So, the slight difference lies in the possible optimisers, though this doesn't mean you'll get different solutions due to convexity properties of the problem (at least numerically).
Answer: If you have logistic activation function in the output layer and you are trying to maximise the log-likelihood of observations belonging to their corresponding classes (e.g. via its negative as the cost function), then yes, each output-layer neuron can be said to be an implementation of a logistic model over its inputs (which can be outputs of the neurons from the hidden layers).
In the simplest case, when you have a "network" of only one neuron with logistic activation function, and assuming you maximise the log-likelihood, then you are performing logistic regression.


Cauchy Integral Formula for $1/z+1/z^2$

Question: From Cauchy's Integral Formula, we can define $f\left(z\right) = z^{2} + z$, and find for any contour $C$ on the right part of the semi-plane $\Re\left(z\right) > 0$ that
\begin{align*}
\int_{C}\left(\frac{1}{z} +
\frac{1}{z^{2}}\right)\mathrm{d}z & =
\int_{C}\frac{z^{2} + z}{z^{3}}\,\mathrm{d}z =
\int_{C}\frac{f\left(z\right)}
{\left(z - 0\right)^{3}}\,\mathrm{d}z =
\pi\mathrm{i}f''\left(0\right) =
2\pi\mathrm{i}
\end{align*}
This should work since $z\not= 0$ because $\Re\left(z\right)>0$. However, if I want to calculate
\begin{align*}
\int_{1 - \mathrm{i}}^{1 + \,\sqrt{\,{3}\,}\,\mathrm{i}}
\left(\frac{1}{z} + \frac{1}{z^{2}}\right)\mathrm{d}z
\end{align*}
Would the two integrals have the same value if the path intersect both points $?$. Or in the definite integral would be necessary to just integrate as the usual $?$.
Comment: Why did you write the integrand as $(z^2+z)/z^3$ rather than $(z+1)/z^2$?
Comment: Right, I think I just did it rushing my procedure. However, we would end up with $4z\pi i$ if we use the Cauchy formula.
Comment: $4z\pi i$? You don't want a $z$-dependent answer.
Comment: @J.G. sorry, it would be first derivative, which would be $f'(z)=1$, so the answer still holds as $2\pi i$, thank you
Answer: In Cauchy's Integral Formula, the contour $C$ is the boundary of a disk in the complex plane that contains the singularity of the integrand.  So, in the example here, we have
$$\oint_C \left(\frac1z+\frac1{z^2}\right)\,dz=2\pi i$$
if $z=0$ is interior to the disk bounded by $C$.
If $C$ is not the boundary of any disk for which $z=0$ is an interior point, then Cauchy's Integral Theorem guarantees that the integral over $C$ is $0$.
Comment: Would the downvoter care to comment?
Comment: Would the downvoter care to comment?  How is this not useful?

Cauchy Integral Formula for $1/z+1/z^2$


Main content height issues

Question: I am having issues with the content and footer on a site that I am developing. On  a large screen all the content is displayed properly, but the footer doesn't have any breathing room. When I view it on a laptop, the content bleeds off the screen and you can't scroll to view it. I am not sure what to do to fix this. Any help would be appreciated.
Here is the page: http://capelos.gonzbergagency.com/catering.html
Comment: please isolate your code to the question.  but from a quick look it is b/c your footer is absolute positioned (relative to the window frame instead of relative to your content), at certain size it cause conflict.
Comment: I am not sure where in the code the conflict is. I have tried to make it relative and when I do that it disappears from the screen and you can't scroll to it.
Comment: there are a ton of problems with this code(CSS).  what you have here is not wrong, but not ideal.  a quick fix you can try is to move your footer inside `.main` and 'clear:both' in your css.
Answer:
Remove the position: absolute, top: 0 and bottom: 0 from the footer.
Remove overflow: hidden from the body.
Remove height: 100% from #catering .main, .main, #container and .content.
Add an additional div inside the div with the class main:

Change the margin off .push to 25px instead of 100%.
Comment: Awesome!! I was trying all these different stylings for a sticky footer and my code got really messy. Would happen to know why the content is not sitting inside the div's, it just seems to spill out of it.
Comment: You have a `float: left` and a `float: right` inside the `` but you never `clear` the `float`. That's the reason why this looks so strange otherwise.

Main content height issues


Hourly points add to users php and mysql solution?

Question: In the website im working on i need to add user points. Every user will have it's own points and maximum amount of points will be 200. And upon registration user gets 100 points. With various tasks user points will be deducted.
But main problem im struggling is how to add points to the user, since every user need to gets 1 point every hour unless he have 200 or more points.
My first thought was to do a cronjob where it will run every hour a script which will check if user is verified and if user have less than 200 points and add 1 point to every user.
But after some reading im thinking of different approach which i don't understand quite exactly. The better approach, less server resource consuming would be to run a function which will check every time when user login how many points he have and add appropriate number of points to him. Problem is i don't know how to set it, how to calculate how many points to add to user if he was offline like 8 hours and how to time it? Or even maybe use ajax with timer?
What would be your suggestion and approach to this ?
Edit: Just to add since you ask, users doesn't see each other points.
Comment: Will you be showing the user and his/her "points" to other users on a profile page or similar (i.e. when the user is not logged on)? If so, you'll most likely need a job running to do this automatically instead of "on a user action". That, or whenever the user's info is displayed (regardless of who requests it), make the update.
Comment: No, only registered user can see his own points, and they don't need to be visible to other users.
Answer: When a user does something, check the last time you gave them points. If it was 5 hours ago, give them 5 points. If it was 10 hours ago, give them 10 points. Etc. Implement caching so if a user visits your site 50 times in one hour, you don't have to check against the DB every time.
Anyway, short answer is, do the check when loading the user data, rather than automatically every hour for all users whether they are active or not.
Comment: That's exactly what i had in mind after some searching, but what troubles me is that website might have 1000 visitors browsing constantly and if each of them load website 20 times per hour, that would be 20 000 more db calls. In other hand using cron if server goes offline for 4 hours users wont get their points.
Comment: Use memcache or something similar to cache a user's info for an hour every time you give them this point. That way, if the cache exists, you don't give them a point, and you don't look up their info again from the db, and if it doesn't... well once an hour per user is very manageable. :)
Answer: UPDATE users
SET points = MIN(points + 1, 200)

I don't really see the problem with this script running as a cron. Would be more problem if you handled each event as transaction points, since you'd have to run something like:
# Generates a row each hour per uncapped user, which may become a lot
INSERT INTO transcations (points, type, created)
SELECT 1, 'HOURLY_INCOME', NOW()
FROM users
WHERE points < 200

Is it relevant for other users, or official/inofficial statistics to check what their current point is? This is quite relevant, since it won't work fully if it only updates upon login.
Comment: wouldn't MIN just select the one that have minimum amount of points ?
Comment: Indeed. If points are `100`, `MIN(100 + 1, 200)` returns 101. If points are `200`, `MIN(200 + 1, 200)` returns 200.
Answer: user_table
---------------
id  |  reg_date
1   |  2013-10-10 21:10:15
2   |  2013-10-11 05:56:32

Just look how many hours left after user registration, add 100 points:
SELECT
   TIMESTAMPDIFF(HOUR, `reg_date`, NOW())+100 AS `p`
FROM
    user_table
WHERE
    id = 1

And then check in PHP if result more than 200 just show 200.
Answer: Hmm, from mysql 5.1 there is neat feature which is basically mysql cron called MySQL Event Scheduler, and i think ill go with that for now since cron script will be very easy to write, small and not time consuming.
All i need to do is to write
UPDATE users SET points = (points +1) WHERE points<200

And add it to mysql event recurring every hour.


swift AVPlayerItemDidPlayToEndTimeNotification not work

Question: I create a class named DecryptAudioPlayer,it inherit NSObject,this class refrenced a AVPlayer,and observe the notice AVPlayerItemDidPlayToEndTimeNotification when init.like below:
override init() {
    super.init()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.playToEnd(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
}

and i have the method:
func playToEnd(notification:NSNotification) {
    Log.printLog("notification:\(notification)")
}

but sometimes the player's ower can't recived the AVPlayerItemDidPlayToEndTimeNotification,i am very confused.it seems the AVPlayerItem may don't post AVPlayerItemDidPlayToEndTimeNotification when its end time ,who can tell me why?
Comment: Are you adding the observer after you init the player.
Comment: of course.the player is owed by DecryptAudioPlayer,i add the observe to the owe.
Comment: In the notification object add the currentItem of the player
Comment: i just want to recived AVPlayerItemDidPlayToEndTimeNotification whatever the notice come from any avplayeritem,so i add the observe when init and the object is nil.the suitation is,there are many avplayeritems to be play seriral,i can recived most of all,but a few i can't recived, this is the problem i have to solve.
Comment: I guess it may be the local audio files has some problem to cause that. But when the suitation happened, I can get the stalled notification to solve the problem. So, my question could be put down for a while. Thanks for you mind.
Answer: I can get the stalled notification to solve the problem. So the question could be put down for a while.