HAProxy route https SNI and http over the same port

Question: I have an HAProxy routing HTTPS without termination using SNI.
The configuration is similar to the following:
frontend ft_ssl_vip
  bind 0.0.0.0:5000
  mode tcp
  option tcplog

  tcp-request inspect-delay 5s
  tcp-request content accept if { req.ssl_hello_type 1 }

  default_backend bk_ssl_default

# Using SNI to take routing decision
backend bk_ssl_default
  mode tcp

  acl application_1 req.ssl_sni -i foo.example.com
  acl application_2 req.ssl_sni -i bar.example.com

  use-server server1 if application_1
  use-server server2 if application_2
  use-server server3 if !application_1 !application_2

  option ssl-hello-chk
  server server1 127.0.0.1:777
  server server2 127.0.0.1:778
  server server3 127.0.0.1:779

I need to also route HTTP traffic over the same port (5000).
How can I modify my configuration to accommodate both HTTP and HTTPS via SNI without termination over the same port?

edit

I've gotten much closer.  The HTTPS routing appears to be working but the HTTP backend acl is not matching the domain for some reason.
Here is where I am at:
frontend app
  bind 0.0.0.0:5000
  mode tcp
  option tcplog

  tcp-request inspect-delay 5s
  tcp-request content accept if HTTP
  tcp-request content accept if { req.ssl_hello_type 1 }

  use_backend testing_http if HTTP

  default_backend testing_https

backend testing_https
  mode tcp

  acl app_2 req.ssl_sni -i foo.bar.com

  use-server server2 if app_2
  use-server default if !app_2

  server server2 127.0.0.1:777
  server default 127.0.0.1:443

backend testing_http
  mode http

  acl app_2 hdr(host) -i foo.bar.com

  use-server server2 if app_2
  use-server default if !app_2

  server server2 127.0.0.1:777
  server default 127.0.0.1:80

Comment: Really? Use a different port.
Comment: @michael-hampton: Obviously I would but aws elastic beanstalk with docker only allows the application to expose one port
Comment: Docker is perfectly capable of exposing as many ports as you need.
Comment: @michael-hampton: It is an AWS Elastic Beanstalk restriction, not docker.  Exposing multiple ports is unfortunately not an option.  Like I said, otherwise I would have already taken this approach.  It isn't my call to make
Answer: I am posting an answer to my own question because I have been able to piece something together and this question doesn't seem to have any interest.  If it comes up in a google search, this should help someone.
The following seems to work for me so far:
frontend app
  bind 0.0.0.0:5000
  mode tcp
  option tcplog

  tcp-request inspect-delay 5s
  tcp-request content accept if HTTP
  tcp-request content accept if { req.ssl_hello_type 1 }

  use_backend testing_http if HTTP

  default_backend testing_https

backend testing_https
  mode tcp

  acl app_2 req.ssl_sni -i foo.bar.com

  use-server server2 if app_2
  use-server default if !app_2

  server server2 127.0.0.1:777
  server default serverfault.com:443

backend testing_http
  mode http

  acl app_2 hdr_dom(host) -i foo.bar.com

  use-server server2 if app_2
  use-server default if !app_2

  server server2 127.0.0.1:777
  server default www.example.com:80

The important parts to understand -- frontend checks if the request is HTTP.  If it isn't, it checks if it is an SNI request.  Otherwise, it doesn't accept.
The other part that tripped me up was the host matching on the http backend.  It was important to use domain matching with hdr_dom instead of hdr so that a manually specified port in the string doesn't break the acl.
The most difficult part is that tcp mode on the front end has unhelpful logging for http.  And since the http backend can't log, you don't get any http information.
Comment: Thanks for you have wrote down your results in an answer. I simply didn't think I could mix tcp and http mode in the config file. I've a similar problem, some https to terminate into the frontend and pass as http to backend. but also some SSL connection that must  pass through to be server as https on the backends.  I too have the need to route based on 'called' domain.


Not getting correct count of NSMutableDictionary

Question: I could not able to get the actual count of object after setting it to the dictionary.
I  am having a structure pointer pEvent which i have put up in myData(NSData object).and I am storing this NSData into the dictionary.
<code>[m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerIds]];
int no = [m_cAppIdMap count];
NSLog(@"The no of entries in array is:%d",no);
</code>
Comment: is m_cAppIdMap an array or an mutable dictionary? (As an aside the `m_` for iVars isn't Cocoa-like)
Comment: Stick a breakpoint on the line - make sure that `myData` and the key are real objects. Also check the dictionary in the debugger to see whether that has any key-value pairs. Try adding another log: `NSLog(@"My dictionary is %@", m-cAppIdMap);` and see what you get. When you say you aren't getting the correct count - what are you getting? Is anything showing up in the debugger?
Comment: @Abizern:Yeah m_cAppIdMap is a mutable dictionary.
Comment: @Abizern:Its printing me a null value.Its not adding the key and value pair onto the dictionary and the dictionary is empty.
Comment: @Abizem:I made a mistake.I didnt intialise the NSMutableArray so is that error.Now i'm getting the correct value.Thanks.
Answer: Use int no = [m_cAppIdMap.allKeys count];
Comment: If the dictionary isn't able to return a `count` getting an array of the keys and counting that isn't going to work either, because if it had keys, it would have values, and it would then have a count.
Comment: I tried as you told me to do.But i could not get the correct count value.


Template suggestions not recognized

Question: I have just introduced my custom template suggestions in MYTHEME_preprocess_node, based on a certain field's value. Won't work somehow.
The content type is project. In my template folder I have already a file named node--project.tpl.php, and my suggestions append additional two: node--project--pcgame.tpl.php and node--project--movie.tpl.php. They are visible when I dpm() the variables, but are not found/applied to the node, even when I remove node--project.tpl.php.
Cache cleared.
Any clue as per what could be the cause?

The code I'm using:
function MYTHEME_preprocess_node($variables){
  if(isset($variables['node'])){
    $node = $variables['node'];
    if($node->type == 'project'){
      // Determine project type based on a term field.
      $project_type = (int) $node->field_genre['und'][0]['tid'];

      switch($project_type){
        case 4:
          $variables['theme_hook_suggestions'][] = 'node__project__pcgame';
          break;
        default:
          $variables['theme_hook_suggestions'][] = 'node__project__movie';
      }
      dpm($variables['theme_hook_suggestions']);
      }
   }
}

Comment: Is that the exact code? `$variables` needs to be passed by reference, i.e. `function MYTHEME_preprocess_node(&$variables){`
Comment: Because the local copy of `$variables` contains it :)
Comment: what version of drupal?
Comment: Could you show the code that creates the template suggestions?
Comment: D7. Just provided the code for you.
Comment: Kaboom. Shame on me :) (Still wondering why I saw the appended suggestion in `dpm`)
Comment: By all means! :) Thanks for nudging my sleepy brain ;-)
Answer: You try this code.
 function youthemename_preprocess_node(&$variables) {
 $node = $variables['node'];
    if($node->type == 'project'){
      // Determine project type based on a term field.
      $project_type = $node->field_genre['und'][0]['tid'];

      switch($project_type){
        case 4:
          $variables['theme_hook_suggestions'][] = 'node__project_pcgame';
          break;
        default:
          $variables['theme_hook_suggestions'][] = 'node__project_movie';
      }
    }
}

You file name should be node--project_pcgame.tpl.php and node--project_movie.tpl.php.
Clear performance cache, it should call hook_theme_registry_alter(&$theme_registry).

Template suggestions not recognized


Como fazer scrapping no Google Scholar?

Question: Utilizando o Mozilla Firefox, alguém poderia dizer como fazer scrapping no Google Scholar?
Por onde começar?
Comment: Karla, olá! Agradeço o compartilhamento. Posso sugerir uma alteração? Talvez seja interessante você alterar o formato para um par pergunta/resposta. Isso ajuda aqueles que possuem uma dúvida que é respondida pelo seu conteúdo ("Como fazer scrapping no Google Scholar?") ao mesmo ajustando para o formato do Stack Overflow.
Comment: O site tem o formato Pergunta/Resposta. De preferência com algum código atual. No seu caso, coloquei uma resposta a sua própria pergunta.
Comment: Você deveria colocar sua resposta, então excluirei minha "resposta". Fiz apenas para indicar como ficará.
Answer: Vou publicar aqui o meu código de web scraping para google scholar, usando palavras-chaves. Com este code eu consegui retirar informações como: Título, Autores, Resumo e número de citações; da página do google scholar. O código vou baseado em informações obtidas pelos seguintes R programmers: Kay Cichini, Gabor Pozsgai e Rogério Barbosa.
library(RSelenium)
library(xlsx)

checkForServer() #baixando um servidor do Selenium (so precisa fazer uma vez)
startServer() # mantenha essa janela aberta

Tenha o Mozilla firefox instalado!! Vamos abri-lo:
firefox_con <- remoteDriver(remoteServerAddr = "localhost",
                            port = 4444,
                            browserName = "firefox"
)

Abrindo o firefox (a navegacao vai se dar nele)
firefox_con$open() # mantenha essa janela aberta

Realiza o Scrapping
url <- paste("http://scholar.google.com/scholar?q=", "+key+word", "&num=1&as_sdt=1&as_vis=1",
             sep = "")

firefox_con$navigate("http://scholar.google.com.br")
busca <- firefox_con$findElement(using = "css selector", value = "#gs_hp_tsi")
Keyword <- busca$sendKeysToElement(list("key word", key="enter"))

pages.max <- 10

scraper_internal <- function(x) {
  doc <- htmlParse(url, encoding="UTF-8")
  tit <- xpathSApply(x, "//h3[@class='gs_rt']", xmlValue)
  aut <- xpathSApply(x, "//div[@class='gs_a']", xmlValue)
  abst <- xpathSApply(x, "//div[@class='gs_rs']", xmlValue)
  others <- xpathSApply(x, "//div[@class='gs_fl']", xmlValue)
  dat <- data.frame(TITLE = tit, AUTHORS = aut, ABSTRACT = abst, CITED = others)
}

for (i in seq(1,pages.max*10,10)){
    baseURL <- paste("http://scholar.google.com/scholar?start=", i, "&q=", "+key+word",
                   "&hl=en&lr=lang_en&num=10&as_sdt=1&as_vis=1",
                   sep = "")
  firefox_con$navigate(baseURL)
  pagina <- xmlRoot(htmlParse(
    unlist(firefox_con$getPageSource())
  ))
  result <- scraper_internal(pagina)
  write.xlsx(result, "C:/KEYWORD.xlsx",
             sheetName = paste("keyword", i), row.names=TRUE, col.names = TRUE, append=TRUE)
}

Comment: Karla, movi o conteúdo que estava na resposta que o Tony fez em seu lugar para cá.

Como fazer scrapping no Google Scholar?


Como somar elementos de duas lista de vetores com if C++

Question: Bom estou travado nesse programa faz bom tempo. Sou inciante e o objetivo da questão é fazer operações entre cada elemento de duas listas se o resto for 1, 2 e assim vai.
Exemplo: 2 lista com elementos, 4 9 7 e 1 2 3, você vai somar 4+1 se a divisão 4/4 for igual a zero.
#include <iostream>
using namespace std;

int main() {
  int n, i, j, s =0, resto = 0;

  cin >> n;

  int vet[n], resultado[n];

  for (i=0; i<n; i++){

    cin >> vet[i];
  }

  for (j=0; j<n; j++){

    cin >> vet[j];
  }

  for (i=0; i<n; i++){

    resto = vet[i] % 4;
    for (j=0; j<n; j++){
        if (resto == 0){
          resultado[i] = vet[i]+vet[j];
        }
        if (resto == 1){
          resultado[i] = vet[i]-vet[j];
        }
        if (resto == 2){
          resultado[i] = vet[i]*vet[j];
        }
        if (resto == 3){
          resultado[i] = vet[i]/vet[j];
        }
        if (resto == 4){
          resultado[i] = vet[i]^vet[j];
        }
    }
    cout << resultado[i] << ' ';

  }
}

Comment: Quando que a divisão `4/4` é igual a zero? No código `if (resto == 0){` por que somar `vet[i]` com `vet[j]` já que a única forma de `resto` ser igual a zero é se `vet[i]` for zero?
Answer: Oi, aconselho a aprender e usar sempre os sub-idiomas de C++ moderno:
Exemplo: corilu
use std::copy_n para ler as entradas
copy_n(istream_iterator<int>(cin), n, std::back_inserter(v1)); // le 'n' números em v1

use std::transform para percorrer e alterar o vetor
transform( v1.begin(), v1.end(), v2.begin(), ... );

use std::vector a 'auto' sempre que possível
 vector<int> v1,v2;

use lambdas para expressar as funções
 auto x = [](int a, int b) { return a + b; }

E por favor, poste a parte importante do código aqui ( como eu fiz acima ) e o código completo no compiler explorer ou corilu.
Abraços


Create a CSV file of all the addresses in an area from OSM file

Question: I am interested in creating a CSV file of addresses from the area below (in the format street name, town, postcode, city, latitude, longitude).

This is what I've done so far:
1) Download osm files for the UK at http://nick.dev.openstreetmap.org/downloads/planet/
2) Run osmfilter:
osmfilter uk.osm --keep="highway=residential =primary =secondary =tertiaty =unclassified" >uk_streets.osm

3) Run osmconvert:
osmconvert uk_streets.osm --csv="@lon @lat addr:city addr:street" --csv-headline --csv-separator=, -o=uk_streets.csv

My problems

I can't figure out how to only pull addresses from the Milton Keynes
area, the above script seems to pull from the whole of UK (i.e. not in
the bounds shown in the image above).
There were lots of gaps in the data after running the script, I could
not find some of the addresses that appeared on the OSM website in
the database

Question

How would I refactor my osmfilter and osmconvert
commands to pull the necessary information for the Milton Keynes
area ONLY?
Comment: Oh, you already asked there. Here's the link for other people running into the same problem: https://help.openstreetmap.org/questions/35148/create-a-csv-file-of-all-the-addresses-in-milton-keynes-area
Comment: Can you name some examples of addresses missing in your result but existing in the OSM database? And consider asking your question at http://help.openstreetmap.org or http://gis.stackexchange.com instead, people here tend to close questions way too fast.
Answer: Another technique is to use https://openaddresses.io/
Does not use OSM data, but gives you a similar (better?) result.
Answer: You could clip the data to only the area you're interested in again with osmconvert, you can create a poly file (with Josm or other program - http://wiki.openstreetmap.org/wiki/Osmosis/Polygon_Filter_File_Format), then using this to clip the file, see this section
http://wiki.openstreetmap.org/wiki/Osmconvert#Clipping_based_on_a_Polygon


In metric spaces, is a function uniformly continuous iff $\delta$ depends on $\varepsilon$?

Question: Most book examples end with an expression for $\delta$ that depends on $\varepsilon$ when proving uniform continuity. What I am wondering is whether a function can be uniformly continuous as long as the distance between any two elements of the domain of the metric space is within some number that does not depend on $\varepsilon$ or the where we "fix" the domain.
Comment: The question is not whether delta depends on epsilon (it always does, except for constant functions), but whether delta depends on epsilon AND ON THE POINT x, or only on epsilon.
Answer: There exist bounded, non uniformly continuous functions, so the answer is no. One example of such a function is $f(x)=\cos(x^2)$, for $x\in\mathbb R$. Then, for all $x,y\in\mathbb R$, you have that $|\cos(x^2)-\cos(y^2)|\leq 2$, but $f$ is not uniformly continuous on $\mathbb R$.
Comment: What is crucial is that the definition has to hold for all $\varepsilon$. There is no need for $\delta$ to depend on $\epsilon$, though.
Comment: You could consider a constant function.
Comment: I see. So, delta has to depend on epsilon then.
Comment: What would be one example of such case?


How can I add a filter to an export display?

Question: I have a view "Nearest Dealers" that lists all the near dealers. There are two displays - Page & REST Export. I've added a filter(exposed to visitors) that lets customer search dealers based on current location and distance(eg: 10km radius). Filter works perfectly, but I want to show the same filtered results in REST Export display for the same view. Is it possible to do so because I have no clue how to make this work. Or is there any way to add the same filter for the REST Export display ?
Answer:
is there any way to add the same filter for the REST Export display ?

On your regular View page, apply filter for something, and you'll see a URL query gets appended to your URL. For example, when I'm filtering by content type, for mine, I see:
mysite.com/page-view?title=&type=article&status=All&langcode=All (This is based on the view filters I have).
Then all you have to do is append this query to your REST export URL.
mysite.com/rest-export?title=&type=article&status=All&langcode=All (Assuming you have the same filters as your page view, they should've been added by default when you added the REST view).
You'll need to create documentation for this. So people that are using your API know what parameter names & values are accepted.
Comment: You can also thank me by accepting the answer with the checkmark and up voting it. I get rep points for that @Aman Devrath
Comment: Thanks for the help. I tried to append the query string but it doesn't work. I tried using `%` since it works for contextual filers, but it didn't work for exposed filter. I was thinking, does replacement pattern work on rest export URL ?
Comment: @AmanDevrath make sure you've the same filters in your Rest export, see [this demo](https://streamable.com/ntx2rb)
Comment: That was a total confusion by my side. This way I can get it. In video you copy paste the query string to the rest export url on the browser address bar. Is it possible to get it automatically in the url ? Like no need to copy paste just click the rest export url and see the filter applied in page display ?
Comment: @AmanDevrath you would have to programmatically redirect it, [like in this answer](https://drupal.stackexchange.com/a/237896/27710); although, that case is for a node, but yours would be similar.
Comment: thank you so much sir. although it might be a lot of work to create view, add filter, pick query from page display, pass it to rest export url. I'll give this a try


Starting temporary second voice in LilyPond

Question: I'm scoring Bach BWV927 in LilyPond. For each hand, at various measures there are two voices. The left-hand second voice starts in the first measure, but the right-hand second voice starts in the third measure.
At the moment, I'm adding rests to position the right-hand second voice correctly, but I don't want its rests to appear. How do I start a voice in a specific measure?
\version "2.20"

\header {
  title =   "Prelude in F - BWV 927"
  subtitle = "Kleine Praledien Fughetten. 8"
  composer =    "J.S. Bach (1685-1750)"
}

global = {
  \key f \major
  \time 4/4
  \tempo 4 = 28
}

rightvoiceone =  {
  \relative b' {
    r16 c16 a c f,  c' a c f,  d' bes-3 d f, d' bes d |

    g,-1 e'-5 bes-2 e g, e' bes-2 e-4  f c-2 a c-3 f,  r8. |

    r8 f' f f r8 f f f | \break

    r8 g bes g a4 r4
   \bar "|."
  }
}

rightvoicetwo =  {
  \relative b' {
    R1 | R1 |

    r8 c a c r8 d bes d | \break

    r8 e e e <c f>4 r4
  }
}

leftvoiceone =  {
  \relative c {
    \stemDown
    f8 f8 f8 f8 r8 f8 f8 f8 |

    r8 f8 f8 f8 f4 r16 c'16 a16 c16 | f,16 c' a c f, c' a c f, d' bes d f, d' bes d |
    g, e' bes e g, e' bes e f c a c f, c a c |
  }
}

leftvoicetwo =  {
  \relative c' {
    \stemUp
    a8 c8 a8 c8 r8 d8 bes8 d8 | r8 g,8 bes8 g8 a4
  }
}

\score {
   \context PianoStaff <<
    \context Staff = "rh" <<
      \global
      \clef "treble"
      \new Voice = "rhfirst"
         { \voiceOne \rightvoiceone }
      \new Voice = "rhsecond"
         { \voiceTwo \rightvoicetwo }
    >>
    \context Staff = "lh" <<
      \global
      \clef "bass"
      \new Voice = "lhfirst"
         { \voiceOne \leftvoiceone }
      \new Voice= "lhsecond"
         { \voiceTwo \leftvoicetwo }
    >>
  >>
  \layout { }
  \midi { }
}

Answer: What's actually going on here is that there are three voices: the top voice (right hand), the bottom voice (left hand), and a middle voice that switches between the two hands.
However, to keep your current scoring (more or less), you have two options:

Use \hideNotes and \unHideNotes;
(Also, in rightvoicetwo, the capital Rs should be lowercase.)
(LilyPond Notation Reference)

rightvoicetwo =  {
  \relative b' {
    \hideNotes
    r1 | r1 |
    \unHideNotes
    r8 c a c r8 d bes d | \break

    r8 e e e <c f>4 r4
  }
}

Use s (spacer, a.k.a. "invisible rest") instead of r (rest).
(LilyPond Notation Reference)

rightvoicetwo =  {
  \relative b' {
    s1 | s1 |

    r8 c a c r8 d bes d | \break

    r8 e e e <c f>4 r4
  }
}

Comment: Cool - invisible rests!


Finding real money on a strange weighing device

Question: You have 50 coins which each weigh either 20 grams or 10 grams. Each is labelled from 0 to 49 so you can tell the coins apart.  You have one weighing device as well. At the first turn you can put as many coins as you like on the weighing device and it will tell you exactly how much they weigh.
However, there is something strange about the weighing device.  If you put coins $x_1, x_2, ..., x_j$ on the device the first time, then you have to put coins $(x_1+1) \bmod 50, (x_2+1) \bmod 50, ..., (x_j+1) \bmod 50$ on the scale the next time, and coins  $(x_1+2) \bmod 50, (x_2+2) \bmod 50, ..., (x_j+2) \bmod 50$ the next time and so on. In other words, all the weighings are defined by the choice of coins you choose to weigh the first time.

Under this rule, what is the smallest number of weighings that will always tell you
  exactly which coins weigh 10 grams and which weigh 20?

Clearly you could just put one coin on the device in the first turn and then it would take exactly $50$ weighings to solve the problem.

Here is an example when you have only $4$ coins that takes only $3$ weighings.  First put coins $1$,$2$ and $3$ on the scale. For the next weighing you will have coins $0$, $2$ and $3$. For the last weighing you will have coins $0$, $1$ and $3$ and you will then know exactly which coins are real and which are fake.

Here is another example when you have $9$ coins that takes only $6$ weighings. First put coins $2,5,7,8$ on the scale (indexing from $0$ again).
Answers so far (smaller is better)

38 by san
35 by Tad
31 by Tad
26 by joriki
25 by joriki (A very impressive record!)
Comment: If you let $f(n)$ denote the minimal number of weighings, for a number $n\ge1$ of coins, the sequence $\{f(n)\}$ starts like this: $1,2,3,3,4,5,6,6,6,7,7,8,\ldots$  This sequence does not appear in OEIS.
Comment: @DrXorile Thank you although I am afraid I made it up. There is a family of related puzzles I might pose at a later date too :)
Comment: How is your example better than just weighing 1 coin at the time? In three weighing you know exactly which coins weigh 20 and which weigh 10.
Comment: @ConradoCosta If you put one coin on the scale you need 4 weighings as you weigh each coin individually. In my example that is reduced to 3.
Comment: In the case  of $4$ coins. do you know how many weigh $20$ and how many weigh $10$? If you do then with $3$ weighing you will have found $2$ coins of the same weight.  If you are lucky you may need only $2$ weighings. Or I am missing something?
Comment: @ConradoCosta No you know nothing about how many weigh 10 or 20 in advance.  All the information you get has to be obtained by weighings.
Comment: @Tad That's very impressive that you have computed those. How did you do it?
Comment: You don't need to try all $2^n$ pattern possibilities, just one from every rotation-equivalence class (it's still a lot).  I used a binary search to determine, for each pattern, how many rotations were needed to get a unique signature for each "coin vector".  Anyway, this confirms $f(9)=6$ as you note in response to @JonMarkPerry.  Great problem - I wish I had a clue how to solve it.
Comment: @Tad That's very interesting, thank you. Would you mind sharing your code (please)?
Comment: Where did you come across this puzzle? It's great. Seems like it should succumb to the usual tricks, and then it really doesn't!
Comment: $f(50)\le 35$ -- I've updated my post.
Comment: Thanks for your generous new bounty offer! In looking at other questions of yours (out of interest and also to look for ones worthy of upvotes so you can keep awarding bounties :-) I noticed this question: http://math.stackexchange.com/questions/1059379 which is related to this one. Is there any particular reason you're interested in these sort of shifted products?
Comment: @joriki Thank you! I just found a class of mathematical problems that seem open and not being a professional mathematician, I find that exciting to be honest.
Comment: About your comments in the new bounty box: Why do you think my argument proves $f(n)\ge n\,/\log n$? What's special about the proportionality factor $1$ between $f(n)$ and $n\,/\log n$? My suggestion would be to use my code to map out the currently uncharted territory between $n=26$ and $n=50$, where we can get statistics much more quickly than at $n=50$. (I'll also continue to look for solutions with $n=50$, $k=24$, of course -- unfortunately the two solutions I found for $k=25$ turned out not to work for $k=24$.)
Comment: @joriki Did you see my comment that I think in fact $f(n) \geq 2n/\log_2 n$?
Comment: I'm sorry, I hadn't realized that by $\lg$ you meant the binary logarithm. Then you're right about $f(n)\ge n/\lg n$ (though an argument would have to be made why it shouldn't be $\lg(n+1)$, since there are $n+1$ possible outcomes per weighing). Yes, I had seen the other comment, but I hadn't realized its significance because I wasn't thinking in terms of the binary logarithm. You have a great point there -- if we model the distribution of the individual measurements as binomial, the effective number of possible values is $~\sqrt n$, so a factor of $2$ would make sense, and it fits the data.
Comment: Sorry, no, I hadn't seen your comment, I came across it now; I thought you were taking about the remark in the bounty box :-) Sorry for all the confusion. I'll check out that reference -- interesting!
Comment: @joriki the only way there could be $n+1$ outcomes per weighing is if the pattern is all ones- but in that case you'd get the same result with every rotation. There are $d+1$ possibilities if the pattern has density $d$.
Answer: Update: I've now found two solutions that require only $25$ weighings:
$$
01011011100010111101000001100111110011010100011010\;,\\
00101110001101001010111110001000110010011111011101\;.
$$
These are the only solutions known (in the context of this post) with $k=n\,/\,2$, for any $n$. I found them using Tad's recipe of repeatedly maximizing the determinant of $AA^\top$ by hill climbing and testing the candidate with the highest determinant among several runs. The determinants are
$$
87546852131623099566361867104\;,\\
93001686149176479553585114299\;.
$$
I only had to test half a dozen candidates to find these two solutions, which seems consistent with $f(50)\simeq 22.4$. I'll now be testing these two with $24$ weighings; that will take the better part of a day and will require a bit more than a trillion difference vectors to be checked in each case.

I believe the bounty should go to Tad, who developed the mathematical approach. I tried to improve on it but couldn't, so instead I coded it a whole lot faster :-). Here's the code. It uses a special bit encoding for efficient arithmetic with vectors over $\mathbb F_3$. On my MacBook, it takes half a minute to test a candidate with $31$ weighings and two hours for a candidate with $26$ weighings.
The best solution it's found so far is $01010111100010011111110000111011000101101100100001$, with $26$ weighings required. I'm now looking for solutions with $25$ weighings, but that requires up to six hours of testing per candidate. I expect the minimum to be near $23$ (see below). I haven't implemented Tad's determinant maximization approach yet; the above solution was just the third candidate I tried with uniform sampling among the vectors (uniform sampling among the rotational equivalence classes would be worse since it gives higher weight to periodic sequences).
Here's a short summary of the mathematical basis of the code, mostly following Tad's ideas and notation; $n$ is the number of coins, and $k$ is the number of weighings. We can treat the two weights of the coins as $0$ and $1$. Then every possible weight configuration is characterized by a binary weight vector, and the differences between weight vectors are ternary vectors with entries $-1$, $0$ and $+1$. A solution is admissible if the $k\times n$ matrix $A$, with entries $A_{ij}\in\{0,1\}$ according as coin $j$ is weighed in weighing $i$, has different products with all possible weight vectors, or equivalently, if its product with all possible difference vectors is non-zero.
We can regard the difference vectors as vectors over $\mathbb F_3$. Only the difference vectors in the kernel of $A$ over $\mathbb F_3$ can be in the kernel of $A$ over $\mathbb Z$. The kernel over $\mathbb F_3$ will generally contain $3^{n-k}$ difference vectors, and these we have to check over $\mathbb Z$ (actually only half of them, due to invariance under negation). The key to doing this efficiently is to bit-encode $\mathbb F_3$ such that the time-limiting steps (addition, componentwise multiplication and summation of vectors) can be performed compactly using integer operations and table lookups instead of iterating over $n$ vector components.
Here are some results that expand on Tad's results for values well below $50$. $n_\text{c}$ is the number of equivalence classes under rotation; the numbers in the header row are $n-k$, and the numbers in the bodies of the two tables are the numbers and fractions, respectively, of rotational equivalence classes that yield a solution.
\begin{array}{c|c|cc}
n_\text{c}&n&0&1&2&3&4&5&6&7&8&9\\\hline
2&1&1\\
3&2&1\\
4&3&2\\
6&4&2&1\\
8&5&6&3\\
14&6&6&4\\
20&7&18&12\\
36&8&20&17&8\\
60&9&50&45&25&6\\
108&10&74&71&56&17\\
188&11&186&178&130&83&4\\
352&12&216&214&200&135&42\\
632&13&630&614&520&469&261&6\\
1182&14&916&910&878&787&535&101\\
2192&15&2002&1988&1924&1831&1427&648&22\\
4116&16&3040&3037&3000&2926&2605&1686&330&2\\
7712&17&7710&7699&7464&7330&6915&5361&2131&34\\
14602&18&10806&10801&10760&10649&10310&9014&5547&875\\
27596&19&27594&27582&27270&27110&26565&24773&18964&7307&152\\
52488&20&40642&40639&40592&40474&40024&38487&33414&20254&3102&2\\
99880&21&94658&94640&94440&94281&93518&91759&85546&65010&24368&508\\
\end{array}
\begin{array}{c|c|cc}
n_\text{c}&n&0&1&2&3&4&5&6&7&8&9\\\hline
2&1&.5000\\
3&2&.3333\\
4&3&.5000\\
6&4&.3333&.1667\\
8&5&.7500&.3750\\
14&6&.4286&.2857\\
20&7&.9000&.6000\\
36&8&.5556&.4722&.2222\\
60&9&.8333&.7500&.4167&.1000\\
108&10&.6852&.6574&.5185&.1574\\
188&11&.9894&.9468&.6915&.4415&.0213\\
352&12&.6136&.6080&.5682&.3835&.1193\\
632&13&.9968&.9715&.8228&.7421&.4130&.0095\\
1182&14&.7750&.7699&.7428&.6658&.4526&.0854\\
2192&15&.9133&.9069&.8777&.8353&.6510&.2956&.0100\\
4116&16&.7386&.7379&.7289&.7109&.6329&.4096&.0802&.0005\\
7712&17&.9997&.9983&.9678&.9505&.8967&.6952&.2763&.0044\\
14602&18&.7400&.7397&.7369&.7293&.7061&.6173&.3799&.0599\\
27596&19&.9999&.9995&.9882&.9824&.9626&.8977&.6872&.2648&.0055\\
52488&20&.7743&.7743&.7734&.7711&.7625&.7333&.6366&.3859&.0591&.0000\\
99880&21&.9477&.9475&.9455&.9439&.9363&.9187&.8565&.6509&.2440&.0051\\
\end{array}
Here are the minimal $k$ values up to $n=26$ (denoted by $f(n)$ as in Tad's table), together with the numbers and fractions of solution classes at minimal $k$:
\begin{array}{c|c|c|c}
n&f(n)&\#&\#\,/\,n_\text{c}\\\hline
1&1&1&.5000\\
2&2&1&.3333\\
3&3&2&.5000\\
4&3&1&.1667\\
5&4&3&.3750\\
6&5&4&.2857\\
7&6&12&.6000\\
8&6&8&.2222\\
9&6&6&.1000\\
10&7&17&.1574\\
11&7&4&.0213\\
12&8&42&.1193\\
13&8&6&.0095\\
14&9&101&.0854\\
15&9&22&.0100\\
16&9&2&.0005\\
17&10&34&.0044\\
18&11&875&.0599\\
19&11&152&.0055\\
20&11&2&.0000\\
21&12&508&.0051\\
22&12&8&.0000\\
23&13&2340&.0064\\
24&13&36&.0001\\
25&14&10688&.0080\\
26&14&216&.0001
\end{array}
The solution class counts of $2$ for $n=16$ and $n=20$ that both come at the end of an unusual triple of identical values of $f(n)$ are salient; here are the solution vectors:
$$
0000101110111011\;,\\
0000110111011101\;,\\
00000101111011110111\;,\\
00000111011110111101\;.\\
$$
Note that in both cases the two solutions are related by inversion, they contain slightly longer runs of $0$s than of $1$s, and the runs of $1$s are separate by single zeros.
It's tempting to speculate that the bound $f(n)\gt n/2$ that holds up to $n=26$ will continue to hold for higher $n$. However, I don't believe that this is the case. There's already a slight indication of this in the data; the solutions are gradually encroaching on the bound. (The trends in the absolute numbers are relevant here, not in the fractions, since we only need a single solution.) The fact that the third uniformly randomly guessed candidate turned out to be a solution for $k=26$, $n=50$ also points in this direction, since it suggests that the density of solutions at that point is much higher than it is for $k=n/2-1$ at  lower $n$ values (where it's almost negligible).
Moreover, statistical considerations suggest that the asymptotic behaviour of $k$ might be $n\,/\log n$. There are various handwaving arguments that could be used to support this, based on entropy or collision probabilities; the details may be hard to get right, but the bigger picture is the same in each case: The $k$ measurements each have an effective space of order some power $n^\alpha$ to spread across ($\sqrt n$ if we consider them to be binomially distributed), so our discerning ability grows with $n^{\alpha k}$, while the number of possibilities we need to be able to discern grows with $2^n$; equating the logarithms yields $\alpha k\log n=n\log2$ and thus $k\propto n\,/\log n$.
Such $n\,/\log n$ behaviour seems consistent with the data up to $n=26$, so we can get a rough estimate e.g. from $f(26)=14$:
$$f(50)\simeq\frac{50\log26}{26\log50}\,f(26)\simeq1.6\,f(26)\simeq22.4\;.$$
That leaves ample space for improvement. :-)
Comment: @Joriki: Great exposition! +1 for you and Tad of course. I'm pretty sure there is also a strong connection with coding theory especially error detecting codes. It would be nice to also find a thread in this direction.
Comment: I agree completely about $k=n/2$. Let me change my acceptance criterion to that.
Comment: @Lembik: Progress report: I implemented Tad's hill climbing for $\det AA^T$, and the four tests that I'm running with high-determinant patterns (in parallel on a quad-core processor) are all succeeding so far -- so we may well have a $k=25$ solution in six hours...
Comment: @Lembik: I put the entire code on github: https://github.com/joriki/algebra. It should be self-contained in that form. Please let me know if there are problems compiling or running it or if you have suggestions for improving it.
Comment: @Lembik: P.P.S.: I forgot to mention: There's a slightly different version of Question1341400.java in that repository because I had to move a class in the process. I also added a main method to show how to use the code. You'll need to use that version and ignore the first one in the gist.
Comment: Welcome back...
Comment: This is a wonderful answer and I feel at some point should be used  to advertise math.stackexchange itself !  I will follow your generous advice and award the bounty to Tad unless someone comes up with a new idea before the bounty ends... and award the win to you when you find a solution with $k <n/2$.  Does that sound reasonable?
Comment: I also have a closely related follow up puzzle which you should be able to use much the same machinery for... except it might be a little harder :)  I won't post it for a few days though.
Comment: @Lembik: It certainly sounds reasonable. Note, though, that the current results satisfy $k\gt n/2$ without exception, so $k=n/2$ would already be somewhat significant.
Comment: Which Java library are you using for `import algebra.Matrix;`  ? (Thank you for releasing your code.)
Comment: @Lembik: It's all my own code -- sorry the gist isn't self-contained -- if you'd like to run it, I can make the classes it depends on available.
Comment: @Lembik: P.S.: The code in the algebra package is written with an eye to mathematical structures and not to efficient computation. It's only used for things that aren't costly, like computing a basis for the kernel. The time-consuming complete traversal of the kernel is done by code optimized for speed that doesn't use the algebra package.
Comment: @Lembik: Unfortunately the four tests for $k=25$ all failed eventually. Some quite late, so I still think there should be solutions with $k=25$, but I won't be finding one before tonight. So the bounty goes to the one who deserves it...
Comment: @joriki Could http://aws.amazon.com/free/ help?
Comment: I put some interesting histograms about the $AA^T$ heuristic in the comments on the follow up question.  It's still unclear to me exactly what is going on with it.
Answer: The following pattern works with $31$ weighings:
$${0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, \
0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, \
0, 1, 1, 1}.$$
This beats the $35$-weighing solution found earlier.
$${1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, \
1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, \
0, 0, 0, 1}.$$  See the comments at the end of this post.
This is not a complete answer, but it won't fit in a comment.  We define $f(n)$ to be the smallest number of weighings possible for $n$ coins.  Here is some simple but not particularly efficient Mathematica code which computes $f(n)$ for small $n$ by brute force: pick a representative $x$ of a rotational equivalence class of $n$-long $\{0,1\}$-vectors, build a matrix out of $k$ successive rotations of $x$, hit that matrix against all $\{0,1\}$-vectors, and see if all $2^n$ results are distinct. There are roughly $2^n/n$ rotation classes, so the complexity of this is about $4^n/n$.
<code>(* check if vector x works when rotated k times *)
ok[x_, k_] := Block[{n = Length[x], m, v},
  m = RotateRight[x, #] & /@ Range[k];
  v = Tuples[{0, 1}, n];
  Unequal @@ (m.# & /@ v)];

(* compute a canonical representative for the rotation class of x *)
MinRotation[x_] :=
  First[Sort[RotateRight[x, #] & /@ Range[Length[x]]]];

f[n_] := f[n] = Block[{k, v},
  v = Select[Tuples[{0, 1}, n], # == MinRotation[#] &];
  For[k = 1, k <= n, k++,
  s = Select[v, ok[#, k] &];
  If[s != {}, Return[{k, First[s], Length[s]}]]]];

TableForm[Prepend[f[#], #] & /@ Range[12],
  TableDirections -> {Column, Row, Row},
  TableHeadings -> {None, {"n", "f(n)", "Example", "# of examples"}}]
</code>
$$
\begin{array}{cccc}
 \text{n} & \text{f(n)} & \text{Example} & \text{$\#$ of examples} \\
 1 & 1 & (1) & 1 \\
 2 & 2 & (0 1) & 1 \\
 3 & 3 & (0 0 1) & 2 \\
 4 & 3 & (0 1 1 1) & 1 \\
 5 & 4 & (0 0 1 1 1) & 3 \\
 6 & 5 & (0 0 1 0 1 1) & 4 \\
 7 & 6 & (0 0 0 0 1 1 1 & 12 \\
 8 & 6 & (0 0 0 1 0 1 0 1) & 8 \\
 9 & 6 & (0 0 1 0 0 1 0 1 1) & 6 \\
 10 & 7 & (0 0 0 0 1 1 0 1 1 1) & 17 \\
 11 & 7 & (0 0 0 1 0 1 0 0 1 1 1) & 4 \\
 12 & 8 & (0 0 0 0 1 0 0 0 1 0 1 1) & 42 \\
\end{array}$$
This quickly becomes infeasible.  However, checking a given vector costs "only" $2^n$ matrix multiplies, so we can get some upper bounds for $f(n)$ by guessing good vectors $x$.  A reasonable heuristic is that the $k\times n$ matrix $A$ we're constructing should have $\det A A^T$ large; using that, we find for example that $f(15)\le 9$, since
$$(0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1)$$
turns out to work with $9$ rotations.
(Added 7/3/2015:)
To construct the solutions for $k=31$ and $k=35$ weighings of $n=50$ coins, I started by running a hill-climb about $3$ times, and picked the pattern giving the largest $\det AA^T$.  As a first check, I looked at a reduced basis for $\ker A$ to check that it didn't have any nonzero vectors whose coordinates were at most $1$ in absolute value, and then exhaustively checked $\ker A$ by putting it into Hermite form first.  This requires checking about $(2/3)3^{n-k}$ vectors, which is easy on a laptop.  The run for $k=31$ took about $7$ hours, $81$ times as long as the run for $k=35$.
Incidentally, just from a visual examination of the reduced bases for smaller values of $k$, I suspect that $f(50)$ is about $28$.
Comment: @san I think we can regard joriki's answers as computer aided proofs. You have to check the code that finds the answers.
Comment: Very nice comment with the bounty. I found a proof that $f(n)  \geq 2n/\log_2{n}$ in  Probabilistic methods in combinatorics. By Paul Erdös and Joel Spencer Academic Press, Inc., New York 1974
Comment: @Tad: Very nice and instructive answer! +1 for you and Joriki
Comment: Your heuristic is very interesting! If you plot $AA^T$ for all the weighings you tested for $n=12$, $f(n)=8$ do you see the ones that work at the peak?
Comment: I mean the determinant of $AA^T$ of course.
Comment: No, I don't think there's a simple rule like that -- the condition here is a very subtle combinatorial condition.  Here's the deal: having two sets of coins which give the same output values is equivalent to having a nonzero vector $v$, with only $-1$'s, $0$'s and $1$'s, such that $vA=0$.  On the other hand, Minkowski's theorem basically says that if $\det AA^T$ is small, then $\ker A$.will have short vectors.  So you get a heuristic, not a guarantee; $\det AA^T$ can be large but $\ker A$ still has short vectors.  It ultimately depends on more geometric details than just the determinant.
Comment: @Tad Could you explain why the length of the vectors in the kernel of $A$ is the relevant factor? I am probably missing something obvious.
Comment: If two vectors $v$ and $w$ of coins ($10$'s and $20$'s) give the same weights, then $Av=Aw$, i.e. $v-w\in\ker A$.  So $(v-w)/10$ is also in $\ker A$, and all components of this vector are in $\{-1,0,1\}$. The converse also holds -- given such a vector in $\ker A$, you can find two sets of coins giving the same weights.  (Looks like I may have transposed a matrix in my earlier comment; maybe that's the confusion. Sorry!)
Comment: @Tad Thank you but that was the part I understood! The part I didn't follow was your comment about "short vectors".  Some vectors in $\{-1,0,1\}^n$ are long and some are short. You seemed to imply that if the kernel of $A$ only has short vectors then we know something about whether it is a solution or not.
Comment: I meant that all the vectors in $\{-1,0,1\}^n$ are short, compared to a "random" vector in $\ker A$, whose coordinates are not in general bounded by anything in particular.
Comment: @Tad Oh I see thank you! And sorry for my confusion.
Comment: Your method for finding solutions is very impressive.
Comment: Given a set of weighting result in the solution of 31, how lpng does it takes to determine the individual weights?
Comment: @san Excellent question. This situation is completely analogous to the phenomenon in coding theory that it is one thing to construct a code with a given error-correction capacity; it is another thing entirely to construct a code which can be efficiently decoded.  I can guarantee that the given pattern allows the individual weights to be determined in principle, but the determination of weights may be computationally difficult.  (You have to solve a linear system over the integers, with bounds; that problem is NP-hard in general.)  Your solution is quite efficient in this respect.
Comment: That is what I thought. And how do I know that your solutions are correct? I have to trust you, which I do, but which is mathematically not very satisfying. If I now say the starting weighing (0,5,15,20,25) needs 35 weighings according to the rule to determine all the weights, how do you know if that is true?(It is true).
Comment: @Lembik: In which section of the book did you find the proof?
Comment: @joriki "The kitchen sink", pages 100 and 101.  This is a lower bound of $18$ for $n = 50$  so quite a lot lower than we are at now!
Answer: For $n\gt3$ the least number of weighings is $n-1$. All versions use the combinations of $n-1$ coins missing one, and a repeated weighing of the remaining coin.
If we analyse the original example, we can add up the total of the $3$ weighings. This gives us:
$2\times$(weight of coin $0$+weight of coin $1$+weight of coin $2$) $+3\times$weight of coin $3$. (I have used weights of $1$ and $2$ instead of $10$ and $20$.)
The sum of the first $3$ coins is from $\{3,4,5,6\}$ and so may take the values $\{6,8,10,12\}$, and the final coin provides either $3$ or $6$, giving the final set of possible weighings as $\{9,11,13,15,12,14,16,18\}$, or sorted: $\{9,11,12,13,14,15,16,18\}$.
So we take the $3$ weighings and add up the totals. Now because we have an even number of the first $3$ coins, we can determine the weight of the last coin as odd or even. This value can be removed from the original equations giving $3$ equations in $3$ unknowns, which have a solution.
For example if our three weighings give $5,5,6$, the totals weight is $16$. If the final coin weighed $1$, we would have $2\times(c_0+c_1+c_2)=13$, which is impossible. We infer the final coin must weigh $2$, so we have:
$$ c_0+c_1=3$$
$$ c_0+c_2=3$$
$$ c_1+c_2=4$$
which has the unique solution $c_0=1, c_1=2, c2=2$.
To generalize this, we can see that a solution set comes from:
$$(n-2)\{n-1,\dots,2n-2\}+(n-1)\{1,2\}$$
A possible weighing is unique modular $(n-2)$, and so we can determine the weight of the last coin by leaving a total weighing $0\mod(n-2)$, which leaves $(n-1)$ equations in $~(n-1)$ unknowns, which has a unique solution.
For example, with $5$ coins, we have the possible weights $\{4,5,6,7,8\}$ from the $4$ coins, and the total weighing is $3\times(c_0+c_1+c_2+c_3)+4\times c_4$. So the final total weighing will be either $3k+1$ or $3k+2$, telling us the value of $c_4$.
Because the range of coin wieghts is limited, a solution with more coins can often be achieved with less weighings than this. The variables are the number of coins used in weighings, the number of weighings and the possible weights of the coins.
Comment: For 9 coins it seems we only need 6 weighings.  Include coins 2, 5, 7 and 8 in the first weighing (indexing from 0).
Comment: @Lembik; ok i can see what you mean now!, i changed the last para, so this i suppose isn't a solution, but i think the maths is ok and on the right track..
Comment: @JonMarkPerry If you assume $x_i=i$, then your solution is correct, although it is easier to start weighting $1,2,3$ and then make $n-1$ weighting according to the rule.


Cannot update firebase tools from 3.19.1

Question: Prior to version 4.0.0 being released I had no problems with my app. I have been trying to update Firebase Tools since 3.19.3 was released and it will not work. It says that it updates without any errors but the tools are stuck on version 3.19.1. It is not updating.
After the release of 4.0.0 hosting no longer works. Cloud functions and Firestore are working without issue. I don't get any errors. It just doesn't work. I've been tying everything I can and searching all over forums for answers and nothing.
Hosting is not working. Static assets are not loading. It says that index.html cannot be found...but that is because there is no index.html because I am using express-handlebars templating engine. I have index.handlebars which was working fine before the release of firebase-tools version 4.0.0.
Still can't update firebase-tools to the latest version.
Comment: I am using express-handlebars as my templating engine.
Comment: Please edit your question to go into more detail about what exactly "no longer works".  What are you expecting that doesn't happen?
Answer: The issue was that I had firebase-tools installed in two different directories on my computer. The directory that was being updated was not the directory that my project was using. I'm still not sure how that happened but I uninstalled firebase and node and reinstalled them and that solved the problem.
Answer: To update firebase-tools, just run this command in the terminal:
curl -sL firebase.tools | upgrade=true bash
note: you must have curl installed.


Expected value of a point/dot to be near the closest side of a square surface?

Question: If we choose a random point inside a square of side length 1, what is the probability for the point is nearest a chosen side of the square?
I would say that the answer is 1/4 since there are 4 sides but I don't think that's right.
Can anyone give a formula proof to this problem?
Picture demonstration:
Comment: What do you mean "near the closest side of a square surface"? Do you mean if you choose a point uniformly in a square, what is the probability it is closest to a given side?
Comment: Heading says *probability*, body says *expected value*.
Comment: @Batman yes that' s correct look at the picture in the link
Comment: @trueblueanil I've changed the heading, sorry for that.
Comment: Seems like you actually wanted probability.
Comment: I've trouble with translating from one language to another... I wish I would had my courses in english...
Answer: If you draw the two diagonals of the square (which divides the square into 4 triangles), note that each triangle contains precisely the points closest to the side of the square it contains (*). Each triangle has $\frac{1}{4}$ of the area of the square by symmetry.
Thus, the probability of a uniformly randomly chosen point in the square to be closest to a given side is $\frac{1}{4}$.
(*) This is easy to see. The points above one diagonal are clearly closer to two sides than the other two sides. Combine this observation with the other diagonal to see the diagonals partition the square by which side the points are closest to.
Comment: I' was just starting to do this xd. Tnx!


Contour Integral for Cosine and a rational function

Question: I've been trying to figure out this integral via use of residues:
$$\int_{-\infty}^{\infty} \displaystyle \frac{\cos{5x}}{x^4+1}dx$$
The usual semicircle contour wont work for this guy as the integrated is unbounded.
My idea came from a book I was reading on contour integration, where we let
$$f(z) = \displaystyle\frac{e^{(-5iz)}}{2(z^4+1)}+\displaystyle\frac{e^{(5iz)}}{2(z^4+1)}$$
And do the integral in the complex play as follows:
$\gamma_{1}= \text{The contour taken to be the top half of the circle in the counter clockwise direction}$ This contour uses the second term in $f(z)$
$\gamma_{2}= \text{The contour taken from $-R$ to $R$ on the real axis}$
$\gamma_{3}= \text{The contour taken to be the bottom half of the circle in the clockwise direction}$ This uses the first term in $f(z)$.
In the end, the contours $\gamma_{1}$ and $\gamma_{3}$ are bounded and will tend to $0$ as $R$ goes to infinity, so that we're left with the two integrals that we want.
My issue now is that when computing residues..everything seems to be cancelling out and I'm getting $0$. Should I take  different contour? I'm really not sure what I did wrong.
Comment: I have some exercises solved on page: http://minerva.ufpel.edu.br/~mauricio.zahn/Var_complexas(2010)/resp_lista_9.pdf Are in Portuguese, but I think it may help you.
Answer: I've given the skeleton of my work below. Fill in any missing pieces and check your answer against mine.
Using $\gamma=[-R,R]\cup Re^{i[0,\pi]}$ and the simple poles at $\frac{1+i}{\sqrt2}$ and $\frac{-1+i}{\sqrt2}$ inside $\gamma$
$$
\begin{align}
\int_{-\infty}^\infty\frac{\cos(5x)}{x^4+1}\mathrm{d}x
&=\mathrm{Re}\left(\int_\gamma\frac{e^{i5z}}{z^4+1}\mathrm{d}z\right)\\
&=\mathrm{Re}\left(2\pi i\left(\left[\frac{e^{i5z}}{4z^3}\right]_{z=\frac{1+i}{\sqrt2}}
+\left[\frac{e^{i5z}}{4z^3}\right]_{z=\frac{-1+i}{\sqrt2}}\right)\right)\\
&=\mathrm{Re}\left(\frac{\pi}{2i}e^{-5/\sqrt2}\left(\frac{1+i}{\sqrt2}e^{i5/\sqrt2}
-\frac{1-i}{\sqrt2}e^{-i5/\sqrt2}
\right)\right)\\
&=\pi e^{-5/\sqrt2}\mathrm{Im}\left(\frac{1+i}{\sqrt2}e^{i5/\sqrt2}\right)\\
&=\pi e^{-5/\sqrt2}\mathrm{Im}\left(e^{i(5/\sqrt2+\pi/4)}\right)\\
&=\pi e^{-5/\sqrt2}\sin\left(\frac5{\sqrt2}+\frac\pi4\right)
\end{align}
$$
Mathematica 8 agrees numerically, but its closed form involves complex functions and looks nothing like what I have above.
Answer: No need to compute two different integrals. Note that $\cos 5x = \operatorname{Re} e^{5ix}$. Put
$$ f(z) = \frac{e^{5iz}}{z^4+1} $$
and integrate over the boundary of a half-disc in the upper half-plane. On the semi-circle $C_R^+$:
$$
\left| \int_{C_R^+} \frac{e^{5iz}}{z^4+1} \right| \le \frac{1}{R^4-1} \cdot \pi R \to 0
$$
as $R \to \infty$ since $|e^{5iz}| \le 1$ in the upper half-plane. Compute the relevant residues and finish off by taking the real part.


Angularjs img id post to database

Question: I'm making a recipe book with angularjs and i have chosen that when the user clicks on an img of the food they want to make, the id of that img tag is posted from a controller to a factory, where the factory makes a database query for a recipe matching the id.
Controller:
<code>$scope.trigger = function(id){
    var id = id;
    recipeFactory.getIngredients(id)
        .then(function(returnedirecipe) {
            ingredientinfo=[
                (returnedirecipe[0].RecipeName),
                (returnedirecipe[0].RecipeDescription)
            ];
        }
}
</code>
Factory:
<code>function recipeFactory($http){
    return {
        getIngredients : function(id){
        var promise=  $http.post("http://localhost:8080/angularcookbook/ajax/recipesdb.php", {RecipeName: id})
            .then(function (response) {
                var jsonResult = response.data;
                return jsonResult;
            })

            return promise;
        }
    }
}
</code>
This works all fine, I can display the data on the same file I've made the query on. My question is how could I return the query from the factory to a new controller? The goal would be to display the recipe on a separate html file with it's own controller.
Comment: Wouldn't hurt to format the code :)
Answer: I think this should help you:
http://fdietz.github.io/recipes-with-angular-js/controllers/sharing-code-between-controllers-using-services.html
:)

Angularjs img id post to database


Tradução de um site sem cms

Question: Olá, tenho um site apenas em html, css e js. O cliente pediu para inserir um botão de alteração de lingua. Inglês e português apenas. Eu gostaria de saber se existe alguma ferramenta ou maneira de fazer este processo apenas usando o js ou se terei que traduzir a página inteira e então criar a ancora redirecionando entre os dois arquivos.
Desde já obrigado pela atenção.
Comment: Acho que você teria de usar i18n, você pode usar dois HTML [en e pt], só não sei se seria viável para seu projeto, ou pode inserir o google translate para o seu site.
Answer: Nathan, antigamente existia um recurso do Google tradutor que era possível incluir um botão mas foi removido, então se o seu site é estático talvez criar uma página html em outro idioma seja mais rápido, você pode traduzir colocando a url lá no google tradutor que ele gera uma página traduzida, depois é só você copiar o código fonte, talvez ajude.
Olha o exemplo: https://translate.googleusercontent.com/translate_c?depth=1&rurl=translate.google.com&sl=pt-BR&sp=nmt4&tl=en&u=https://pt.stackoverflow.com/questions/370108/tradu%25C3%25A7%25C3%25A3o-de-um-site-sem-cms&xid=17259,15700022,15700186,15700190,15700248,15700253&usg=ALkJrhiJWUBzVkGYs1dFDEEURXCgFFRgCQ

Tradução de um site sem cms


Hardening Captcha security

Question: Nearly all websites use CAPTCHA images to protect their forms from spam. But is this the most secure way? As far as i understand, the idea of CAPTCHA is to challenge the user with an image containing some "hard-to-recognize" text so that if the visitor is a human being (not a bot) he/she will be able to post data but not machines. The website sends the captcha code (image) and a session variable containing perhaps a hashed version of the captcha image (the correct answer but hashed). The user submits the form and the server has to make sure that the hash of the letters he/she typed = the hash contained in the session variable.
Fine, what if i (the spammer) wrote a piece of software that mimics that same request and sends it to the server? in other words, if the captcha is abc123 and the hash (in the session variable which can be read with any HTTP sniffer) is xyz345 (consider this a 32 character string) and i sent this data to the server in a post request? Then i start to be more creative, i put this code in a 10,000 loop that will overwhelm the server with spam data! Now is CAPTCHA that secure? are their any options by which i can face such a threat?
Thanks
Comment: am sorry but as far as i understand Session is a server side entity and its not transported to client by any means, i couldn't understand the concept of Sniffing session variables , could you please elaborate a bit more ?
Comment: Sessions are contained in the HTTP request of the user. It should be there, otherwise the server won't "recognize" the user. Don't forget that HTTP is a stateless protocol.
Comment: Sir , http is a sessionless protocol but the server doesnt send session to the client , it just sends a session identifier to the client which client returns on the next call, the session variable remain only at the server side, so there is no issue of loosing the session values
Comment: Fine, Can i resend this session_identifier over and over? yes i can and i already wrote a C# program that did this very thing. The program was able to bypass the CAPTCHA security for one of my sites and the form was used to send mails to the clients. Imagine the amount of spam that was produced.
Comment: But in that scenario , might be u missed some part where in you were allowing to send it without the Captcha, and ya if you still feel that you can , try your hands on any production running popular sites that need captach, may be something like gmail  ,try to bypass their captchas
Comment: I did send the CAPTCHA code in the POST variables, together with the session identifier. By the way the site i tried it on was a production one (not gmail of course but it was in business).
Comment: no i didnt specifically mean, but what you are saying is like u send the form without captcha and submitted , well that might be a flaw in the application. but honestly i dont forsee any chance that the user will be able to pass the captcha if thats properly implemented and captcha is used all over to avoid the programmatic users like bots and other things, though captcha can be cracked if you are able to detect the text in captcha using your programs and submit that value
Answer: Your assumptions are wrong: Neither can the session data be read by the client nor are Captchas meant to mitigate DOS attacks.
A Captcha is a challenge/response technique where the server issues the client a challenge that is meant to be only solvable by a human. An optical character recognition (OCR) challenge that most of the Captchas present is just one variant but certainly a good one as OCR is easier for most literate humans but pose a problem for computers.
But any Captcha is worthless if the response to the challenge is easy to guess, to derive, or to obtain otherwise. Sending the expected response in plain or in a derived form in a hidden form field is such an example. Having the response passed to the Captcha image as a parameter is another example.
That's why the expected response should stay at the server side, as a session datum, that is not readable by the client as only the session's identifier is transmitted.
Your second concern, that Captchas can't prevent DOS attacks, is true. Again, that's not the reason Captchas were supposed to solve. Captchas were invented to "tell computers and humans apart" and nothing else. They can only help to prevent automated spamming to succeed. But frankly, intense challenge/response generation is rather likely to lead to DOS.
Answer: Captcha is not a way to prevent stealing session cookies. If you want secure sessions use e.g. HTTPS.
Captcha does not prevent (D)DOS attacks, if you want your server to be save against 10.000 spam requests per second, put countermeasures against that.
The only purpose of a captcha is to decide whether a request comes from a human being or a machine. That shall prevent automated scripts that create accounts and such but you still have to secure your website including the security of the captcha by other means. A server that exposes the answer of a captcha or lets the user decide which captcha to solve is doing it wrong.
The ideal captcha would be trivial to solve for every human but impossible to solve for every machine. So it should not be a challenge for the user. Machines are unfortunately pretty good so you have to raise the challenge and that makes it hard for us too.
Comment: I was not talking about DDOS attacks. I was talking about attacking the purpose CAPTCHA code existed at the first place: I can send the "legitimate" request to the server that appears to be coming from a human being while it is originating from a bot that i created that will mimic a genuine request by just adding the "correct" session variable to my request. This "correct" session variable can be grabbed from any HTTP sniffer that sniffs one (only one) request from a human. The bot will re-generate this request as many times as needed to create accounts or send mails. Do you get the idea?
Comment: Not the captcha's fault if that works. If you authenticate once and can do as many requests with that session as you want then your problem is in your authentication schema. If you simply require a new captcha authenticated session for every action that can be abused you can't do anything with sniffing since your session is not valid for more than 1 action.

Hardening Captcha security


Exercise on compactness

Question: I came across an exercise on compactness and, though it seems really easy, I can't get it done! I'd appreciate it if you gave me some sort of hint and not the full solution!
So, here it is:
Let $(X,τ) $ be a topological space, $\left \{F_i :i\in I \right\}$ a collection of closed subsets and $U$ an open subset of $X$ such that $\bigcap_iF_i \subseteq U$. If some $F_{i_0}$ is compact, then there are $i_1, ..., i_n \in I$ such that $\bigcap_{k=0}^{n}F_{i_k} \subseteq U$.
Thoughts:
1) I believe that the trick right here is to show that $U^{c}$ is compact, but there's nothing to lead me there.
2) Just because we are working with closed sets I believe that the F.I.P. (finite intersection property) will come in handy, but I really can't see how this is going to happen.
Thank you in advance!
Answer: Hint: by relativizing to $F_{i_0}$, you can reduce the question to the case when $X$ itself is compact. The condition that $
\bigcap_i F_i\subseteq U$ is equivalent to $\bigcap_i(F_i\setminus U)=\emptyset$.
Comment: First of all, thank you for answering! Secondly, can you tell me if the following is correct? The sets $K_i:=F_{i_0}∩F_i∩U^{c},i∈I$ are closed subsets of the compact space $F_{i_0}$, so if they have the FIP, then $⋂_i K_i$ is nonempty. But, because $⋂_i K_i=∅$, we have the desired result!
Comment: @SotirisSimos: Yes, that seems correct.
Comment: @SotirisSimos: Glad you are happy. If you think your question is resolved, you should mark the preferred answer (by clicking the tick sign under the voting arrows).

Exercise on compactness


Por qual motivo, tenho de dar um duplo clique no bookmarklet pra inserir um conteúdo dinâmico

Question: Desenvolvi um pequeno plugin comumente conhecido como bookmarklet. Resultado esta quase satisfatório para meu caso, no entanto esta havendo um empencilho. Para mim iniciá-lo tenho de dar um duplo clique senão, ele não lança o player na página. Uma vez que toda a função contém os elementos de modo dinâmico, ou seja, será incluso em tempo de execução no documento HTML.
Meu Bookmarklet

javascript:(function(){
var head=document.getElementsByTagName('head')[0];
var scriptA=document.createElement('script');
scriptA.setAttribute('type', "text/javascript");
scriptA.setAttribute('src', "http://releases.flowplayer.org/js/flowplayer-3.2.13.min.js");
head.appendChild(scriptA);
var link=document.createElement('a');
link.setAttribute('class', "player");
link.setAttribute('id', "player");
link.setAttribute('href', "http://www.hdwplayer.com/videos/2012.mp4");
link.setAttribute('style', "display:block;width:1280px;height:720px;margin:10px auto");
document.getElementById('video').appendChild(link);
var body=document.getElementsByTagName('body')[0];
var scriptB=document.createElement('script');
scriptB.setAttribute('type', "text/javascript");
scriptB.innerHTML='flowplayer("player", "http://releases.flowplayer.org/swf/flowplayer-3.2.18.swf")';
body.appendChild(scriptB);
}())

Abaixo esta a estrutura do documento HTML, pra realizar Teste(s) onde plugin bookmarklet irá aplicar o "flowplayer":

    &lthtml>
     &lthead>
      &lttitle>Video</title>
      &ltstyle>
        #video {
            background-color: black;
            border: 1px solid red;
            width: 1280px;
            height: 720px;
        }
      </style>

     &ltbody>
        &ltcenter>
            &ltdiv id='video'>

Resumo
Ele parece não inserir o(s) elemento(s) html e/ou script na primeira inserção com apenas um clique. Isso mostra que somente parte da função é inclusa na página HTML faltando um segundo clique para que complemente o primeiro, fazendo assim a inserção do flowplayer. Mas porque isso ocorre???

Acho que algo em torno do innerHTML

Se eu der um clique só, a saída no console exibi o seguinte alerta:

Após clicar novamente, não ha alerta no console. Tudo flui normalmente.

Atenção - FlowPlayer requer FlashPlayer.
Answer: O que acho que está acontecendo é que o script do flowplayer ainda não terminou de ser carregado na página e por isso que aparece o erro flowplayer is not defined no primeiro clique e funciona sem problemas no segundo (por que quando você clica a segunda vez ele já está na página). Eu alterei seu script para utilizar o flowplayer após ele ser inserido na página.
Tenta utilizar esse script:
javascript:(function(){
var head = document.getElementsByTagName('head')[0];
var scriptA = document.createElement('script');
scriptA.type = "text/javascript";
scriptA.src = "http://releases.flowplayer.org/js/flowplayer-3.2.13.min.js";
scriptA.onload = function () {
  var link = document.createElement('a');
  link.setAttribute('class', "player");
  link.setAttribute('id', "player");
  link.setAttribute('href', "http://www.hdwplayer.com/videos/2012.mp4");
  link.setAttribute('style', "display:block;width:1280px;height:720px;margin:10px auto");
  document.getElementById('video').appendChild(link);
  var body = document.getElementsByTagName('body')[0];
  var scriptB = document.createElement('script');
  scriptB.type = "text/javascript";
  scriptB.innerHTML = 'flowplayer("player", "http://releases.flowplayer.org/swf/flowplayer-3.2.18.swf")';
  body.appendChild(scriptB);
};
head.appendChild(scriptA);
}())

Tudo que depende do flowplayer foi movido para dentro de scriptA.onload que é um callback que só será executado depois que o script do flowplayer for carregado na página.


Modelling clustered data using boosted regression trees

Question: I'm modelling habitat selection using boosted regression trees (BRTs), which I prefer over linear models for a variety of reasons (modeling complex nonlinear relationships and interactions, multicollinearity, etc.). I now have a dataset that includes repeated measures for individual animals (100s or 1000s per individual). In a linear modeling framework this is easily analyzed with random effects, but I haven't found any way to model clustered data with BRTs.
I found methods that produce individual regression trees (e.g., Mixed Effect Regression Trees (MERT), Regression Trees with Random Effects (REEMtree)). But the only mention I've found of random effects with BRTs is in Buston and Elith 2011 (http://onlinelibrary.wiley.com/doi/10.1111/j.1365-2656.2011.01803.x/abstract), who did a post-hoc residuals analysis to identify group effects.  Is there any way to account for clustering within the BRT analysis itself? Thanks!
Comment: Are you aware of [Mixed-effects random forest](http://stats.stackexchange.com/questions/103730/how-can-i-include-random-effects-into-a-randomforest)?
Comment: I am not sure if I have the right to share their code. But we wrote a simplified function [MixRF](https://github.com/randel/MixRF/blob/master/R/MixRF.r). It's based on `lme4` so there are many possibilities. Maybe you can try the example therein.
Comment: Thanks Randel. Yes, I read that paper and tried contacting the first author for the R program, but got an auto-reply saying she's on maternity leave. Can you or anyone else point me to a copy of the R code?
Comment: We wrote a open-source Python implementation of mixed effects random forests from the paper quoted above. You can easily extend to make the base learner a boosted regression tree if you want. https://towardsdatascience.com/mixed-effects-random-forests-6ecbb85cb177 https://github.com/manifoldai/merf
Comment: Any update on this issue? I'm having the same problem four years later. @Michel how did you solve your problem?
Answer: If you want to use boosted trees instead of linear models, you essentially have three options: (i) you can ignore the grouping structure, (ii) you can include the grouping structure (i.e. the animal ID in your case) as a categorical variable (this corresponds to using fixed effects), (iii) or you can use a boosting algorithm that explicitly accounts for the clustering structure using random effects.
Option (i) is in general not a good idea as you ignore potentially important information when ignoring the clustering. Also, option (ii), including the grouping ID (animal ID in your case) as a categorical variable, can have drawbacks: learning is not efficient when there are many categories and a relatively small number of samples per category, and tree algorithms can have problems with high-cardinality categorical variables. The third option avoids these issues.
The GPBoost library with Python and R packages builds on LightGBM and allows for combining tree-boosting and mixed effects models. Simply speaking it is an extension of linear mixed effects models where the fixed-effects are learned using tree-boosting. See this blog post and Sigrist (2020) for further information.
Disclaimer: I am the author of the GPBoost library.


Specify the convergence of function series

Question: The task is to specify convergence of infinite function series (pointwise, almost uniform and uniform convergence):
a) $\displaystyle \sum_{n=1}^{+\infty}\frac{\sin(n^2x)}{n^2+x^2}, \ x\in\mathbb{R}$
b) $\displaystyle\sum_{n=1}^{+\infty}\frac{(-1)^n}{n+x}, \ x\in[0;+\infty)$
c) $\displaystyle\sum_{n=0}^{+\infty}x^2e^{-nx}, \ x\in(0;+\infty)$
I know basic facts about these types of convergence and Weierstrass M-test, but still have problems with using this in practise..
Comment: "almost uniform"?
Comment: @David: uniform except for a set of measure $0$? (at least that is how i know the literal german translation)
Comment: I was taught (hence I had to explain this concept into English and sorry I didn't clarify) that almost uniform is a weaker version of uniform convergence. The series converges almost uniformly when it converges uniformly after cutting the domain to any interval. Especially uniform convergence implies almost uniform convergence.
Answer: First observe that each of the series converges pointwise on its given interval (using standard comparison tests and results on $p$-series,  geometric series, and
alternating series.
Towards  determining uniform convergence, let's first recall the Weierstrass $M$-test:

Suppose $(f_n)$ is a sequence of real-valued functions on the set $I$ and $(M_n)$ is a sequence
  of positive real numbers such that  $|f_n(x)|\le M_n$ for $x\in I$,
  $n\in\Bbb N$. If the series $\sum M_n$ is convergent then $\sum f_n$
  is uniformly convergent on $I$.

It is worthwhile to consider the heart of the proof of this theorem:
Under the given hypotheses, if $m>n$, then for any $x\in I$
$$\tag{1}
\bigl| f_{n+1}(x)+\cdots+f_m(x)\bigr|
\le| f_{n+1}(x)|+\cdots+|f_m(x)\bigr|
\le M_{n+1}+\cdots M_n.
$$
So if $\sum M_n$ converges, we can make the right hand side of $(1)$ as small as we wish. Noting that the right hand side of $(1)$ is independent of $x$, we can conclude that $\sum f_n$ is uniformly Cauchy on $I$, and thus uniformly convergent on $I$.

Now on to your problem:
To apply the $M$-test, you have to find appropriate $M_n$ for the series under consideration. Keep in mind that the $M_n$ have to be positive, summable, and bound the $|f_n|$.  Sometimes they are easy to find, as in the series in a). Here note that
for any $n\ge 1$ and $x\in\Bbb R$,
$$
\biggl| {\sin(n^2x)\over n^2+x^2}\biggr|\le {1\over n^2}.
$$
So, take $M_n={1\over n^2}$ and apply the $M$-test.   The series in a) converges uniformly on $\Bbb R$.
 Sometimes finding the $M_n$ is not so easy. This is the case in c). Crude approximations for $f_n(x)=x^2e^{-nx}$ will not help. However, we could try to find the maximum value of $f_n$ over $(0,\infty)$ and perhaps this will give us what we want. And indeed, doing this (using methods from differential calculus), we discover that
 the maximum value of  $f_n(x)=x^2e^{-nx}$ over $(0,\infty)$ is ${4e^{-2}\over n^2}$. And now the road towards using the $M$-test is paved...

Sometimes the $M$-test doesn't apply.  This is the case for the series in b), the required $M_n$ can't be found (at least, I can't find them).
However, here, the proof of the $M$-test gives us an idea.  Since the series in b) is alternating (that is, for each $x\in[0,\infty)$, the series $\sum\limits_{n=1}^\infty{(-1)^n\over x+n}$ is alternating), perhaps we can show it is uniformly Cauchy on $[0,\infty)$.
Indeed we can:
For any $m\ge n$ and $x\ge0$
$$\tag{2}
\Biggl|\,{(-1)^n\over n+x}+{(-1)^{n+1}\over (n+1)+x}+\cdots+{ (-1)^m\over m+x}\,\Biggl|\ \le\  {1\over n+x}\le {1\over n}.
$$
The term on the right hand side of $(2)$ is independent of $x$ and can be made as small as desired.  So, the series in b) is uniformly Cauchy on $[0,\infty)$, and thus uniformly convergent on $[0,\infty)$.
Comment: thank you very much :-) I've analyzed your answer very carefully and understand everything. You've helped me very much, thank you!
Comment: @xan You're welcome; glad to help.


Dynamic create environment and run Cypress parallel

Question: We are using Cypress to run our end-2-end-tests in GitLab. Before we run the test we create a dynamic environment. A dynamic environment is an environment which is created with docker-compoe inside the gitlab runner which executes the cypress tests. After the dynamic environment is up fire the tests against this dynamic environment. Everything happens in one gitlab-runner so no external deployment to a test environment takes place.
Now we want to move forward and parallelize the cypress run. Its documented here https://docs.cypress.io/guides/guides/parallelization and it is working under the assumption that the environment is already there. It creates several GitLab runners and cypress takes care for distribution the scenarios between the runners.
The question is, how to set up a dynamic environment with GitLab which can be shared between GitLab runners? Is it only possible with a dummy deployment to a Kubernetes environment which is prepared for this user case? Do I need create a dynamic environment in each runner? Or any other hints?
Comment: I _think_ I understand what you mean, but could you explain in more detail precisely  what you mean by _dynamic environment_? Ideally, if you're going to parallelize your test cases, they should not be dependent on one another. _Each_ parallel job will create any necessary environment (e.g. like a service container your tests run against). Alternatively, yes, you can do a deploy to a non-production environment and point all your tests running in parallel to that single deployed environment, which is another common pattern.
Comment: Hi @sytech - you already answered the question. The tests are not depending on each other. I hoped that the envionment could be created inside gitlab and then shared by the runners so I do not need an external environment. But seems not to be doable so easy. Thank you!
Answer: Our solution now looks like this.
We start the environment from docker-compose in each running gitlab-job. This of course reduces the time-saving of parallel execution of tests since gitlab runners are blocked longer. But since it happens in parallel and we are not short on runners its OK for us. An other advantage was that we could keep our current setup with only minimal modifications. In the end we reduced our "run all end 2 end tests" - execution time by about 30%


Are the sets of a power set considered "elements?"

Question: I'm trying to review some set theory.  The question I'm encountering is "How many elements are in a power set of a set?"  I know the answer if my interpretation of the question is correct.  If the original set A has n elements, the power set of A will have 2^n new sets within it, but are these sets considered "elements" of the power set, or am I misinterpreting the question?  If these sets are not considered elements of the power set, then is the question asking for the total number of elements of all the sets of the power set?  I'm not entirely sure.
Comment: Each set is an element. In set-builder, $\mathcal{P}(S) = \{ X : \ X \subset S \}$ where $\mathcal{P}$ is the power set "function."
Comment: Should the subset symbol have an underline for possible equality?
Comment: @OscarLanzi likely a [notation difference](https://en.wikipedia.org/wiki/Subset#%E2%8A%82_and_%E2%8A%83_symbols).
Answer: Short Answer: Yes
Long Answer:
I know why this is confusing, but always think of it this way: a set can contain any kind of objects, but the term elements exclusively refers to the objects that are members of the set. For example, if I say $x$ is an element of $y$, then $x\in y$, regardless of what $x$ is, even if it is another set.
Comment: Also in ZFC (for example), everything is a set anyways


Calculus of variations and least action from Feynman lectures.

Question: In Feynman's lecture on least action, he mentions that a perturbation at an extremum of the action functional would cause a zero first order change in the action. Intuitively this makes sense because I find it analogous to the Taylor expansion of a function - at extrema, $f^\prime = 0$ this the first order term disappears. My difficulty is with the fact that the action is a functional, and thus I don't really understand this rigorously.
http://www.feynmanlectures.caltech.edu/II_19.html
Furthermore, the Wikipedia derivation of the Euler Lagrange equation seemed to make sense to me. However, I am unable to connect that derivation to statement made by Feynman.
Comment: I edited the title of your post so the my old buddy Dick Feynman's name is spelled correctly.  Cheers!
Comment: Sorry about that. Thanks for the correction.
Answer: The proof is very easy if you know the multivariable chain rule (for the Calculus of Variations, you need to know the infinite-dimensional version... which is still the same) and the single variable version of this theorem. The statement

he mentions that a perturbation at an extremum of the action functional would cause a zero first order change in the action

made by Feynman would be phrased in the following manner by a Math person:

Theorem:
Let $V$ be a real Banach space (a complete normed vector space), and let $f:V \to \Bbb{R}$ be a differentiable function. If $x_0$ is a local extremum point for $f$, then $df_{x_0} = 0$.

Note that the differential $df_{x_0}$ is itself by definition a continuous linear transformation from $V$ into $\Bbb{R}$. So, what we have to show is that for every "perturbation" $\xi \in V$, we have $df_{x_0}(\xi) = 0$. So, to prove this, pick any $\xi \in V$. Now, define the curve $\gamma : \Bbb{R} \to V$ by $\gamma(t) = x_0 + t\xi$. Now, consider the composite mapping $f \circ \gamma: \Bbb{R} \to \Bbb{R}$. It is clear that $\gamma$ is differentiable, and by assumption, $f$ is also differentiable. Hence, by the chain rule, $f \circ \gamma$ is differentiable at the origin.
Next, note that since $x_0$ is a local extremum of $f$, it follows that $0$ is a local extremum for $f \circ \gamma$. Since $f\circ \gamma$ is a simple mapping from $\Bbb{R} \to \Bbb{R}$, we can use the simple single-variable calculus version of the theorem to conclude that $(f \circ \gamma)'(0) = 0$. Hence,
\begin{align}
0 &= (f \circ \gamma)'(0) \\
&= df_{\gamma(0)}\big( \gamma'(0)\big) \tag{chain rule} \\
&= df_{x_0}(\xi) \tag{by definition of $\gamma$}
\end{align}
This is precisely what we wanted to prove! Since $\xi$ was arbitrary, this completes the proof that $df_{x_0} = 0$.

The theorem proven above is very general. In the particular context of the principle of "least" action, here's how we interpret the above theorem. The Banach space $V$ is usually a set of curves in the configuration space of the system. We interpret $f$ to be the action (I realize the typical notation is $S$ or $J$), and what I called $x_0$ is going to be a " local extremal curve" for the action $f$.
By the way, the Euler Lagrange equations have absolutely nothing to do with the actual statement Feynman made. The statement made by Feynman translated word-for-word into more pedantic and technical mathematical jargon is exactly what I have written in the Theorem above.
What the Euler Lagrange equations tell you is that if the action $S: V \to \Bbb{R}$ is of the specific form
\begin{align}
S(\varphi) := \int_a^b L(t, \varphi(t), \varphi'(t)) \, dt
\end{align}
where $L: \Bbb{R} \times \Bbb{R} \times \Bbb{R} \to \Bbb{R}$ is a smooth function,
then the condition $dS_{\varphi} = 0$ is equivalent to the Euler Lagrange equations:
\begin{align}
\dfrac{d}{dt} \bigg( \big(\partial_3L\big) \big(t, \varphi(t), \varphi'(t) \big) \bigg) - \big(\partial_2 L \big)(t, \varphi(t), \varphi'(t)) = 0
\end{align}
Where $\partial_iL$ means the $i^{th}$ partial derivative of $L$.


Call a php function from inside echo onclick without JS

Question: Looked through some other peoples questions however the replies suggest using JS; however due to the parameters for this project; I don't believe thats viable for me.
Do not use JavaScript/CSSto hide/track/manipulate your data.
anyways I'm echoing this in side of a <?php ?> block:

And above it I have another <?php ?> block that has:
function addToRecentlyViewed($productName){

    // If the cookie is already set lets work with whats in there.
    if( isset($_COOKIE['recentlyViewedProducts'])){
        $products = explode(',',$_COOKIE["recentlyViewedProducts"]);

        // Max of 4 items in the list.
        if(sizeof($products) >= 4){
            // Start -> red, green, blue, yellow and adding purple
            //$products[0] = $products[1];
            //$products[1] = $products[2];
            //$products[2] = $products[3];
            //$products[3] = $productName;
            //end -> green, blue, yellow, purple.
            //$newList = join(",",$products);
        }
        // If less than 4 then just add.
        else{
            // Just append to list.
            //$newList = $_COOKIE["recentlyViewedProducts"];
            //$newList .= ',' . $productName;
            //setcookie["recentlyViewedProducts", $newList];
        }
    }
    // If its not set lets set up the cookie.
    else{
        echo ' HELLO! ';
        setcookie('recentlyViewedProducts', $productName);
    }
}

I can't even get it to echo ' HELLO! ' so I'm thinking I might be doing something wrong :(
ADDED SOME CODE:

This does create the cookie; but it says its deleted automatically. Should I just use infinite time...? Also I've never used these

I'm not breaking the no JS rule am I?
Comment: You cannot execute a PHP function via an `onclick` handler. PHP runs server-side, JavaScript rund client-side. `onclick` attributes are for JavaScript handlers.
Comment: `onclick` is a client event so that only works with JS (which is executed client side). If you want to trigger a PHP script, you need to use an ordinary link (put the URL to the PHP file in the links `href`) which will redirect the client to that page when clicked. You might be able to add an iframe (with width and height set to 0) with an id and set the link target to that iframe if you don't want the client to be redirected.
Comment: That's why you shouldn't use `onclick`! ;-) As @MagnusEriksson said: Use the `href` to pass a `GET` parameter that you can react to
Comment: Who's giving you all these ridiculous restrictions and to what end? If they tie your hands behind your back, you can't really be expected to be able to use them. The restrictions are basically hindering you from doing what you're asking about.
Comment: Those `
Comment: @ConstantinGroß Yea thats what I've been reading,and it makes sense but I don't think I'm allowed to use JS for this :L
Comment: @MagnusEriksson Not really sure what an iframe is :o kind of new around here I did manage to come with something that at least hits the function now though re: my edit :)
Comment: If the code is to track viewed products, you could simply add that code on the product page itself, so when someone lands on a product page, the first thing you do is to run your PHP function before you show the contents.
Comment: @ConstantinGroß Alrighty; I'll give that a try unless you think my edit is worth persuing.
Comment: @MagnusEriksson I tried that prof reminded me that product.php is used to display the product only nothing else. So that was a no go :/
Comment: @ConstantinGroß I thought they might be... They're were supplied in the start package for this project so I doubt the prof will nail me for it; but now I'm going to ask him; thank you for clarifying.
Comment: @MagnusEriksson prof for the php course; and yea I think its a bit much but I get why he wants us to use php since its the php course lol. And it actually says:
Use JS and take an automatic 0
So I'm not about to mess around; espically since its a final and worth a big %
Comment: Sure, but they aren't allowing you to use PHP either since _"product.php is used to display the product only nothing else"_. Either you've misunderstood the requirements, or your professor has given you a very unrealistic scenario which, imho, is nonsense.
Comment: @MagnusEriksson This is a direct quote from our instructions:
***The product page does nothing but pull up information on that clicked-on item***.
So yea I agree its pretty unrealistic.
Answer: Thanks to @MagnusEriksson and @ConstantinGroß for the help
created a separate page so instead of onclick launch function it redirects to a page that sets up the cookies and looks like this:
<?php

    function addToRecentlyViewed($productName){
        //If the cookie is already set lets work with whats in there.
        if( isset($_COOKIE['recentlyViewedProducts'])){
            $products = explode(',',$_COOKIE["recentlyViewedProducts"]);

            //Max of 4 items in the list.
            if(sizeof($products) >= 4){
                //Start -> red, green, blue, yellow and adding purple
                $products[0] = $products[1];
                $products[1] = $products[2];
                $products[2] = $products[3];
                $products[3] = $productName;
                //end -> green, blue, yellow, purple.
                $newList = join(",",$products);
                setcookie("recentlyViewedProducts",$newList);
            }
            //If less than 4 then just add.
            else{
                //Just append to list.
                $newList = $_COOKIE["recentlyViewedProducts"];
                $newList .= ',' . $productName;
                setcookie("recentlyViewedProducts", $newList);
            }
        }
        //If its not set lets set up the cookie.
        else{
            echo 'woo hoo!';
            setcookie('recentlyViewedProducts', $productName);
        }

    }

    addToRecentlyViewed($_GET["productName"]);
    header('location: product.php?product='.$_GET["productName"]);
?>

Best of luck to all :D


How i can prove that $x^2=x\cos(x)+\sin(x)$ has 2 real roots?

Question: How i can prove that $x^2=x\cos(x)+\sin(x)$ has 2 real roots?
I have tried to solve this by studying $f(x)'$ and $f''(x)$, and lateral limits $\lim f(x)$ when $x$ tends to $+$ and $-$ $\infty$.
Studying the first derivate has a minimum value when $x=0$ and $f(0)=1$. As the second derivate is $>0$ that minimum value is relative 'local'.
When the limit tends to + infinity = $+\infty$  and when the limit tends to - infinity = $-\infty$
I do not know what to conclude. Can anyone help me to resolve this problem, thanks
Answer: Clearly $x = 0$ is a real root (just plug $0$ into both sides). As $x \rightarrow +\infty$, then $f(x) = x^2 - x\cos(x) - \sin(x)$ is positive. However $f'(0) < 0$ and so there is a neighborhood $(0,y)$ where $f(x)$ is negative. But since it is eventually positive by the intermediate value theorem it must've hit $0$ somewhere in between.
Comment: And why when I graph the function I see two different roots that are distinct from 0? [function graph by Wolfram](https://www.wolframalpha.com/input/?i=x%5E2%3Dxsen%28x%29%2Bcos%28x%29)
Comment: Because that's $x^2 = x\sin(x) + \cos(x)$ which not what you originally asked for.
Comment: Ok you are right, thanks
Comment: You wont see roots distinct from zero, the equation has two roots including zero!
Comment: @Bhauyal Simply graphing it shows a real root around $1.173$, not sure why you think it has no other real root.