Erro ao fazer deploy appengine

Question: Eu tenho esse projeto em spring, roda localmente com o appengine, mas quando faço deploy, ele da erro la no appengine
<code>org.eclipse.jetty.annotations.ServletContainerInitializersStarter doStart:  (ServletContainerInitializersStarter.java:67)
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'historicoTermosDeUsoRepository' defined in com.fogas.termos.repository.HistoricoTermosDeUsoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
</code>
pom.xml
<code>  <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.fogas.termos</groupId>
    <artifactId>termos</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>termos</name>
    <description>Termos de uso</description>
    <packaging>war</packaging>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.13.Final</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-storage</artifactId>
        <version>1.14.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-maven-plugin</artifactId>
            <version>1.9.60</version>
        </plugin>
    </plugins>
</build>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>
Answer: Resolvi faltou uma configuração setada para true no arquivo de configuração do appengine

Erro ao fazer deploy appengine


Skip Beat in a Measure

Question: Can we skip some/a beat(s) in a measure in music notation?
In the picure, I want to skip that quarter rest so we can play directly the next c note?
Comment: Is this a piece you have written, or a piece you're playing that someone else wrote?
Comment: It's a piece I'm writing
Answer: To "skip" a beat, change the time signature for that measure. In the specific case in the question, the time signature for the measure shown would be 3/4, then the following measure would return to the original time signature. Here's an example of some music in 4/4 time, switching the 3/4 (i.e., "skipping a beat"), then returning to 4/4 time.
Comment: That's an interesting interpretation of that melody :-)
Comment: Stravinsky's "Twelve Variations on *Ah! vous dirai-je, Maman*"?
Comment: @MichaelSeifert Now I'm hearing "Twinkle" with the *Rite of String* chords under each note.
Comment: Wow it works! Tnkiu!
Comment: @Wastrel I don't know what you're talking about. This is a totally original composition. :-)

Skip Beat in a Measure


Laravel 5.8 - Validação - passar valor de um input para validar outro

Question: Gostaria de verificar se ha possibilidade de na validação do formRequest passar o valor de um input como parâmetro para validar outro.
Exemplo:
Inputs 'company_id', 'email'
no formRequest gostaria de passar o valor do 'company_id' em uma validação personalizada.

'teste' é minha validação personalizada e como parâmetro gostaria que fosse o valor do input 'company_id', mas desta maneira ele envia como parâmetro uma string com o valor = 'company_id'.
A validação que quero fazer é de e-mail único para o ID da empresa. O e-mail pode repetir porem não com mesmo ID de empresa.
Answer: Resolvi o problema atribuindo o valor do input em uma variável e passando como parâmetro conforme imagem.


Back Button in WP

Question: I'm facing a problem in an application that I'm building for windows phone. The application consists of many pages and when the back button is pressed in one of the pages it goes back to the main page. The problem is that when the back button is pressed again in the main page it goes to the previous page and it doesn't exit the application. How would i exit the application?
Answer: Don't override back button behavior. If user presses back, he want to go to previous page. If you have another back button in UI then use NavigationService.GoBack instead of going to concrete page.
If your app really can't work this way and you cannot change this, as a last resort you can remove last entry from navigation history (so back will not go to this entry) using NavigationService.RemoveBackEntry (this is new in Mango).
Answer: <code>protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
        NavigationService.GoBack(); // if you want to go back

        // or if you want to exit
        try
        {
            while(NavigationService.CanGoBack)
                NavigationService.RemoveBackEntry();
        }
        catch (InvalidOperationException)
        {
        }
 }
</code>

Back Button in WP


WPF Image to string and string to image

Question: I have a data driven application and one of the entities is supposed to have an image attached to it. Now, since I'm putting the images in a sub-folder of my project directory I don't need to serialize the actual image to the binary file, just the path to it. The image is selected from a ListBox that contains thumbnails and should be displayed on an image panel in another dialogue (when the appropriate entity is selected)
I can't seem to extract the path from the actual Image. The ListBox is bound to an object of the type Image in the ViewModel and from there I should be extracting the path and placing it in the constructor of the object.
The other thing I need is to access the image using the path, in another dialogue. Basically, in my table of entities I have a details panel that shows all the attributes of the selected entity, but how would I go about displaying the image if I only have it's path?
Comment: Posting the code would be helpful.
Comment: http://stackoverflow.com/questions/2573912/binding-image-source-to-string-in-wpf
Comment: http://www.telerik.com/community/forums/wpf/gridview/using-a-converter-for-string-to-image.aspx
Comment: As I can see you have to handle the couple Image/path. Why don't you make a simple object containing that information and work with `Converters`? it may be easier.
Answer: Ok, I solved my issue using BitmapImage instead of Image. I accessed the absolute path, via the UriSource property, after which I split the string, using \ as the splitter argument.
I then simply accessed the last element of the array of strings formed by the split method to save the name of the image. After that it was only a matter of creating a new Bitmap image with the given Uri using the following parameter:
Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + App.MyPictureFolder + MyPictureName

Where MyPictureFolder is a static string variable whichc contains the name of the appropriate folder. Might not be the best method, but it works well enough for me.

WPF Image to string and string to image


Python: Web Scraping em página dinâmica

Question: Estou pesquisando sobre web scraping. Já encontrei dezenas de páginas, porém, em nenhuma delas encontrei como extrair informações de páginas dinâmicas.
Pois bem, estou tentando pegar o valor da criptomoeda LTCBRL  diretamente no site a seguir: https://br.tradingview.com/symbols/LTCBRL/
Abaixo está a foto da tela...
A tag em que está o valor é:
269.97

Eu gostaria de apenas uma dica de como pegar o valor.
O código fornecido pelo colega Jones Vieira foi:
Ele informa que para ele funcionou, porém, para mim apresente o erro na imagem abaixo.
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome(
    chrome_options = chrome_options,
    service_args = ['--verbose']
)

driver.get('https://br.tradingview.com/symbols/LTCBRL')
wait(driver, 10).until(
    EC.presence_of_element_located((By.CLASS_NAME, 'tv-symbol-header-quote__value'))
)

value = driver.find_element_by_class_name('tv-symbol-header-quote__value').text
print(value)

Comment: https://scrapy.org
Comment: você esta tentando pegar o objeto que possui o valor diretamente?
Comment: @RFL sim. Estou. É aquele valor 269.99, dentro da tag 269.97
Comment: Já pesquisei tanto e, li em perguntas de outros usuários que pode ser a questão do javascript.
Comment: Já tentou utilizar o Selenium? https://selenium-python.readthedocs.io
Comment: Já pesquisei sobre, ainda há pouco. Ainda vou precisar aprender como utilizar. Tentei pegar um código pronto apenas para teste mas não deu certo.
Comment: Se alguém me disse que a biblioteca selenium ou qualquer outra certamente funcionaria, eu a estudaria sabendo que a solução estaria lá... a questão é que já li bastante e, sem rumo me sinto perdido.
Answer: Tenta esse código, fiz aqui rápido pra testar e funcionou:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome(
    chrome_options = chrome_options,
    service_args = ['--verbose']
)

driver.get('https://br.tradingview.com/symbols/LTCBRL')
wait(driver, 10).until(
    EC.presence_of_element_located((By.CLASS_NAME, 'tv-symbol-header-quote__value'))
)

value = driver.find_element_by_class_name('tv-symbol-header-quote__value').text
print(value)

Comment: Caro Jones Vieira. Agradeço sua atenção. O código não funcionou comigo. Eu atualizei a minha pergunta colocando o código que você informou e a imagem de erro. Agradeço!
Comment: Eu instalei o drive do chrome pelo link a seguir
 https://sites.google.com/a/chromium.org/chromedriver/downloads    e funcionou pelo seu código. Obrigado
Comment: Que bom que funcionou amigo. Fiz um teste em um projeto que eu já possuía o driver, por esse motivo acabei esquecendo de informar a necessidade dele.

Python: Web Scraping em página dinâmica


Height of the embedded object HTML

Question: I encountered small problem with Height of embedded object in html.
I want to set the height and with of the object as per height and width of the browser. I am using following code Width sets properly but when i am trying to set height 100% it will not.
<object type="application/x-shockwave-flash" data="book.swf" width=100% height=100%>

it is working properly for width but not for height.
Is there any possible solution?
Answer: You need to set e.g.
 html, body { height: 100%; }

Otherwise, there's really nothing that the percentage in setting the height of the object would relate to. You may also wish to set
 html, body { margin: 0; padding: 0; }

Comment: Thank for answer. I tried this one but its still not working.
Comment: @chotai.mit, please post your code (a full example, not just one tag) and specify the browser(s) tested.
Answer: Try to write the actual Values of the width and height instead of procents for example :
<object type="application/x-shockwave-flash" data="../Desktop/final.swf" width="349" height="171">

Updated due to comment
If you want full browser size try this links:
http://www.kirupa.com/developer/mx2004/fullscreen.htm
http://www.webdesign.org/flash-swish/flash-tutorials/making-flash-taking-the-size-of-browser.15847.html
Comment: I want full height of browser.

Height of the embedded object HTML


Cannot recieve incoming email on recently transferred domain - all MX records updated and have proper status

Question: Domain Name: digiwhirl.com
Edition: Free edition
Affected Username/s: N/A
Issue Description: Cannot recieve incoming email on recently transferred domain - all MX records updated and have proper status
Steps to Reproduce (if applicable): Email bounces back if sent to any user on this domain. However, these users can send outgoing email to any other domain.
I changed the MX records for my domain for Google Apps about 30 hours ago.
    0 digiwhirl.com

1 aspmx.l.google.com

    5 alt1.aspmx.l.google.com

    5 alt2.aspmx.l.google.com

    10 aspmx2.googlemail.com

    10 aspmx3.googlemail.com

However, I am not able to get any incoming mail for domain.
I am able to send new email (outgoing).
I checked the status of my MX Records from a couple of lookup websites (Websitestuff & DNSStuff), and they say things are fine.
Updates:
On sending any email, the mailer-daemon responds back instantly with the following error:
Technical details of permanent failure:
Google tried to deliver your message, but it was rejected by the recipient domain. We recommend contacting the other email provider for further information about the cause of this error. The error that the other server returned was: 550 550-mail-ey0-f177.google.com [184.108.40.206] is currently not permitted to
550 relay through this server. (state 14).

----- Original message -----

MIME-Version: 1.0
Received: by 10.14.11.199 with SMTP id 47mr3192398eex.87.1302707326011; Wed,
13 Apr 2011 08:08:46 -0700 (PDT)
Received: by 10.14.48.67 with HTTP; Wed, 13 Apr 2011 08:08:45 -0700 (PDT)
X-Originating-IP: [220.127.116.11]
Date: Wed, 13 Apr 2011 20:38:45 +0530
Message-ID: <firstname.lastname@example.com>
Subject: asd
From: *obfuscated*<*firstname.lastname@example.com>
To: *obfuscated*<*email@example.com>
Content-Type: multipart/alternative; boundary=0016364c7cc369c94e04a0ce2f1e 4/13/11

Any help ?
Answer: While not the answer for Hrishikesh, I wanted to share another possibility for future visitors to this question.
I was encountering a similar problem after migrating DNS management to a BlueHost account.  It turns out there's a setting for the MX records "Email Routing" that you have to set the routing to "Remote Mail Exchanger" in order for the Google Apps email servers to accept the email.
Here's a screenshot of the correct setting that fixed it for me.
Comment: This sorted the problem for me.   I had the MX entries in correctly to route me mail to google apps and the setting was originally to "Automatically detect" and I was getting 550 errors.  Changing it to the remote "Remote Mail Exchanger" setting in Cpanel fixed it.

Thanks @philip-faulconer
Answer: Google's mail server is rejecting the message because, it would appear, that Google doesn't know they're supposed to be the authoritative recipient of those messages. The "clue" is the mention of relaying in the error message. That means that the recipient server is "seeing" the message as a relay attempt, not a local delivery attempt.
Are you certain that Google's service is configured for the correct domain name and all paid-up, provisioned, etc?
Comment: Yes, I've been poring over Google Apps settings for hours. All seems to be fine on their end.
Comment: @Hrishikesh Choudhari: I think you may have to attempt to get some support from Google. (Good luck getting a human, too... I've heard it's notoriously difficult to get human support from Google.) The rejection you're seeing is definitely coming from their server and is definitely because their server doesn't think it should be accepting the incoming messages.
Comment: @Evan: I've posted it on the Google Apps forum - http://www.google.com/support/forum/p/Google+Apps/thread?tid=38dce21618569eaa&hl=en - If not this, and not SF, then it surely seems as a dead end.
Comment: @Evan: BTW, how do I even *start* to get human support from Google ?
Comment: @Hrishikesh Choudhari: I've only ever been able to get human help from Google thru a salesperson and, then, only a larger account (300+ users).
Comment: @Evan: I got it working!!!

The first record - the one with priority 0 and pointing towards my domain - had been messing things up. It should not have been there in the first place.
Comment: @Hrishikesh Choudhari: Hmm-- I didn't see that one in there when I looked myself y'day.
Answer: Avoid bounced messages after changing MX records
http://www.google.com/support/a/bin/answer.py?answer=45679
"Any time you change your MX records, it can take up to 48 hours for your new records to propagate."
Answer: Most likely because you have 0 digiwhirl.com in your MX records and possibly have emails accounts on the same server swallowing the emails.
Comment: Thanks @steve.. You're right, I removed that particular MX record and things were rosy again.


Comparing multiple incidence rates

Question: I asked the following question on stack overflow yesterday:
Negative binomial function in R
Reading comment 2, I understand that I cannot use a negative binomial modeling approach (a Poisson model works, but I suspect the assumption of equal mean and variance is invalid-though I'm uncertain as to how I can test this with an offset) and compare the betas to a reference category. I've googled and looked through my books but cannot find any other approach to compare multiple incidence rates.
b <- data.frame(
  s=c(1800,539,490,301),
  pop=c(2900000,1327000,880000,268000),
  reg=c("A","B","C","D")
)

summary(pois.b<-glm(s~reg,offset=log(pop),data=b,family="poisson"))

So the question is : Is there any difference between the regions with regard to incidence?
Since the question yesterday was software related and today is more statistically flavored I figured it belonged here on cross-validated.
EDIT: Aug 11:
Since there are no other covariates here and the numbers are large I guess something as simple as
pairwise.prop.test(x=b$s,n=b$pop,p.adjust.method="bonferroni")

would get me a long way.
Answer: Given the limited data you have to work with you may only be able to address this question by incorporating additional assumptions (or data?) regarding the process behind these incidence rates, then doing some manual modeling.  Any statistical technique you use will be implicitly making such assumptions for you under the hood, so better to call those out and structure your analysis around them.
You have observations of discrete incidence counts.  The forms of some common discrete distributions encode the following assumptions:

Poisson: variance is equal to the mean
Binomial:  variance is smaller than the mean
Negative Binomial: variance is greater than the mean

You've already started down this road by ruling out a poisson model for the underlying process, saying variance = mean is not reasonable.   If the process is a contagion model then it might be very reasonable to assume variance is greater than mean, so a negative binomial distribution.
The next question is fitting the parameters of the selected model and then making your comparisons.  You could approach this in a couple of ways:

Empirically with your four data points - calculate mean and variance, then fit to distribution with old-fashioned algebra using distribution's mean and variance formulas. (You may need to standardize your data, for same reasons you'd use an offset in the glm.) Then calculate the probabilities of all 4 data points (and perhaps different combinations of 3) using the fitted model(s); lower probability suggests the process generating the incidence rates are not equivalent.
Use data from existing literature/research to fit the model; then test the probability of your incidence data occurring under that model.  Poor fit for one of the data points could suggest that it's incidence rate deviates from the standard process in some way (or a poor model of course if most or all do not fit well).

Such results are hardly conclusive (nothing can be with only this data imho), but just as importantly it can inform dialogue and further research into the process you're modeling.
Answer: If you only have the four data points, I think the best way to do this is with a G^2 test. You want to start by assuming the frequency is a binomial distribution (every person in the population has the condition with probability p). And your null hypothesis is that p_1=p_2=p_3=p_4.
So the overall mean is (1800+539+490+301)/(2.9m+1.327m+.88m+.268m)=0.000582.
Your expected cases in each group are 1688.7, 772.7, 512.4, and 156.1. You can calculate the G^2 statistic, but the answer I get is 192.8, which is chi-squared(3) under the null hypothesis. This is a very low p-value, so you'd reject the null and say that yes, you can be quite confident that the incidence is different between these locations.
In particular that last location is considerably higher than the other three, so that is contributing heavily to the low p-value. You can repeat this analysis for the other three and you may get something a bit different, but that is an exercise to the reader :-)
HTH
ETA: the DF is 3, not 1, as Yves pointed out in the comments.
Comment: This is a Likelihood-Ratio test. A LR test works also
for the Poisson model where the expectation of $S$ is assumed to be $\lambda \times \text{Pop}$. The null hypothesis is then $\lambda_{\text{A}} = \lambda_{\text{B}}
= \lambda_{\text{C}} = \lambda_{\text{D}}$.
LR could also work for overdispersed the Negative Binomial
case, but more data would be required to estimate the
two parameters (using a non-canonical glm link).
Comment: In this LR test, I think that the number of degrees of freedom to use is 3 = 4 - 1, since the resticted 'null' model has 1 df while the unrestricted has 4 df, one by region.
Comment: Would it not be easier to just use - prop.test(x=b$s,n=b$pop) - and then use -pairwise.prop.test(x=b$s,n=b$pop,p.adjust.method="bonferroni")- to determine the individual differences?
Comment: That ought to work too. That test I believe uses Pearson's Chi-Squared which is asymptotically equivalent to the G^2. If you want to test that the first three are equal, you'll have to just omit the fourth one to get an overall p-value.

Comparing multiple incidence rates


php call inside javascript

Question: I want to call java script in my PHP file but it in not working. I am in confusion because when i combine whole code in one single php file it works fine but again when i split the codes in two pages like test.php and upload.js and when i am calling the .js file in .php it don't works.I have done various search but i am not getting what i needed. Can someone figure it where i am missing what.
here is the sample code of test.php

here is the js function
Comment: Please post code as text, not images.
Comment: You should use ajax.
Comment: Thanks, but please use the `edit` link under your question to add the code to the question. Don't put it in the comments where it is hard to read.
Comment: its displaying error so can you please help by seeing the code?
Comment: @jabirkhan please post the error.
Comment: @Rambarun Komaljeet  there is no error shoen by code. but what i get i a pop up with what i have written in echo.
Answer: I'm not sure I follow exactly what you are trying to do, but PHP is executed server side, Javascript is executed client side.
If you have a PHP file such as:

then the PHP is executed before anything is sent to the browser. The browser gets:

So if you have javascript trying to call a PHP function after the page has been sent to the browser, it just won't work. Browsers can't execute PHP. You might want to look into AJAX or similar to send a request back to your server, which can then execute PHP code.
It might help if you could post all the various versions of code so we can see what you are attempting.
Answer: Separate JS files will not be able to read any PHP code. What you can do is setup all the values you need inside your PHP code so that you can access it in any separate JS file. One way to do this is to setup a global namespace/variable and hook into browser window object.
// upload.js

function callphp() {
   var result = window.MyJSValues.result;
}

// test.php
...
<?php
function php(){
   return "Welcome to Javascript";
}
?>

...
<button onclick="callphp()">Test</button>
...

Comment: thank u i will be going through it.

php call inside javascript


Four dimensional field over complex numbers

Question: A guy in Facebook claims he's come up with an algebraic field extension to the complex plane. He's defined the unit multiplications as $i^2=-1$, $j^2=i$ and $k^2=-i$. This implies that $ij=ji=k$, $ik=ki=-j$ and $jk=kj=-1$.
Furthermore complex numbers are seemingly a subset of this space, since each complex number $z = a + bi$ can be represented as $a + bi + 0j + 0k$.
So far I've checked that both addition and multiplication in this space are indeed associative and commutative, the addition and multiplication are distributive, and that $0$ and $1$ are the additive and multiplicative inverses respectively. I've yet to find an example of a non-inversible element.
Could someone help explain what's going on?
Comment: It's well-known that $\mathbb{C}$ is algebraically closed, so there are no non-trivial algebraic field extensions of $\mathbb{C}$.
Comment: Yes, but the proof is not very intuitive for a layman.
Comment: How does $i^2=-1$, $j^2=i$ and $k^2=-i$ imply that $ij=ji=k$? Could you not also have $ij=ji=-k$?
Comment: Yes. It's either $ij = k$ or $ij = -k$. The guy in Facebook chose the former.
Answer: Your Facebook guy seems to have stumbled upon some interesting identities among $8$-th roots of unity. To wit,
$$
j = e^{\pi i/4} = \tfrac{\sqrt{2}}{2} (1+i)
\qquad \text{and} \qquad
k = e^{3\pi i/4} = \tfrac{\sqrt{2}}{2} (-1+i)
$$
satisfy all of your identities within $\mathbb{C}$. (Notice that $i = j^2$ and $k = j^3$.) This had to be the case since $\mathbb{C}$ is algebraically closed. This means that any $\mathbb{R}$-linear combination of $1, i, j, $ and $k$ can actually be expressed just in the span of $1, i$.
Note: the pair $-j, -k$ would also work.
Answer: If $j^2=i$, then $j$ is a squareroot of $i$. This implies that $j\in \mathbb{C}$ as $\mathbb{C}$ is algebraically closed. Furthermore, if $ij=k$, then $k\in \mathbb{C}$ as well. This is not an extension, there are no elements being added.
Comment: I too noticed that $j$ is another root for $z^2=i$, but is this a problem? Even in Hamilton quaternions $j^2=-1$ which does not imply that $j=i$.
Comment: @EsaLindqvist In that case, we have $(j-(1+i)/\sqrt2) (j+(1+i)/\sqrt2) = i-i = 0$, so both $j-(1+i)/\sqrt2$ and $j+(1+i)/\sqrt2$ are zero divisors, thus noninvertible.
Comment: @EsaLindqvist In a *commutative* integral domain a quadratic can have at most two zeros. Hamilton quaternions are not commutative. Indeed, $x^2=-1$ has infinitely many solutions in $\Bbb{H}$. See [this short exposition by Arturo Magidin](https://math.stackexchange.com/a/122953/11619) for an explanation as to why commutativity plays a role here.
Comment: Or alternatively, what would be the implications if we were to suppose that $z^2 = i$ had more than two solutions?
Comment: No one's mentioned this yet: you **can** interpret this as a 4D algebra (in two different ways), or even an 8D algebra, at the cost of no longer having a field. For instance, ignoring $k$ for the moment, you can interpret adjoining-$j$-satisfying-"$j^2=i$" as the algebra $\Bbb C[j]/(j^2-i)$, which is equivalent to $\Bbb C\oplus\Bbb C$.
Comment: Precisely, your facebook guy declares this thing to be a field extension (so in particular, it needs be compatible with all algebraic equations). The quaternions are not a field, as such you really can have multiple (more than the degree) roots to the equation $z^2+1=0$ which are independent ($i,j,k$).
Comment: Intuitively this construction feels like a four dimensional space, but it's not. Is there some graphic or layman's explanation that would make it more clear what is actually happening in this construction?
Comment: @JyrkiLahtonen considering the fact that Hamilton quaternions are defined with unit vectors such that $i^2 = j^2 = k^2 = ijk = -1$, which incidentally _implies_ that they are not commutative (as is easily proven elsewhere). So the underlying assumption already _is_ that there are several roots to $z^2 + 1 = 0$.
Comment: @EsaLindqvist in tessarines (which are 4D) any quadratic has up to 4 roots. Not a big problem, but it is not a field (has null elements).
Answer: This is not an answer but an answer to some comments which is simply too long to be a comment itself:

Intuitively this construction feels like a four dimensional space, but it's not. Is there some graphic or layman's explanation that would make it more clear what is actually happening in this construction?

I do not have a graphical explanation. The crucial point indeed is that the space is not four dimensional. If you are familiar with group presentations, a very similar issue occurs. Suppose you have a group generated by a bunch of elements ($a,b,c$) and you are giving a bunch of relations in between those elements ($a^2b=cb, \dots$). It is possible that you have so many relations that one does not really need all generators (for example $a^2b=cb$ implies that $a^2=c$ and thus $c$ is redundant). In this you at first might be tempted to think that this group needed three generators, but actually less suffice.
Your facebook guy did something similar. At first glance it looks like you need 4 independent vectors te express everything, but these vectors are really not independent. That's the crux of the current story.

Or alternatively, what would be the implications if we were to suppose that $z^2=i$ had more than two solutions?

If $z^2-i=0$ has more than two solutions, you cannot be working in a field. Indeed, you can easily prove that any polynomial $P(X)\in K[X]$ of degree $n$ over a field $K$ cannot have more than $n$ roots. The proof is straightforward as soon as you have the division algorithm for polynomials over a field.
Edit: I'll include a proof of the latter statement. Let $P(X)\in K[X]$ be a polynomial. We can write $$P(X)=\sum_{i=0}^na_iX^i$$ with each $a_i\in K$ and $a_n\neq 0$. First note that we may assume that $a_n=1$ by multiplying the polynomial by $a_n^{-1}$ (here I use that $K$ is a field). Furthermore, doing so does not change the roots of $P(X)$ (that's a claim that you can prove as an exercise).
Now I claim the following: If $c\in K$ is a root of $P(X)$ (i.e. $P(c)=0$), then $$P(X)=(X-c)Q(X)$$ for some polynomial $Q(X)\in K[X]$ with $\deg(Q(X))=\deg(P(X))-1$. Indeed, by the division algorithm for polynomials, one can write $$P(X)=(X-c)Q(X)+R(X)$$ where $Q(X),R(X)\in K[X]$ and $\deg(Q(X))\leq \deg(P(X))$ and $\deg(R(X))<\deg(P(X))=1$. By assumption, $P(c)=(c-c)Q(c)+R(c)=R(c)=0$. On the other hand, $\deg(R(X))=0$ and thus $R(X)=0$ as it is a constant polynomial. Thus $P(X)=(X-c)Q(X)$ as required.
Hence we now showed that if $c$ is a root of $P(X)$, then we find that $P(X)=(X-c)Q(X)$ with $\deg(Q(X))=\deg(P(X))-1$. Now assume that $P(X)$ has more roots than its degree. Iterating the above procedure, you find that $P(X)=(X-c_1)(X-c_2)\dots (X-c_m)Q(X)$ with $m>\deg(P(X))$, but then $\deg(P(X))\geq m$, a contradiction!
Comment: @EsaLindqvist Correct. A final remark may be that if, instead of using all the real coefficientsin the proposed $a+bi+cj+dk$ construction, we restrict the coefficients $a,b,c,d$ to **rational** numbers, then we do get a 4-dimensional field extension over $\Bbb{Q}$! This may explain why your FB-friend could not easily find zero divisors. We absolutely need that $\sqrt2$ to make an appearance in at least one of the coordinates. Topology (more precisely, the completeness of the reals) makes a huge difference here, severely tying our hands.
Comment: Oh wow. That's actually quite cool.
Comment: Thanks. I have a hunch that this is a direct implication from the fundamental theorem of algebra.
Comment: Which part do you mean?
Comment: That in complex plane, each polynomial has at least one root in the plane. You are proposing that each polynomial has at most $n$ roots, where $n$ is the degree of the polynomial. So I suppose that there are some implications between the two.
Comment: See my edit for a proof of the claim. In any field, a polynomial cannot have more roots than its degree. The fundamental theorem of algebra says that any polynomial over $\mathbb{C}$ has precisely as many roots (with multiplicity) as the degree of the polynomial. That's a much stronger statement than the first.
Comment: Alright, thanks! I think this suffices to convince the Facebook guy.
Comment: @EsaLindqvist It may be worth emphasizing that if we drop commutativity, then the argument fails at the point where Mathematician42 calculates
$$P(c)=(c-c)Q(c)+R(c).$$ Without commutativity we don't have the rule that a polynomial factorization $P(x)=(x-c)Q(x)$ implies the same for the values at a point. In other words, we may have $P(d)\neq (d-c) Q(d)$. Hamiltonian quaternions offer an example. There we have $x^2+1=(x-i)(x+i)$, but
$$j^2+1=0\neq (j-i)(j+i).$$
Comment: Thanks @JyrkiLahtonen. So in essence if we assume that this "four" dimensional space is commutative, we necessarily prove that it is, in fact, just the plain old complex field.
Answer: You're looking at the extension $\Bbb{C}\subset\Bbb{C}[j,k]$ where $j$ and $k$ satisfy $j^2=i$ and $k^2=-i$. The key is that you are requiring this to be an extension of fields. Over a field, a polynomial of degree $d$ has at most $d$ roots. As $j$ and $k$ are zeros of $X^2\pm i\in\Bbb{C}[X]$, and we can find two roots of both quadratics in $\Bbb{C}$, it follows that $\Bbb{C}[j,k]$ is isomorphic to (a subfield of) $\Bbb{C}$.
More explicitly, we can find the polar forms of these roots from the fact that $\pm i=e^{\pm\tfrac{\pi}{2}i}$. It follows that
$$j=\pm e^{\tfrac{\pi}{4}i}\qquad\text{ and }\qquad k=\pm e^{-\tfrac{\pi}{4}i},$$
because these four complex numbers are precisely the roots of $X^2\pm i$.
Similarly we could find the Cartesian forms of these roots by solving $(a+bi)^2=\pm i$. This is equivalent to the simultaneous equations
$$a^2-b^2=0\qquad\text{ and }\qquad 2ab=\pm1.$$
The former implies that $b=\pm a$ and hence the latter reduces to $2a^2=\pm1$, or equivalently $a=\pm\sqrt{\pm\tfrac12}$, which we can express more concisely as $a=i^k\tfrac{1}{\sqrt{2}}$. Tracing our steps back then shows that
$$j=\pm\frac{1}{\sqrt{2}}(1+i)\qquad\text{ and }\qquad k=\pm\frac{1}{\sqrt{2}}(1-i).$$
Either way we see that $\Bbb{C}[j,k]$ is isomorphic to a subfield of $\Bbb{C}$, and hence isomorphic to $\Bbb{C}$ itself.


Wrong constant value in C

Question: I am trying to use 256 as a constant in C with #define. That equals 255 + 1 (which is 0xff + 1). And since in limits.h, UCHAR_MAX is 255, 256 should be equivalent to UCHAR_MAX + 1. So I write:
#include <limits.h>
#define BASE_NUM ((int)UCHAR_MAX)+1

So, when I do printf("%f",1000.0/(float)BASE_NUM);, it prints 4.921569, which is wrong (it would only be correct if BASE_NUM was 203.187).
However, by writing printf("%f",1000.0/((float)UCHAR_MAX+1));, I get 3.906250 as the output, and it is indeed correct. Therefore, BASE_NUM must not be equal to 256, but astonishingly, printf("%d",BASE_NUM); prints 256, which is clearly a contradiction, as BASE_NUM must not actually be 256.
I guess it has something to do with an overflow when I do the sum at the definition of the constant, but I really can't see what the problem exactly is, given that I am casting UCHAR_MAX to an int before adding anything to it, so there should be no overflow.
Answer: Wrap your #define in another set of parenthesis:
#define BASE_NUM (((int)UCHAR_MAX)+1)

Explanation:
Whenever you're having trouble with macros, just copy-paste their definition tho wherever you're using them and then evaluate from there:
printf("%f", 1000.0 / (float) ((int)UCHAR_MAX) + 1);

First, UCHAR_MAX is cast to an int and becomes 255. (here the cast is unnecessary as the constant 255 is already treated as an int by the compiler).
Then it is cast to a float and becomes 255.0.
Then, because division takes precedence over addition in C, 1000.0 is divided by 255.0
And finally 1 is converted to a float, becomes 1.0, and gets added to the result of the division (1000.0 / 255.0 + 1.0) == 4.92.
Comment: Anyone is free to nominate the question for reopening if they feel the closure was inappropriate.  In general (at least as far as I'm concerned) (a) a "duplicate" question needn't match exactly as long as the answer is the one the questioner needs, and (b) marking a question as a duplicate is in no way a criticism of the questioner for not having found that prior question; it merely says "here's your answer", and keeps people from wasting time re-answering.
Comment: On a side note flagging your question as a duplicate was a stupid decision by whoever did it.
Comment: Indeed, your explanation solved the problem, thanks a lot! I personally don't think this is a duplicate, either, as I tried searching before and didn't find anything like my question, but I guess there may be another related question.
Comment: Please accept the answer if it did indeed help you! Also, yeah, your question being a duplicate doesn't make sense. You had a problem and you weren't aware of the cause, whereas the author of the linked question was asking exactly about the need for parenthesis inside of macros.
Comment: Also there are often questions that often have trivial superficial - and wrong answers and often a better way in the canonical duplicate.
Comment: everything relates to your issue is answer in the other question, so definitely it's a duplicate. You couldn't find it because you used the wrong keyword. But next time read [read through the whole macro section in your C book before asking](https://stackoverflow.com/q/562303/995714)
Answer: Preprocessor left your printf like this:
printf("%f\n", 1000.0/(float) ((int)(0x7f * 2 + 1))+1);

which is interpreted as: (1000.0/UCHAR_MAX) + 1

Wrong constant value in C


Product of i.i.d. random variables uniformly distributed on $(-1,1)$ converges almost surely to $0$

Question: Let $(\Omega,\mathcal{F},P)$ be a probability space and $(X_n)$ i.i.d. random variables with uniform distribution on $(-1,1)$. If $Y_n=X_1\ldots X_n$, prove that $(Y_n)$ converges to $0$ a.s.
Comment: Still another approach is to note that $E\left(\sum\limits_n|Y_n|\right)=\sum\limits_nE(|X_1|)^n$ is finite since $E(|X_1|)<1$ hence the series $\sum\limits_n|Y_n|$ is finite almost surely hence $Y_n\to0$ almost surely.
Comment: Another approach than the two valid ones already posted on the page is to note that $\log|Y_n|$ is the sum of $n$ i.i.d. random variables $\log|X_k|$, each with mean $E(\log|X_1|)<0$, hence the law of large numbers ensures that $\frac1n\log|Y_n|$ has a negative almost sure limit--and this is more than enough to get the desired conclusion.
Comment: And yet another one (the thing is a goldmine...): since $(|Y_n|)$ is almost surely decreasing, it converges almost surely to some random variable $L$; since $Y_{n+1}=X_1Y'_n$ where $(Y'_n)$ is distributed as $(Y_n)$ and independent of $X_1$, $|Y_{n+1}|\to|X_1|\cdot L'$ almost surely, where $L'$ is distributed as $L$ and independent of $X_1$ hence $E(L)=E(|X_1|\cdot L')=E(|X_1|)\cdot E(L)$, which implies $E(L)=0$ because $E(|X_1|)<1$, hence $L=0$ almost surely since $L\geqslant0$ almost surely by construction.
Comment: @Did Nice! ${}{}{}{}$
Comment: @Did, very good (multi)approaches to the task! Great job!Thanks a lot!
Comment: Tools of the reals, applied to ramdom variables / distributions. Great job @Did!
Answer: By the Borel-Cantelli lemma, if the series
$$
\sum_{n=1}^\infty P\{|Y_n|>\varepsilon\}
$$
converges for each $\varepsilon>0$, $Y_n\to0$ almost surely as $n\to\infty$. Using Chebyshev's inequality,
$$
\sum_{n=1}^\infty P\{|Y_n|>\varepsilon\}
\le\frac1{\varepsilon^2}\sum_{n=1}^\infty\operatorname E|Y_n|^2
$$
since $\operatorname EY_n=0$. By independence,
$$
\operatorname E|Y_n|^2=\operatorname E|X_1|^2\ldots\operatorname E|X_n|^2.
$$
We have that
$$
E|X_1|^2=\frac{(1-(-1))^2}{12}=\frac13.
$$
Hence,
$$
\sum_{n=1}^\infty P\{|Y_n|>\varepsilon\}
\le\frac1{\varepsilon^2}\sum_{n=1}^\infty\biggl(\frac13\biggr)^n<\infty
$$
for each $\varepsilon>0$ and $Y_n\to0$ almost surely as $n\to\infty$.
Comment: @ClementC. The Wikipedia page for Markov's inequality gives a more general version: if $\phi$ is a monotonically increasing function from the nonnegative reals to the nonnegative reals, then $P(|X| \geq a) \leq \frac{E[\phi(|X|)]}{\phi(a)}$.  Source: https://en.wikipedia.org/wiki/Markov%27s_inequality
Comment: Yes, I saw that after the edit... the appearance of the squares makes "logical" sense if the idea was to use Chebyshev, as it's now clear it was (vanilla-Markov, as simpler/requiring less assumption on the r.v., seemed the natural choice when i read your answer, and then I was intrigued by the choice of applying it after the squaring -- again, this is completely valid, but seemed to me like an unnecessary step.) Without the squaring, you'd get $\frac{1}{2}$ instead of $\frac{1}{3}$ (and $\frac{1}{\varepsilon}$ instead  of $\frac{1}{\varepsilon^2}$), and everything goes through as well.
Comment: Why do you have squares appearing for Markov's inequality?(there would be if you consider $\mathbb{P}\{Y_n^2 > \varepsilon^2\}$, which you can (even if it does not add much to the argument); but then the squares are within the expectation, and so you should compute $\mathbb{E}[X_1^2]$, not $\mathbb{E}[\lvert X_1\rvert]$.)
Comment: That is true -- and easy to show from the "regular" Markov, but you don't need it, really. $\frac{\mathbb{E}[\lvert Y_n\rvert]}{\varepsilon}$ would do the job as well. (My comment, besides the typo, was mostly to ask if there was a specific reason to choose to square the quantities.)
Comment: @ClementC. By Markov's inequality I mean this general inequality pointed out by user46944 and Chebyshev's inequality is a special case of Markov's inequality. I used the second moment since I knew the variance of a uniform distribution. I think other absolute moments would work too.
Answer: Hint: use the Borel—Cantelli lemma.
In  more detail: fix any $\varepsilon > 0$, and let $A_n=A_n(\varepsilon)$ be the event $\{ \lvert Y_n\rvert > \varepsilon \}$. By Borel—Cantelli, to show that $Y_n \xrightarrow[n\to\infty]{\rm a.s.} 0$, it is sufficient to show
$$
\sum_{n=1}^\infty \mathbb{P} A_n < \infty.
$$
In even more detail: (place your mouse over the gray area to reveal its contents)

 Since $\lvert Y_n\rvert \leq \varepsilon $ whenever at least one of the $X_i$ satisfies $\lvert X_i\rvert \leq \varepsilon$ (this is a sufficient condition, clearly not necessary), we have $$\mathbb{P} A_n  \leq \mathbb{P}\{ \forall\ 1\leq i \leq n,\ \lvert X_i\rvert > \varepsilon \} = \prod_{i=1}^n \mathbb{P}\{ \lvert X_i\rvert > \varepsilon \} = (1-\varepsilon)^n.$$ It follows that $$ \sum_{n=1}^\infty \mathbb{P} A_n \leq \sum_{n=1}^\infty (1-\varepsilon)^n < \infty. $$
Comment: Thanks a lot, great job! Just a minor thing (for sake of completeness), that doesnt't change anything of course: $P(|X|>\varepsilon)=1-\varepsilon$.
Comment: @NikolaosSkout True, I forgot to multiply by the density, $\frac12$. Fixed.


Adicionar espaço a cada letra em MAIÚSCULA

Question: Como dar espaço usando PHP quando começar uma palavra em maiúsculo, por exemplo, a string oiEusouMuitoLegal resultar em oi Eusou Muito Legal.
Answer: Para fazer isso você pode utilizar a seguinte regex, /(?<!\ )[A-Z]/.
$str = "oiEusouMuitoLegal";
echo preg_replace('/(?<!\ )[A-Z]/', ' $0', $str);
// oi Eusou Muito Legal

Ideone
O trecho (?<!\ ) é uma afirmação de que irá certificar-se que não adicionar um espaço antes de uma letra maiúscula que já tem um espaço antes dele.
Fonte
Comment: Quando vamos ter uma expressão regular para nos tirar um cafézito fresquinho pela manhã? ;) +1
Comment: @Zuul, avisem-me que estou a precisar dela!
Comment: É só um palpite não testado, mas acho que a regex `([^^ ])([A-Z])`, com replace pra `$1 $2` também funciona.
Answer: Já tens uma resposta que sem dúvida é o caminho a seguir, fica um exemplo para quem não quer usar expressões regulares:
$texto = "oiEusouMuitoLegal";

$letras = preg_split('//', $texto, -1, PREG_SPLIT_NO_EMPTY);

foreach ($letras as $letra) {

    if (ctype_upper($letra)) {
        $texto = str_replace($letra, " $letra", $texto);
    }
}

echo $texto;  // Saída: oi Eusou Muito Legal

Exemplo no Ideone.

Código lida com o problema na pergunta e ilustra a complexidade de trabalhar uma string sem fazer uso de expressões regulares para operações baseadas num padrão repetitivo.
Answer: echo preg_replace('/\B[A-Z]/', ' $0', "Olá oiEusouMuitoLegal! Tem Dias...");
//Olá oi Eusou Muito Legal! Tem Dias...


Make API call to Azure Service Management - how do I send the .pfx file in the call?

Question: I can successfully use Postman to make a call to  https://management.core.windows.net//services/hostedservices because I placed a .cer in Azure and a .pfx in my keystore.  Does anyone know how to make this call without using Postman?  How do I get the .pfx successfully in the call?
Java or JS answers would be helpful.
Comment: I wrote a blog post long time back on consuming Service Management API using Java. You can read the post here: http://gauravmantri.com/2013/08/25/consuming-windows-azure-service-management-api-in-java/. See if this helps.
Answer: Summarizing @GauravMantri blog, please the steps below.

Create a self-signed certificate with Java tool keytool, command ?<java-path>/keytool -genkeypair -alias <domain> -keyalg RSA -keystore <keystore-filename>.jks
-keysize 2048 -storepass "<password>"
Export the management certificate, command <java-path>/keytool -v -export -file <path like D:>\<certname>.cer -keystore <keystore-filename>.jks
-alias <domain>
Upload the management certificate in MANAGEMENT CERTIFICATES tab of SETTINGS tab on Azure classic portal.

Create the Service Management Client with the certificate jks file using Azure SDK for Java.
import java.net.URI;

import com.microsoft.windowsazure.Configuration;
import com.microsoft.windowsazure.core.utils.KeyStoreType;
import com.microsoft.windowsazure.management.configuration.ManagementConfiguration;
import com.microsoft.windowsazure.management.compute.ComputeManagementService;
import com.microsoft.windowsazure.management.compute.ComputeManagementClient;
import com.microsoft.windowsazure.management.network.NetworkManagementService;
import com.microsoft.windowsazure.management.network.NetworkManagementClient;

String uri = "https://management.core.windows.net/";
String subscriptionId = "<subscription-id>";
String keyStorePath = "<path>\<keystore-filename>.jks";
String keyStorePassword = "<password>";

Configuration config =  Configuration config =     ManagementConfiguration.configure(
            new URI(uri),
            subscriptionId,
            keyStoreLocation, // the file path to the JKS
            keyStorePassword, // the password for the JKS
            KeyStoreType.jks // flags that I'm using a JKS keystore
          );
ManagementClient client = ManagementService.create(config);
// Or other management clients, such as ComputerManagementClient
// ComputeManagementClient computeManagementClient = ComputeManagementService.create(config);


Load "Vanilla" Javascript Libraries into Node.js = 'Unexpected token export'

Question: Building on related issue: Load "Vanilla" Javascript Libraries into Node.js
I'm trying to load a 'Vanilla' Javascript library 'rsa.js' into NodeJS, using the method described by Chris W. in the question above. In essence I've created a custom node_modules directory like this:
./node_modules/rsa/rsa-lib/rsa.js
./node_modules/rsa/rsa-lib/README
./node_modules/rsa/index.js

Only problem is, compiling the module fails on the last line of rsa.js:
undefined:836
export default rsa;
SyntaxError: Unexpected token export

rsa.js
var rsa = {};
 (function(rsa) {

   ...

})(rsa);
console.log("rsa",rsa);
export default rsa;

index.js
var fs = require('fs');

// Read and eval library
filedata = fs.readFileSync('./node_modules/rsa/rsa-lib/rsa.js','utf8');
eval(filedata);

/* The rsa.js file defines a class 'rsa' which is all we want to export */
exports.rsa = rsa

Any suggestions how to fix this problem?
Answer: The error 'Unexpected token export' is caused because the library is using
export default thingToExport;
instead of
module.exports = thingToExport
This is an ES6 feature not supported by Node (yet), so when Node tries to run the code, it throws an error.
How to solve: try modifying the last line of the library so it says module.exports = rsa;.
I should add, though, that eval is not a good way to load a library into your own code. That is what require is for. If you have installed this library with npm i and it is in your node_modules, you should be able to load it into your code with var rsa = require('rsa');.
Again though, if you're not transpiling the code, it may have problems with export default, so you will probably want to change that to module.exports either way.
Comment: Brilliant, swapping it for module.exports = rsa; did the trick. Also good point about the eval(), though not sure you can 'require' a vanilla javascript library...
Comment: You can require your own JS files using `require('./path/to/file.js')`, so I think you should be able to `require` someone else's javascript

Load “Vanilla” Javascript Libraries into Node.js = 'Unexpected token export'


Using Flickr API + CURL to get image URL & Caption

Question: How can I make a simple CURL request to that Flickr API that does the following:
Get the X number of most recent photos URLs + captions from collection Y?
Where "X" is the number of photo URLs and "Y" is the collection name.
This code is part of an existing application and I'm not allowed to use scripts like PHPFlickr for help.
Answer: what is the problem of using a already tested PHP api, you probably will need care about lot of stuff as authentication, size, etc. doing that by your own
Edit:
I will put some simple code using curl. hope helps you. I grabbed the idea from here
<code><?php
$ch = @curl_init();
@curl_setopt($ch, CURLOPT_URL, "http://api.flickr.com/services/feeds/groups_pool.gne?id=675729@N22&lang=en-us&format=json");
@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:18.104.22.168) Gecko/20061204 Firefox/126.96.36.199");
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
@curl_setopt($ch, CURLOPT_TIMEOUT, 10);

$response       = @curl_exec($ch);
$errno          = @curl_errno($ch);
$error          = @curl_error($ch);

if( $errno == CURLE_OK) {
    $pics = json_decode($response);
}

?>
</code>
Comment: I'm writing code that is part of another application. Although I would love to do it, I'm not permitted to use an existing tool like PHPFlickr.
Comment: I'm sorry, but if you are asking here about some "advice" about code and you use it, isnt the same as download the library, which is on "GNU Lesser General Public License" license and see how it works and then make your own code? regards
Comment: I've seen examples where JavaScript can be used to request JSON that contains the data I'm looking for. I was hoping that somebody knows a  easy way to pull this simple data with CURL. This way, I don't have to spend all weekend trying to reverse engineer PHP Flickr :)
Comment: I just made an edit, my basic steps were setup curl in get mode and added a user-agent. saludos
Comment: Great! That did the trick. Now I will figure out how to specify a collection and I'm done.


Java8 lambda for checking two conditions

Question: I have the following code snippet which I would try to change to the lambda function.
if(catList != null && catList.size() > 0) {
    animalType = AnimalType.CAT;
    HttpEntity<List<?>> request = new HttpEntity<>(catList, headers);
    response = restTemplate.postForObject(apiUrl, request, String.class);
} else if(dogList != null && dogList.size() > 0) {
    animalType = AnimalType.DOG;
} else {
    return;
}

Somehow I have written like as shown below, but don't know to incorporate the dogList checking the condition
Optional.of(catList)
    .map(catList -> {
        ....
    })
    .orElse(return); //<------ THIS IS NOT POSSIBLE

Can anyone please help me with this
Comment: stop shoehorning everything into optionals (which btw mostly designed for using as a clearer return type in your api) and lambdas
Comment: what is the signature of the resource/service method that you're using? Does it expect the various lists and either of them would be `null` is a must?
Comment: @Naman its a void function....I use `response` later for some other business logic within the same function
Comment: Would actually be better if you can update the question with the method and entities that are dealt with in the code segment shared by you.
Answer: You can have an other Optional inside of the first Optional
Optional o = Optional.of(catList)
                     .map(catList -> ...)
                     .orElse(Optional.of(dogList)
                                     .map(dogList -> ...));

Or other method using Stream if you can make the call to the service generic enough
Or other method using Stream#of
It will basically go through both lists, find the first that is not null (but you can add other conditions to your filter if you want) and apply the generic call to service.
Optional o = Stream.of(catList, dogList)
                   .filter(Objects::nonNull /*or other condition if you want*/)
                   .findFirst()
                   .map(list -> /*generic call to service*/);

And invoke it this way
if (!o.isPresent()) return;

Comment: in that case I think the first option is better right
Comment: Thanks for the reply, but I need to return to branch out of a control flow block and exit the method if both `catList` or `dogList` condition is not matching
Comment: @AlexMan I modified the answer, I'm afraid it's not possible in a single chain of method invocation
Comment: also how do we set the `animalType` in the second option using `Stream.of`
Comment: @AlexMan By making the method generic. For example, `if (list.get(0) instanceof Dog) animalType = AnimalType.DOG;`
Comment: @AlexMan Yes I'd prefer the first option if only for two lists, if more lists can come, then I'd choose the second one and refactor my code
Comment: I am getting an exception when I use the first option like this `Error:(40, 21) java: incompatible types: no instance(s) of type variable(s) U exist so that java.util.Optional conforms to com.example.demo.Cat`
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/194009/discussion-between-yassin-hajaj-and-alex-man).
Answer: It is not possible to exit a method using the Optional or any other class without either explicitly invoking return or throwing an exception. Usage of return inside a lambda expression is understood within the scope of the method implemented of the functional interface, hence there is no chance to do as your shown code.
There are basically two ways to achieve the desired behavior and keep Java language compliance.

Use return after obtaining a definitive result from Optional.
Here I might repeat an existing answer, but the best you can do is:
Optional<MyObject> optional = Optional.of(catList)
    .map(catList -> new HttpEntity<>(catList, headers))
    .map(httpEntity -> restTemplate.postForObject(apiUrl, request, String.class));

if (!optional.isPresent()) { return; }           // here the method execution is terminated

Checking against null or an Null Object might be a way to go as well.
Throw an exception using the Optional::orElseThrow allows the method terminates the method and throws an Exception. Unfortunately, it obliges an upper layer with a need to handle it or rethrow).
MyObject myObject = Optional.of(catList)
    .map(catList -> new HttpEntity<>(catList, headers))
    .map(httpEntity -> restTemplate.postForObject(apiUrl, request, String.class))
    .orElseThrow(MyObjectException::new);        // here the method execution is terminated

If the return parameter of the method is not void, the Optional might be used for the return type definition. The null check (or again a Null Object is a way) might be used there is the method called at:
 return Optional.of(catList)
        .map(catList -> new HttpEntity<>(catList, headers))
        .map(httpEntity -> restTemplate.postForObject(apiUrl, request, String.class))
        .orElse(null);

Comment: But how abt the `dogList` and the `animalType`
Comment: I am trying to create a generic lambda function for handling both catList and dogList instead of duplicating the logic


Examples of fields of characteristic 1

Question: I'm a beginner in this topic, so this question seems stupid, but I think it's a doubt many beginners can have.
I realized that I can't find examples of fields with characteristic 1, and as 1 is a prime number we can try to find examples of such fields.
I find a little bit strange this kind of field, it seems that it can have only the zero element, then it can't exist such fields
I said something wrong?
Thanks
Comment: Presumably characteristic $1$ would mean $1=0$. But the specification of a field says $1\ne 0$.
Comment: this should help: http://en.wikipedia.org/wiki/Field_with_one_element
Comment: @PatrickDaSilva Which specifications are these? Just about anywhere I look we require that $K\backslash\{0\}$ is an abelian group, and therefore contains a neutral element $1$.
Comment: @RafaelChavez: The word "prime," like other mathematical words, is subject to definition. Very few people in the field have called $1$ a prime. The lone serious exception is Legendre.
Comment: @PatrickDaSilva:  I believe that most definitions of field do not allow the one element ring. To check, one would have to go through a collection of standard books. For what it's worth, the Wikipedia entry for "field with one element" explicitly says it is not a field.
Comment: What convention are you using that considers $1$ a prime number?
Comment: Dear @Patrick, there is not one serious book or mathematician on this planet today claiming that the ring with one element is a field: I hereby challenge you to name a counter-example :-)
Comment: Dear @Patrick: I completely agree with you that it is interesting to analyze the axioms for "field", or for that matter of any mathematical structure. At the end of the day, however, we have to adopt the accepted definitions.
Comment: @Andre : The specifications of a field don't require that. Many authors assume $1 \neq 0$ because the only field satisfying $1 = 0$ is the zero field, so they leave it aside because it behaves differently with the other ones and we don't want to consider it.
Comment: @Georges : I am not saying it is *useful* to do so, I can even say it is *useless*. What I am saying is that you can remove a *very little subtlety* in the definition of a field and this unique zero-field will appear. This is why most people ask for $1 \neq 0$. I think it is nice to understand such things rather than just accepting the definitions mathematicians tell you.
Comment: @Amzoti then my mistake was to be considered 1 prime?
Comment: @AndréNicolas very interesting!!!
Comment: @André Nicolas : Damn wiki. :P But seriously ; if you do not ask that $F^{\times}$ is a group, but rather that it satisfies all its axioms beside non-emptiness, you get the same definition of a field except that $\{0\}$ satisfies it. We have discussed this in my Galois theory class, and we arbitrarily chose to remove $\{0\}$ from our definition of field.
Comment: It is interesting that definitions are arrived at democratically in that course. Luckily, the deinition arrived at was the usual one.
Answer: The fields of characteristic $p$ are such that "$p=0$" by handwaving. Therefore, if $1=0$, the only field you can expect is the zero field, which is indeed, as you stated, a bit strange, for it is the only field with this property. For every other field, $1 \neq 0$.
(EDIT : You can interpret my word "expect" in "the only field you can expect" this way : the definition of field that allows $1=0$ only adds the zero field to the possible fields, even though it is non-standard to do so, so we usually assume $1 \neq 0$ to get rid of this case. See the discussion in the comments for more details.)
Usually people do not consider $1$ as a prime, for it does not generate a prime ideal in the ring $\mathbb Z$. Now this again is a matter of definition ; we define the prime ideals those who satisfy some property and are not the whole ring. There are many other reasons why $1$ is usually not a prime, and you just found one of them. $1$ behaves significantly differently than the non-$1$ primes, so it is natural to leave it aside.
Hope that helps,
Comment: Maybe can be a subject of another question on MSE :P
Comment: Dear Patrick, I don't know why you have been downvoted, but I'll upvote you as a compensation.
Comment: Most likely the downvote was for the suggestion that $\{ 0 \}$ is a field...
Comment: The uniqueness of the factorization in prime numbers can be another reason why 1 is not a prime.
Comment: @Rafael : There are a thousand reasons not to consider $1$ as a prime, I didn't want to make a list. =P
Comment: Thank you it helped a lot!
Comment: @Rafael : It is possible that this question has already been asked. Otherwise, feel free to do so.
Comment: I modified the answer so that the downvoter may revise his downvote.
Comment: @ZhenLin : I added a discussion that explains in which sense I say that. And I obviously not mean it in the standard sense. What's wrong in that?
Answer: According to Alain Connes, characteristic 1 only really shows itself clearly when you deal with semirings (only a commutative monoid under addition) and semifields (semirings in which non-zero elements form a group under multiplication). The only finite semifields are the finite fields and the 2-element Boolean algebra B, with "or" and "and" for + and *. (Note - this is not the 2-element field F_2, which has exclusive or for +.)
Although B does not satisfy 1=0, it does satisfy 1+1 = 1. Hence any B-algebra is a semilattice under addition.
Comment: Can you provide a reference for your quote of Alain Connes?

Examples of fields of characteristic 1


k8s HPA change inits new pods when reducing max to above current pod count?

Question: Say I have 100 running pods with an HPA set to min=100, max=150. Then I change the HPA to min=50, max=105 (e.g. max is still above current pod count). Should k8s immediately initialize new pods when I change the HPA? I wouldn't think it does, but I seem to have observed this today.
Comment: Why would it initialize new pods after reducing the min? It should only terminate pods.
Comment: If usage metrics for your existing pods don't justify having more than the min replicas count from your HPA: eventually, kubernetes would remove pods. Although that won't be "immediate".
Answer: First, as mentioned in the comments, in your specific case some pods will be terminated if usage metrics are below utilization target, no new pods will be created.
Second thing it's absolutely normal that is takes some time to scale down replicas - it's because the
stabilizationWindowSeconds parameter is by default set to 300:

behavior:
scaleDown:
   stabilizationWindowSeconds: 300
   policies:
   - type: Percent
     value: 100
     periodSeconds: 15

So, if you have running HPA with configuration (min=100, max=150) for a long time, and you have changed to min=50, max=105, then after 300 seconds (5 minutes) your replicas will be scaled down to the 50 replicas.
Good explanation about how exactly stabilizationWindowSeconds works is in this document:

Story 5: Stabilization before scaling down
This mode is used when the user expects a lot of flapping or does not want to scale down pods too early expecting some late load spikes.
Create an HPA with the following behavior:
behavior:
 scaleDown:
   stabilizationWindowSeconds: 600
   policies:
   - type: Pods
     value: 5

i.e., the algorithm will:

gather recommendations for 600 seconds  (default: 300 seconds)
pick the largest one
scale down no more than 5 pods per minute

Example for  CurReplicas = 10  and HPA controller cycle once per a minute:

First 9 minutes the algorithm will do nothing except gathering recommendations. Let's imagine that we have the following recommendations

recommendations = [10, 9, 8, 9, 9, 8, 9, 8, 9]

On the 10th minute, we'll add one more recommendation (let it me  8):

recommendations = [10, 9, 8, 9, 9, 8, 9, 8, 9, 8]
Now the algorithm picks the largest one  10. Hence it will not change number of replicas

On the 11th minute, we'll add one more recommendation (let it be  7) and removes the first one to keep the same amount of recommendations:

recommendations = [9, 8, 9, 9, 8, 9, 8, 9, 8, 7]
The algorithm picks the largest value  9  and changes the number of replicas  10 -> 9

Another thing is that it depends which Kubernetes version, which apiVersion for the autoscaling are you using and which Kuberntes solution are you using. The behaviour could vary - check this topic on GitHub with a bug reports.
If you want to have scale down done immediately (not recommended in the production), you can setup following:
behavior:
    scaleDown:
      stabilizationWindowSeconds: 0
      policies:
      - type: Percent
        value: 100
        periodSeconds: 1

Also check:

Horizontal Pod Autoscaling in particular Example: change downscale stabilization window and Example: limit scale down rate
Configurable scale up/down velocity for HPA


Error of election polls for parliament

Question: Given a poll, where $N$ people were polled, and $n_i$ people voted for party $i$, so that: $$\sum{n_i} = N$$
If there are M parliament seats in total we can expect:
$$m_i = M\cdot\lim_{N\rightarrow\infty} (n_i/N)$$
To be the number of parliament seats party $i$ will have.
My question regards the error involved in this prediction:
What is it's error distribution and what is it's variance?
If the number of seats were not finite, I'd say that the distribution would be Poisson and each poll value should be $n_i \pm \sqrt{n_i}$, but since the sum is given, It would seem the errors must be correlated in some way.
Any ideas?
Comment: To make things more complicated, the number of seats is usually an integer, which could suggest that the seat allocation method used for fractions could have an effect.
Comment: @Henry - of course. The actual system used in my country is a variant of the [D'Hondt method](http://en.wikipedia.org/wiki/D%27Hondt_method), And I wouldn't even try writing the formula down. I just was trying to understand what the actual polling error is, as the papers don't seem to be very keen on explaining what "4.5% error" refers to.
Answer: If the polling population is infinite, the $n_i$ follow a multinomial distribution. If the population is finite, the $n_i$ follow a multivariate hypergeometric distribution. The Wikipedia pages have the variances and covariances for both cases.
Comment: Now that I think of it, the multivariate hypergeometric distribution gives me the opposite of what I'm looking for - It gives the chances of getting $n_i$ voters in the poll who will vote $i$ given $N_i$ total $i$ voters. What I'm looking for is the opposite: The chances of there being $N_i$ total voters, given $n_i$ voters in the poll who will vote $i$. How can I "invert" this distribution?

Error of election polls for parliament


How to determine if I'm running as a console app? (Delphi on Win32)

Question: I have a common unit that does some logging to GExperts Debugger and/or OutputDebugString. I am going to use it in a console app, so I want it to be able to output to stdout via writeln().
The main executable has {$APPTYPE CONSOLE} already, but I don't think that'll help me here. The logging routine will be called from several places:

the main console app, which will link to a BPL,
from another BPL that "requires" the first bpl, and.....
from a DLL that statically links the unit.

The BPLs and DLL will be built with no visibility to the {$APPTYPE CONSOLE} directive, so I can't use IFDEF conditional compilation.  The BPL and DLL need to be able to go either way, depending whether the main app is a regular winapp or console app.
One ugly solution that occurred to me is to use the name of the executable.  ex:
if (UpperCase(ExtractFileName(ParamStr(0))) = 'MYCONSOLEAPP.EXE')  then ...

But I hate to do that, as I could have other console apps...
I'd rather just have a magic function AmIAConsoleApp : boolean;
Is there anything like that?
I'm using Delphi2005 on this project.
Update: I see that I'm kind of a duplicate of this question, but I'd like to survey the Delphi folks to see if there's a better approach.
Comment: There were a couple of well-intended, helpful-looking answers suggesting the use of System.IsConsole.  They were deleted by the posters, but I felt that it was valuable to include in the discussion.  So here's why it won't work:  System.IsConsole returns true, according to the doc, "{ True if compiled as console app }".  I'm not compiling as a console app (well the main app is, but the DLL isn't).  So I had mixed results, depending on where the logger was being called from.
Answer: Call GetStdHandle(Std_Output_Handle). If it succeeds and returns zero, then there is no console to write to. Other return values indicate that a console is attached to the process, so you can write to it (although the console may not be the most desirable place to log messages in a console program since they'll interfere with the normal output). Something like this:
function IAmAConsoleApp: Boolean;
var
  Stdout: THandle;
begin
  Stdout := GetStdHandle(Std_Output_Handle);
  Win32Check(Stdout <> Invalid_Handle_Value);
  Result := Stdout <> 0;
end;

Comment: This answer also covers the case if the application is not of a console type but allocated one. So I think this is the correct answer even though the question is wrong (the ultimate aim is to output to console, not to find out how the executable is linked).
Comment: Cool - I'll give it a shot tomorrow. Thanks.
Answer: Use constructor injection to inject a logger at the time you create the instance. Here's a simple example.
Your proposed solution of testing whether the app is a console app works for only those two scenarios. The constructor injection solution is scarcely any more code and works anywhere you need output.
Comment: @Rudy, yes, that's what I mean.
Comment: Do you mean something along the lines of `X := TY.Create(MyLogger)`? and then the console app provides a logger that uses Writeln while a GUI app provides another one, or even nil? A good idea (although the term was new to me) I have used several times in such a situation (e.g. a lexer/parser that requires an ICharProvider: The console test app provides one that gets characters from a set of string constants, while the real app provides one that gets characters from the IDE editor).


Login without password

Question: I'm in a project where the main login form must not have a password field. The user will login with a username and selecting a Country. This country field is configured within the user profile.
So far, I can manage to log in users checking their username and the selected countries, but I can't find anything not to require a password for login.
This is my code.
function hdp_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block') {
    // Add country field to login form
    $form['pais'] = array(
      '#type' => 'select',
      '#title' => t('Pais'),
      '#options' => array(
        'Argentina' => t('Argentina'),
        'Chile' => t('Chile'),
        'Peru' => t('Peru'),
      ),
      '#required' => TRUE,
    );
    // Add validation to check country-username
    $form['#validate'][] = 'validacion';
  }
}

function validacion(&$form, &$form_state) {
  // Variables.
  $usuario_nombre = $form_state['values']['name'];
  $usuario_pais_seleccionado = $form_state['values']['pais'];

  // Search user countries by username. Username must not be duplicated.
  $uid = db_query("SELECT uid FROM {users} WHERE name IN ('$usuario_nombre')")->fetchField();
  if (!empty($uid)) {
    $paises = db_query("SELECT field_paises_value FROM {field_data_field_paises} WHERE entity_id IN ($uid)")->fetchAll();
    $paises_habilitados = NULL;
    foreach ($paises as $pais) {
    $paises_habilitados .= $pais->field_paises_value;
  }

  // Check if selected country is one of the user profile selected countries.
  $habilitado = strpos($paises_habilitados, $usuario_pais_seleccionado);
  if ($habilitado === false) {
    form_set_error('pais', 'Acceso denegado. Por favor revise su nombre de usuario y el país seleccionado.');
  }
}

Answer: If you don't require a password from your users, then you should:

Make the password form field not visible to the users (it is enough to set #access to FALSE)
Remove the form validation handlers that are not necessary

The form validation handlers that the user login block uses are the following:

user_login_name_validate() just checks the user account matching the username is not blocked
user_login_authenticate_validate() checks the entered password matches the one set for the user account using that username
user_login_final_validate() checks the user didn't enter too much times the wrong password

What you need to do is removing 'user_login_authenticate_validate' and 'user_login_final_validate' from the array $form['#validate'].
Remember also that your form validation handler needs to set $form_state['uid'], since that is the value used from user_login_submit() to load the user object from the database.
As additional notes:

Your code is making assumptions about where/how the field data are saved; in particular, it is assuming the field data are saved in the database currently used by the Drupal site, which is not necessary true, since field data could be saved in MongoDB. I would rather use the following code.
$uid = db_query("SELECT uid FROM {users} WHERE name = :account_name", array(':account_name' => $usuario_nombre))->fetchField();
if (!empty($uid)) {
  $account = user_load($uid);
  if ($countries = field_get_items('user', $account, 'field_paises')) {
    // I assume users can just select a single country.
    $country = array_shift($countries);
    if ($country != $usuario_pais_seleccionado) {
      // Show the error message.
    }
  }
}

You cannot use user_authenticate(), since that requires the account password, which is not saved in the database. The database contains the password hash.
The string passed to t() should contain words in English, since the function is used to translate from English to the language currently set for the site. (Pais is not an English word; probably you meant Country.)
Instead of WHERE name IN ('$usuario_nombre'), you should use WHERE name = :username. Input from users should not be used directly in SQL queries, as that is a security issue. (See SQL injection.)
Functions implemented by a module should always have their names prefixed by the module name.

Talking of security issues, I hope you are using the authentication method you described in a very restricted, controlled environment. I would not use it in a public site where everybody can create an account, especially if the username and the country selected from users are visible to everybody. Even in the case the country is not visible, getting the right username/country combination is much easier than finding the right username/password combination that allows you to log in.
Comment: Thanks Kiamlaluno. I manage to add `$form['pass']['#access'] = FALSE` and it worked. And i tried `$form['#validate'] = array('user_login_name_validate', 'validacion');` and it does not work and i think its because i don't know what to do with this line `$form_state['uid']`. I get 5 errors like `Undefined property: stdClass::$uid...`. Plus Drupal "login" a user without name...
Comment: `$form_state['uid']` is the user ID of the account that Drupal will load. It is used from [user_login_submit()](http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_login_submit/7).
Comment: kiamlaluno, i searched about login_submit, handler and $form_state and i can't understand too much. I tried `$form['#submit'] = 'kbza';function kbza($form, &$form_state) {
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;

  user_login_finalize($form_state);
}` as in user.module but it does not work. This is my first module and i'm not a developer, do you know any good tutorial about it? Thanks in advance.
Comment: You don't need to replace the form submission handler with another that does the same thing: If there is code that doesn't work, that is in your validation handler.
Comment: I have been reading, learning from and analysing the extra code you just put and i works fine. Even it works fine, Drupal won't log me in so i ended up erasing the validation function. Even if i erase it, Drupal logs the same error: `Notice: Undefined index: uid in user_login_submit() (line 2269 of \modules\user\user.module).` That line is `$user = user_load($form_state['uid']);` so i presume something about $form_state['uid'] is missing somewhere. Plus when you mention i have to remove `'user_login_name_validate'`, i think you meant `'user_login_authenticate_validate()'`.
Thanks 4 ur patience
Comment: Alright, after looking up user.module i found that 'user_login_authenticate_validate', which is not in my validation array, sets $form_state['uid'] when successful `$form_state['uid'] = user_authenticate($form_state['values']['name'], $password);`. I ended up adding `else { $form_state['uid'] = $uid; }` to the bottom of your code. Thanks for all the help you gave me. Remember to switch `'user_login_name_validate'` to `'user_login_authenticate_validate()'` (previews comment)
Comment: Yes, that is correct: It is `'user_login_authenticate_validate'` that should be removed from the array of validation handlers, not `'user_login_name_validate'`. You cannot use [user_authenticate()](http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_authenticate/7) as that requires the password, but you can set `$form_state['uid']` with the user ID you get from the database, when the country selected in the login block is the correct one.

Login without password


Accessing Remote files using HTTP from a web application

Question: we have a requirement where all file (text , image , PDF etc) uploaded in the Server1. Now we have a Java web application running in a different server (Server 2) which has to read these files and show it in the GUI.
FTP is blocked in web application server. So i am thinking of using HTTP.
The files in Server1 is not distributed .i.e not inside any ear or war.
I managed to get the code to read a file from HTTP.
My question is
- How do i access this file through HTTP when these files are not distributed
- When i write a code accessing the file like http://server1:port1/location of file , its says file not found .
- how do i expose these files , so that i can access it via HTTP from my web application
Answer: That means, you want to download the content of the file.
Well at very first, open up a browser. Enter http://server1:port1/FILE_PATH .
what do you get as a response ?
Second, if you get "FILE NOT FOUND" then you need to configure a virtual path mapped to real path in server1. After that, try the URL from browser again. When it works,
<code>URL website = new URL("http://server1/file_location");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("file_name");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
</code>
will help you to download the file to your local machine.
Comment: What server are you using for listing the files ? Tomcat container ? Apache HTTP ? `Alias /myproject "C:/path/to/my/project"

  Options Indexes FollowSymLinks MultiViews ExecCGI
  AllowOverride All
  Order allow,deny
  Allow from all
`
Comment: Server 1 - Weblogic Container  contains files outside the ear    Server 2 -  weblogic container which will read files in server1.
Comment: Check this http://docs.oracle.com/cd/E13222_01/wls/docs81/webapp/weblogic_xml.html#1039396
Comment: And also this would be helpful http://connectionserver.blogspot.com.tr/2009/05/listing-directories-simple-weblogic.html
Comment: File is not accesible  from browser .. How do i add virtual path ?


in 4 part harmony is it bad practice to double the bass of the I6 chord?

Question: Many places say that doubling the bass of major chords in 1st inversion is bad practice. So using C major as an example the bass note E would not be doubled.
please see the following from a harmony and voice leading text book.

Now you can see in the 1st example that shows common soprano lines over a chord progression and the I6 chord has the bass and soprano both with the 3rd of the chord. Can someone please explain. Is there any kind of standard or do people just not agree and you can actually double everything except a leading tone?
Comment: Related: [Doubling the third of a root position major chord in four-part harmony](https://music.stackexchange.com/q/74990/70803).
Comment: "Bad practice" is probably better stated as "dangerous if you don't know what you're doing."  It's certainly not synonymous with "forbidden."
Answer: Voice leading gets tricky; parallels are more difficult to avoid nicely.
https://musictheory.pugetsound.edu/mt21c/VoiceLeadingFirstInversionTriads.html
The link points out that one can double the third (of the chord) in first inversion diminished chords D-F-B-D. Of course, doubling the third of minor chords is good.
Another possibility is with parallel first inversion chords, one often doubles the third and root of every other chord. And it's possible to double the third if these are approached in contrary motion.
Another point (that may not apply in Renaissance or Medieval or other non-CPP styles) is that a major chord in first inversion with doubled third sounds like a Neapolitan Sixth. While normally the N6 occurs on the flat scale step (bII6 or Db63 in the key of C) it may be a "secondary Neapolitan Sixth" and may occur on any scale step.
Comment: To the first sentence, I would add "and it's harder (for non keyboard instruments) to tune"  I would also note in the next-to-last paragraph that the example in question employs contrary motion.


Installing Drush on WSL

Question: How should I install Drush on WSL when running the following command shown in the Drush documentation fails?
<code>php -r "readfile('http://files.drush.org/drush.phar');" > drush
</code>
Comment: It would be very helpful if you included the error message as there might be several reasons why the command didn't work.
Answer: Better to follow this to require with composer: https://www.drupal.org/node/1248790

Install composer globaly:
$ curl -sS https://getcomposer.org/installer | php
$ sudo mv composer.phar /usr/local/bin/composer
Require drush:
composer global require drush/drush:7.*

The instructions in drupal.org also show how to add the path so you can use drush from everywhere.
Im working with WSL and it works great.
Comment: Yes, Drush is installed on WSL in the same way it's installed on Linux. I would add that the Drush installation instructions now suggest to avoid installing it globally.

Installing Drush on WSL