500 Internal Server Error due to htacess config

Question: I tried to configure my htacess for multiples reasons :
First I have my views pages in this path : mywebsite.fr/views/contact-us.php (for example). I want access to files in the /views without being in the url and without extention format; like this : mywebsite.fr/contact-us
I written this lines and it working very nicely :
<IfModule mod_rewrite.c>

Options +FollowSymlinks
RewriteEngine on
RewriteBase /

# Retirer les extensions des pages et les rendre accessibles en lecture
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]

# check to see if the request is for a PHP file:
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*)$ /$1.php [L]

# WWW => domaine
RewriteCond %{HTTP_HOST} www.mywebsite.fr
RewriteRule (.*) http://mywebsite.fr$1 [L,R=301]

# Suppression d'un sous répertoire
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /views/$1 [QSA,L]

But when I try to open an unexisting page, I have a redirection in page error 500 Internal Server Error instead my 404 page custom...
Theses error pages are in this path : mywebsite/views/errors/404.php
And I written this lines in my htaccess file :
ErrorDocument  404  /views/errors/404

Maybe someone can say me why the page 404 are not deployed ? Thank's
Comment: `Maybe someone can say me why the page 404 are not deployed?` Yes, your apache error log will.
Comment: Ahm, you don't have to put the extension in your /views/errors/404, like */views/errors/404.php*?
Comment: Do you have another htaccess file?
Comment: @DimasPante I tried with extension but anything changed. I also read this post but I dont know how, and where I have to read the exeption format in my RewriteRule (If I have to ...). http://stackoverflow.com/questions/20752140/500-internal-server-error-when-trying-to-use-errordocument-to-handle-request#_=_
Comment: @JonLin Yes I have in the directory /view but he is empty. He shouldn't ?
Answer: Unless you have an htaccess file in /views/ with rewrite rules in it, this rule will cause a rewrite loop:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /views/$1 [QSA,L]

If you go to /not-exist the two conditions will pass, and the URI gets rewritten to /views/not-exist, and the rewrite engine loops. Since that doesn't exist either, your conditions will pass again, and the URI gets rewritten to /views/views/not-exist, etc.
Try:
RewriteCond %{DOCUMENT_ROOT}/views/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/views/$1 -d [OR]
RewriteCond %{DOCUMENT_ROOT}/views/$1.php -f
RewriteRule (.*) /views/$1 [QSA,L]

Comment: That working ! Thank's u for the tip about the rewrite loop... Now the problem is... When I go in mywebsite.fr I have a redirection to 403 (custom page).
Answer: Ok, I found finally the solution :
<IfModule mod_rewrite.c>

    Options +FollowSymlinks
    RewriteEngine on
    RewriteBase /

    # Retirer les extensions des pages et les rendres accessibles en lecture
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
    RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]

    # check to see if the request is for a PHP file:
    RewriteCond %{REQUEST_FILENAME}\.php -f
    RewriteRule ^/?(.*)$ /$1.php [L]

    # Suppression d'un sous répertoire
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/views/$1.php -f
    RewriteRule (.*) /views/$1 [QSA,L]

</IfModule>

And for my custom error pages :
ErrorDocument  401  /views/errors/401.php
ErrorDocument  403  /views/errors/403.php
ErrorDocument  404  /views/errors/404.php
ErrorDocument  500  /views/errors/500.php

Now all working correcly.
Comment: It would be most helpful to others to edit the answer to point out which parts caused the error and how you fixed it without having to do a line by line comparison.  After all, the point of SO is _"to build a library of detailed answers to every question about programming"_.  Thanks.


How to store instances of the same object in PHP (stateless)?

Question: I was looking at "Pimple", Fabien Potencier's "simple service container" for PHP, and I was intrigued by the following comment:

By default, each time you get a service, Pimple returns the same instance of it. If you want a different instance to be returned for all calls, wrap your anonymous function with the factory() method.

Based on how PHP is executed, how on earth would this be possible? Wouldn't PHP give me a new instance of an object every time a PHP script was executed?
EDIT: Pimple link - https://github.com/fabpot/Pimple
Comment: The docs are not implying persistence across executions, rather that calling for a service creation multiple times in the same script will return the same object, unless wrapped in the factory method.
Comment: I'm not sure I understand your question completely, but to be clear - PHP **does** always give you a new instance of a class every time a script is run, e.g. a login class that is instantiated on every page of a website has a new instance of itself created every time you open a page.
Comment: Drat, I was hoping this was some Fabien Potencier magic.
Comment: Ah thanks. Figured I was taking it out of context
Answer: Answering this, because nobody in my comments did. The answer - you can't! PHP over HTTP is stateless, and I took the pimple documentation out of context.
If you need to achieve this, you should look into a cache system (APC, memcached) or an object server (Redis).
Thanks for the clarification.


Como usar animate e fadeOut em Javascript

Question: Estou fazendo um site. O cliente quer só uma página com todas as páginas nela, logo pensei em usar seções.
Queria que a cada troca de seção, por exemplo do 'inicio' para 'agencia' esmaecesse a tela com um fade e trocasse nesse intervalo, no final do fade já mostre a outra seção.
Eu consegui fazer ele com animate ele ir para a próxima seção, mas queria fazer o fade, alguém pode me ajudar nisso?
Aqui tem o HTML

  <button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar2">
    ☰
  </button>

        Início (current)

        Agência

        Equipe

        Clientes

        Trabalhos

        Contato

Home

About

Contact

    Previous

    Next

  <button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar2">
    ☰
  </button>

        Início (current)

        Agência

        Equipe

        Clientes

        Trabalhos

        Contato

Home

About

Contact

Agência

Aqui tem o JS que eu fiz
$(document).ready(function(){
    $('.inicio').click(function(){
        $('html, body').animate({
            scrollTop: ($('.section01').first().offset().top)
        },750);
    });
    $('.agencia').click(function(){
        $('html, body').animate({
            scrollTop: ($('.section02').first().offset().top)
        },750);
    });

});

Answer: Se entendi direito, você quer "esconder" as outras seções e "mostrar" apenas a que foi selecionada?
Tente assim:
Primeiro crie uma classe comum para as Divs (Aqui estou chamando de: Divs_Sessoes )
Depois no evento click, basta ocultar todas e mostrar somente a que foi selecionada. Por exemplo:
function SeuEventoClick()
{
     $(".Divs_Sessoes").fadeOut(700);
     $("#SuaDivSelecionada").fadeIn(700);
}

Onde você pode até passar por parâmetro a div que deseja dar o FadeIn.
function SeuEventoClick(NomeSuaDiv)
    {
         $(".Divs_Sessoes").fadeOut(700);
         $("#" + NomeSuaDiv).fadeIn(700);
    }


Suggesting closed-form representations of mathematical constants by means of experimental mathematics?

Question: Quite a  few mathematical constants are known to arise in several branches of mathematics (more here). I have no doubt that they are useful to the understanding of some mathematical structures and add to the whole body of knowledge of mathematics as a whole. Sometimes, however, I find myself looking at these constants and I feel unsatisfied. I suspect that more constants can be expressed in more 'fundamental' constants like $\pi, e$ and $\gamma$.
Although Euler probably came close to be a living one, mathematicians of the past did not have computers. We can now use computers to determine te value of the afore mentioned constants with great precision. We can also try to conjecture the exact value of these constants by finding the value of some arithmetic combination of $\pi, e$ and $\gamma$ and the real numbers that corresponds to one of the 'unevaluated' constants with high precision. My question is: have experimental mathematicians 'found' the value(s) of some of the constants I described (by the the method I described or a similar one)?
Thanks,
Max
P.S. If someone knows of a reference to a paper/book that summarizes some results in this subield of a field, I would be grateful to him/her.
Comment: http://oldweb.cecm.sfu.ca/projects/ISC/
Comment: Maybe you will find something interesting on this website (and in the books referred to there): http://www.experimentalmath.info/
Comment: I have seen many attempts to express the fine structure constant or mass(proton)/mass(electron) in terms of mathematical constants, then construct a physical theory that says it has to be that.  None have been seen as convincing by the community, and many have fallen afoul of more accurate measurements of the physical constant they were modeling.
Comment: Bear in mind that almost all numbers are algebraically independent.... I see no reason that suggests certain constants can be written in terms of $\pi$.
Comment: @ Qiaochu Yuan: I think the Inverse Symbolic Calculator is a useful tool, but even the smart lookup option only deals with a few combinations with $\pi$ and $e$ and some function, like ln(x). With a more advanced program, one can make millions of combinations with $pi$ , $e$ and the reals. Do you know of any of such project undertaken by experimental mathematicians?
Comment: @ muad, True, but I'm not talking about just $\pi$, but other constants and all the reals, too.
Answer: I can't resist giving a couple of examples of (contrived) numerical coincidences (both are from Experimentation in Mathematics by J.M. Borwein, D.H. Bailey and R. Girgensohn).
Example 1.
$$\int_{0}^{\infty}\cos(2x)\prod_{k=1}^{\infty}\cos(x/k)\ dx=\frac{\pi}{8}-\epsilon,$$
where
$0<\epsilon<10^{-41}.$
Example 2.
$$\sum\limits_{k=1}^{\infty}e^{-(k/10)^2}\approx5\sqrt\pi-\frac{1}{2}=8.362269254527580...$$
Well, they agree through 427 (four hundred twenty seven) digits yet they are not equal.

A moral. Make sure you understand the context and use your inverse symbolic calculator with caution.
Comment: Example 2 is one of those theta series with exceedingly fast convergence. The reason why some PDEs are easy to numerically approximate is due to this speed. [Here](http://www.cecm.sfu.ca/personal/pborwein/PAPERS/P56.pdf) BTW is the article that preceded the *Experimental Mathematics* book by Borwein *et al.*
Comment: @J. M.: That's right. Thanks for the reference.
Comment: @ Andrey Rekalo: Thanks a lot, this is what I what I was looking for.
Comment: @Max Muller: You're welcome.
Answer: Have you tried the Inverse Symbolic Calculator?
Comment: @Max Muller: that's not how it works.  You input decimal expansions and the ISC tries to guess what the constant is.
Comment: @ Yuval Filmus: no, seeing this website is a first for me. Thanks! It can help to conjecture the value of some constants, although it would take a lot time to try some examples, whereas a good computer program probably can check a lot of values within a shorter time. I think I should point out that I'm more looking for a paper or another reference that presents the method by which closed-form representations of these constants and which "results" (conjectures) it has found already. Thanks for the suggestion, anyway!
Comment: @ Yuval and Qiaochu: I'm trying it now but I'm not able to insert any of the constants I want. I guess one has to punch in the 'mathematica-symbol', but what's the mathematica-symbol of Catalan's constant, for example? And how do I find the mathematica-symbol of other constants?
Comment: @ Qiaochu Yuan: ok... but it also says one can enter a maple expression (I meant that one, not a mathematica-symbol), how do you do that?
Comment: For example, is Catalan's Constant   C  in maple? And what about $\zeta(3)$?
Comment: Catalan, Zeta(3)
Answer: The rational constant for an Apery like series for $$\zeta(4)$$ was found experimentally, using continued fractions.
Comment: @ muad: interesting, I was going to post a question that somewhat relates to this. Thanks, muad.
Comment: "A numerical test (suggested by Cohen) implies that

$\zeta (4)=\frac{\pi ^{2}}{90}=\frac{36}{17}\sum_{n=1}^{\infty }\frac{1}{n^{4}\binom{2n}{n}}$

(...) Apparently such expressions can be generated virtually at will on using appropriate series accelerator identities. Most startling of all
though should be the fact that Apery's proof has no aspect that would not have been accessible to a mathematician of 200 years ago."

http://www.ega-math.narod.ru/Apery1.htm
Answer: Gauss discovered the AGM/elliptic integral connection through the value $$\frac{\omega}{\pi}$$ by experimental mathematics.
Answer: Not many people know that WA is also able of giving you all kinds of possible closed forms concerning fundamental constants, e.g.:
http://www.wolframalpha.com/input/?i=2.9299372410244
You can also click "more"...
Answer: I had a math teacher whose hobby was collecting "first fail" examples.   Some of these were conjectures that were true for hundreds of cases before a counterexample was found.  Matching of numerical constants to many digits should never be used as a proof; rather it should stimulate the hunt for a proof.


How to query all fields of the node that is tagged with taxonomy term from a specific vocabulary

Question: I'm struggling to find a way to retrieve all the node fields where a specific taxonomy is implemented. I was close to find something with this query :
$query = db_query('SELECT fci.field_name
    FROM d7_field_config_instance fci
    LEFT JOIN   (SELECT tv.vid, tv.machine_name
    FROM d7_taxonomy_vocabulary tv
    LEFT JOIN d7_taxonomy_term_data ttd
    ON tv.vid = ttd.vid
    WHERE ttd.tid = 76) AS tax
    ON tax.machine_name LIKE fci.bundle'));

But it seems like machine_name and bundle have different values for a same technology.
The idea is : From a taxonomy id => find taxonomy vid (vocabulary id) => find machine name of the vocabulary => find the bundles where this vocabulary is used.
Any help would be appreciated.
Solution  : Thanks to @Eugis' answer (Accepted answer), I came up with this solution :
db_query("SELECT fcf.field_name, fcf.data FROM
          (SELECT fc.field_name, fc.data FROM field_config fc
          WHERE fc.type LIKE 'taxonomy_term_reference') AS fcf
        INNER JOIN field_config_instance fci
          ON fcf.field_name = fci.field_name
          AND fci.bundle LIKE :bundle",
      array(':bundle'=> $bundle));

Hope it'll help someone else.
Comment: I edited the title of your question to reflect your goal better. Please correct it if I went in a wrong direction.
Comment: No that is perfect. Thanks for correcting my approximate English ^^
Answer: I think, you should check the field_config table where type = 'taxonomy_term_reference'.
The vocabulary name where the field is referencing to is stored in the data column as BLOB. you can use the unserialize php function to extract the data stored in the BLOB. That's because you can't reach it with a single select query.
Try using loops and ifs :)


Create a view that links to another view

Question: I'm trying to create a view that works as category page (aggregates a list of titles from content pages I've created). I need that list to link out to another view that is used to display photo galleries. Am I approaching this the correct way?
I want it to be dynamic so the customer can create photo galleries and they will automatically populate in the category page; then, a link send you to the proper display view.
Comment: Hi ! - Are you photo galleries content types or taxonomy terms ? When you say "link out to", do you mean simply display a link to the page of the gallery ?
Comment: Hi Gregory. As it is right now- I'm just using content types with a tag (with unlimited image field) to display a certain gallery. I want to be able to have several galleries and seperate them within categories. Should I do this another way?
Comment: I figured out what to do. I created a new field on the content page, used it as the gallery view url. Then used the rewrite token of that field for linking url. The title categories will now go to that view. Thanks for the help. -James
Comment: It's great that you figured it out. You can submit an answer to your own question to help others with the same problem.
Answer: Suppose the name of views are view1 and view2 as content pane.You have to link view2 to view1.
For linking one view to another you would have to follow some simple steps:

In view2 you have an option under PANE SETTINGS 'Link to view' and select Yes.
In view1 also you have an option under PANE SETTINGS 'Link to view' and select Yes.
Now decide the place where you want to display view2.
Suppose its the footer region. Go to the footer region and add a Global:View area.
There you have a list of all views. Select view2 and save the view.

This way you can let one view execute under another view.
Comment: This option will only be seen if you create a panel pane.
Comment: Could you, please, supply a screen shot. I could not able to find `Pane Settings`?!
Comment: @sємsєм, make sure you are creating a custom pane instead of block of the view.
Answer: Solution to this issue:
Use a tag, on your content page, that has the same url as your gallery view has. Make sure that the order of your fields, in the views config page, has the title field coming after the tag field.....in order for the tokens to appear in the rewrite section of the title field. Add the content:tag token to your title field, as the link url. Now you have a category page that uses titles to link to view galleries. Create view as a block to offer list on other pages.


Compute the $Cov(X,Y)$ of the two random variables

Question: Let $X,Y$ be absolutely continuous random variables. $X$ is $Uniform[0,12]$ and $f_{Y|X}(y|x)=\frac{1}{x}$, for $y\in [0,x]$ and $0$ otherwise.
We are asked to find $Cov(X,Y)$.

$Cov(X,Y)=E(XY)-E(X)E(Y)$.
Usually in these types of problems, I'm given $Y=X^2, X+3$, or a function of $X$. Here I am given the conditional function.
So, $f_{Y|X}=\dfrac{f_{XY}(x,y)}{f_{X}(x)}$, by definition.
We know the $f_X(x)=\dfrac{1}{12}; 0\leq x \leq 12$, as it is uniform.
Then, we get that $\dfrac{1}{x}=\dfrac{f_{XY}(x,y)}{(1/12)}\to f_{XY}(x,y)=\dfrac{1}{12x}$
This is as far as I got.
To find $f_Y$, I need to integrate $f_{XY}$ over a range ($x$ values). What is this range?
We have firstly that $0 \leq y \leq x$, and then we have $0 \leq x \leq 12$. How can I combine these two?
I don't know what to integrate $f_Y$ over.
Comment: Not a duplicate, mse accidently posted it twice, I don't even know how thats possible
Comment: Don't forget the condition that $0 \le y \le x$ in your formula for $f_{XY}(x,y)$.
Answer: Hint:
You know $0 \le x \le 12$ and $0 \le y \le x$, which you can combine into $0 \le y \le x \le 12$
Write the joint density with an indicator function taking the value $1$ when the condition is met and $0$ otherwise
$$f_{XY}(x,y)=\dfrac{1}{12x} I{[0 \le y \le x \le 12]}$$
Then you want to integrate this over $x$ to get the marginal density for $Y$ and then adjust the limits of integration to respect the indicator function
$$f_{Y}(y)=\int_{x=-\infty}^{\infty} \dfrac{1}{12x} I{[0 \le y \le x \le 12]} \, dx= \int_{x=y}^{12} \dfrac{1}{12x} I{[0 \le y \le 12]} \, dx$$
and that integral is not particularly difficult: you will be left with a function of $y$ multiplied by an indicator function depending on $y$ showing where the marginal density is non-zero

Alternative hint:
You know that $E[Y \mid X=x]=\frac{x}{2}$ so $E[Y \mid X]=\frac{X}{2}$
This will give you $E[Y]=\frac12E[X]$ and $E[XY]=\frac12E[X^2]$
So $\text{Cov}(X,Y)=\frac12E[X^2]-\frac12(E[X])^2 = \frac12\text{Var}(X)$ which you can calculate
Comment: I really liked Henry's Alternative hint.  Similarly, one could define $Z= Y-X/2$.  It's not too hard to see that Cov(Z,X)=0, so  Cov(X,Y) =  Cov(X,X/2+Z) = Cov(X,X/2) = $\sigma_X^2/2$.


Making a script into a linux service

Question: -- EDIT, still some issues --
OK my script uses a loop to wait for network connections. So when I run it, even with daemon it will just sit there and not take me back to the shell. I tried su -c "/home/webreports/report-list &" USER    but it tried to run as the user & even though i have it in quotes, i even tried single quotes.
-- Original --
I have made a script (yet to be tested) for running a bash script as a service. I have two questions.
1) how do i get it to run as a specific user? the software we use CANNOT be run as root and will fail horribly if it does (horrible software we are sadly stuck with). So how do i make it run the service as user "JOEBOB" lets say.
2) Do I just put the script file into "/etc/rc5.d " to be able to use "service report-listen start" ?
--- Script --
#!/bin/sh
#
# myservice     This shell script takes care of starting and stopping
#               the /home/webreports/report-listen
#

# Source function library
. /etc/rc.d/init.d/functions

# Do preliminary checks here, if any
#### START of preliminary checks #########

##### END of preliminary checks #######

# Handle manual control parameters like start, stop, status, restart, etc.

case "$1" in
  start)
    # Start daemons.

    echo -n $"Starting report-listen daemon: "
    echo
    daemon /home/webreports/report-listen
    echo
    ;;

  stop)
    # Stop daemons.
    echo -n $"Shutting down report-listen: "
    killproc /home/webreports/report-listen
    echo

    # Do clean-up works here like removing pid files from /var/run, etc.
    ;;
  status)
    status /home/webreports/report-listen

    ;;
  restart)
    $0 stop
    $0 start
    ;;

  *)
    echo $"Usage: $0 {start|stop|status|restart}"
    exit 1
esac

exit 0

Comment: I think not being able to run as root is a feature :)!
Comment: It would be except it will let you run as root and then change all the permissions and lock everyone out, then crash.
Comment: What distribution?
Comment: Redhat enterprise
Answer: Use su to run the script as a different user:
daemon su -c /home/webreports/report-listen johndoe

where johndoe is the user you want it to run as.
Put the script in /etc/init.d/myservice, then symlink it to /etc/rc.d/S99myservice.
Comment: Only issue I have is that it doesn't seem to be running the script in the background. I tried
daemon su -c '/home/webreports/report-listen &' USER
but then it tried to run as the user & even though I have it in quotes
Answer: just copying will not do the job. You have to take care the program is decoupled from stdin and stdout. Therefor all output has to be printed to a logfile. You also have to background the program, which should be done by the daemon function.
Answer: If you're using Ubuntu (Debian based OS) you can base your script on /etc/init.d/skeleton and replace DAMEON var:
DAEMON=su -c "/home/webreports/report-listen" joebob

You will have a pid file also for clean start/stop.
You can start it automatically during boot with (Assuming your service script is named /etc/init.d/my-report-listen):
$ sudo update-rc.d my-report-listen defaults

This method is just an attempt, not a recipie that works. I hope it helps
Answer: Daemonising code is hard to get right.  For this, I use daemontools -- basically it does the hard work of running in the background, and you just write your script as though you're going to run it in the foreground, and then tell daemontools to run it instead.
See http://cr.yp.to/daemontools.html for all the documentatory awesome.
Answer: You haven't mentioned what distribution you're using, but it seems like you're using a Red Hat based one. I'll base my answer on that assumption.
To answer the first part of your question, about running the script on startup. You have to put the script in /etc/rc.d/init.d, and add a "chkconfig" compatible line to allow you to add it to the correct levels with the "chkconfig" command. see a previous question on that issue.
As for starting the script with a specific user. Since you're already using the "daemon" function, you can try using the "--user" switch:
daemon --user=reportsuser /home/webreports/report-listen

Making a script into a linux service


Increase buffer size or time for video-js HTML5 player

Question: how do I increase buffer on video-js HTML5 player? I have a US server and in the US is all fine but clients in EU have loading issues related to video caching.
buffer size in video.js is constant value and I want to change it.
Comment: Did you check my answer?
Answer: You can now customize the buffer length by modifying videojs.Hls.GOAL_BUFFER_LENGTH for change buffer size of HLS videos, I tryed and It's work for me
Comment: @Steve Harrig please mark as answer if it work for you
Comment: How can I use it? videojs.Hls is deprecated and using videojs.tech().Hls does not have GOAL_BUFFER_LENGTH property
Comment: did you find a solution for this?
Answer: For me this has worked (video.js 7.7.6):
let player = videojs('my-player');

player.vhs.options_.externHls.GOAL_BUFFER_LENGTH = 60;

You might also need to change the MAX_GOAL_BUFFER_LENGTH value, e.g.:
player.vhs.options_.externHls.MAX_GOAL_BUFFER_LENGTH = 80;

The case when you might need to increase buffer length values is when your viewers are facing buffering during playback (e.g. the spinner instead of a video). Video.js may give a warnings in the console that means its buffer values have been changed.
Be careful with a buffer length values. If it is a live streaming the browser will continue to load (buffer) video segments and the higher buffer values are the more MB will be downloaded even after pausing/stopping the player.
Video.js DOCS: https://github.com/videojs/http-streaming
Video.js Troubleshooting:
https://github.com/videojs/http-streaming/blob/main/docs/troubleshooting.md
Used Type Definitions for VideoJS:
https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/video.js
Answer: This works for me (video.js 8.0.4):
videojs.Vhs.GOAL_BUFFER_LENGTH = 60*30;
videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = 60*60;
let player = videojs('my-player');

Ref https://github.com/videojs/video.js/issues/7473


Given a complex Gaussian variable $Z$ and a real Gaussian variable $X$, what is the mean of $Z\,e^{b\,X}$?

Question: Eq. 19 of Gershgorin et. al. (2010) states that given a complex Gaussian variable $Z$ and a real Gaussian variable $X$, the mean of $Z\,e^{b\,X}$ is given by
$$\left\langle Z\,e^{b\,X} \right\rangle = \left( \left\langle Z \right\rangle + b\,\text{Cov}\left( Z,\ X \right) \right)\,e^{b\,\left\langle X \right\rangle + \frac{b^2}{2}\,\text{Var}\left( X \right)}.$$
The paper mentions that this quantity can be computed using the characteristic function of a Gaussian distribution, but I'm not sure how one would go about this.
I understand that the characteristic function is the inverse Fourier transform of the probability distribution function, and that the characteristic function of a linear combination of probability distribution functions is a product of the individual characteristic functions, but I don't know how the characteristic functions of $Z$ and $X$ would relate to the characteristic function of $Z\,e^{b\,X}$.
EDIT: I've made some progress on this problem. If we assume that $X$ and $Z$ are independent, with probability density functions $f_{X}\left( x \right)$ and $f_{Z}\left( z \right)$, then we may use the Law of the Unconscious Statistician
$$E\left[ g\left( X \right) \right] = \int_{\mathbb{R}} g\left( x \right)\,f_{X}\left( x \right)\,dx$$
to evaluate
\begin{align*}
     E\left[ Z\,e^{b\,X} \right] &= \int_{\mathbb{C}} \int_{\mathbb{R}} z\,e^{b\,x}\,f_{X}\left( x \right)\,f_{Z}\left( z \right)\,dx\,dz \\
&= \int_{\mathbb{C}} z\,f_{Z}\left( z \right)\,dz\,\int_{\mathbb{R}} e^{b\,x}\,f_{X}\left( x \right)\,dx \\
&= \left\langle Z \right\rangle\,M_{X}\left( b \right)
\end{align*}
where $M_{X}\left( t \right)$ is the moment-generating function of $X$
$$M_{X}\left( t \right) = E\left[ e^{t\,X} \right].$$
Since $X$ is Gaussian, we have
$$M_{X}\left( b \right) = e^{b\,\left\langle X \right\rangle + \frac{b^2}{2}\,\text{Var}\left( X \right)},$$
which means for independent $X$ and $Z$ we have
$$\left\langle Z\,e^{b\,X} \right\rangle = \left\langle Z \right\rangle\,e^{b\,\left\langle X \right\rangle + \frac{b^2}{2}\,\text{Var}\left( X \right)}$$
which is almost there! I am guessing that once we drop the assumption that the desired identity falls out.
Answer: Alright, I figured it out based on some of the references ([15, 16]) in that Gershgorin et. al. 2010 paper.
To begin, let's write $Z = U + i\,V$ so that we may discuss its real and complex parts, and define a vector $\overrightarrow{V} = \left[ U\  V\  X \right]^T$. Note that $\overrightarrow{V}$ is normally distributed since each of $U$, $V$, and $X$ are as well.
The quantity we would like to find $\left\langle Z\,e^{b\,X} \right\rangle$ will come from finding its real and complex parts $\left\langle U\,e^{b\,X} \right\rangle$ and $\left\langle V\,e^{b\,X} \right\rangle$.
To find $\left\langle U\,e^{b\,X} \right\rangle$, we begin by considering the partial derivatives of the moment-generating function $M_{\overrightarrow{V}} \left( \overrightarrow{t} \right)$ for $\overrightarrow{V}$
$$M_{\overrightarrow{V}} \left( \overrightarrow{t} \right) = \int_{\mathbb{R}^{3}} e^{\overrightarrow{t}^{T}\,\overrightarrow{v}}\,f_{\overrightarrow{V}}\left( \overrightarrow{v} \right)\,d\overrightarrow{v},$$
where $f_{\overrightarrow{V}}\left( \overrightarrow{v} \right)$ is the probability density funciton for $\overrightarrow{V}$. We will differentiate this function with respect to the first and second entries of $\overrightarrow{t}$, denoted $t_1$ and $t_2$ respectively
\begin{align*}
  \frac{\partial M_{\overrightarrow{V}} \left( \overrightarrow{t} \right)}{\partial t_1} &= \int_{\mathbb{R}^{3}} u\,e^{\overrightarrow{t}^{T}\,\overrightarrow{v}}\,f_{\overrightarrow{V}}\left( \overrightarrow{v} \right)\,d\overrightarrow{v},\\
   \frac{\partial M_{\overrightarrow{V}} \left( \overrightarrow{t} \right)}{\partial t_2} &= \int_{\mathbb{R}^{3}} v\,e^{\overrightarrow{t}^{T}\,\overrightarrow{v}}\,f_{\overrightarrow{V}}\left( \overrightarrow{v} \right)\,d\overrightarrow{v}.
\end{align*}
Evaluating these partial derivatives at $\overrightarrow{t} = \left[ 0\ 0\ b \right]^{T}$, we obtain
\begin{align*}
  \left.\frac{\partial M_{\overrightarrow{V}} \left( \overrightarrow{t} \right)}{\partial t_1}\middle|_{\overrightarrow{t} = \left[ 0\ 0\ b \right]^{T}}\right. &= \int_{\mathbb{R}^{3}} u\,e^{b\,x}\,f_{\overrightarrow{V}}\left( \overrightarrow{v} \right)\,d\overrightarrow{v} = \left\langle U\,e^{b\,X} \right\rangle,\\
   \left. \frac{\partial M_{\overrightarrow{V}} \left( \overrightarrow{t} \right)}{\partial t_2}\middle|_{\overrightarrow{t} = \left[ 0\ 0\ b \right]^{T}} \right. &= \int_{\mathbb{R}^{3}} v\,e^{b\,x}\,f_{\overrightarrow{V}}\left( \overrightarrow{v} \right)\,d\overrightarrow{v} = \left\langle V\,e^{b\,X} \right\rangle.
\end{align*}
Now, since $\overrightarrow{V}$ is a normally distributed, its moment-generating function is
$$M_{\overrightarrow{V}} \left( \overrightarrow{t} \right) = e^{\overrightarrow{t}^{T}\,\left(\overrightarrow{\mu}_{\overrightarrow{V}} + \frac{1}{2}\,\Sigma\,\overrightarrow{t}\right)}$$
where $\Sigma$ is the covariance matrix of $U$, $V$, and $X$. Hence,
\begin{align*}
   \left\langle U\,e^{b\,X} \right\rangle &= \left.\frac{\partial M_{\overrightarrow{V}} \left( \overrightarrow{t} \right)}{\partial t_1}\middle|_{\overrightarrow{t} = \left[ 0\ 0\ b \right]^{T}}\right. \\
   &= \left. \left( \left\langle U \right\rangle + t_1\,\text{Cov}\left( U,\ U \right) + t_2\,\text{Cov}\left( U,\ V \right) + t_3\,\text{Cov}\left( U,\ X \right) \right)\,e^{\overrightarrow{t}^{T}\,\left(\overrightarrow{\mu}_{\overrightarrow{V}} + \frac{1}{2}\,\Sigma\,\overrightarrow{t}\right)} \middle|_{\overrightarrow{t} = \left[ 0\ 0\ b \right]^{T}}\right. \\
   &= \left( \left\langle U \right\rangle + b\,\text{Cov}\left( U,\ X \right) \right)\,e^{b\,\left\langle X \right\rangle + \frac{1}{2}\,b^2\,\text{Var}\left( X \right)},
\end{align*}
and similarly
\begin{align*}
   \left\langle V\,e^{b\,X} \right\rangle &= \left( \left\langle V \right\rangle + b\,\text{Cov}\left( V,\ X \right) \right)\,e^{b\,\left\langle X \right\rangle + \frac{1}{2}\,b^2\,\text{Var}\left( X \right)},
\end{align*}
Therefore,
\begin{align*}
   \left\langle Z\,e^{b\,X} \right\rangle &= \left\langle U\,e^{b\,X} \right\rangle + i\,\left\langle V\,e^{b\,X} \right\rangle \\
   &= \left( \left( \left\langle U \right\rangle + i\,\left\langle V \right\rangle \right) + b\,\left( \text{Cov}\left( U,\ X \right) + i\,\text{Cov}\left( V,\ X \right) \right) \right)\,e^{b\,\left\langle X \right\rangle + \frac{1}{2}\,b^2\,\text{Var}\left( X \right)} \\
   &= \left( \left\langle Z \right\rangle + b\,\text{Cov}\left( Z,\ X \right) \right)\,e^{b\,\left\langle X \right\rangle + \frac{1}{2}\,b^2\,\text{Var}\left( X \right)}
\end{align*}
as desired.


Are Node.js Buffers as JSON a portable storage format?

Question: If I create  Node.js Buffer containing the bytes of a binary file like a jpg -image, convert it to JSON, can I transport binary content in this way to other machines and have the images viewable on those other machines too?
In other words can I fill a Buffer on one machine with bytes of an image-file, and transport the buffer as JSON to another machine, then restore the image there by simply writing the same buffer to a file with the same name?
Would it work between platforms say Linux Windows and Mac? Does "endiannes" become an issue?
Would TypedArrays be a better solution?
Comment: If it's just an "image" such as a JPG as stated, then diffrerent OS implementations and processor architectures do not care about such things. The worry would be executable content, where it *does* make a difference. As noted, the simplest solution is generally just to send the file, and common transfer protocols handle the how level stuff like byte order for you. For more complex data structures, then a standardized binary format in network byte order is generally preferred.
Answer: JSON isn't useful for transferring binary data... at least, not efficiently.  You would have to base64-encode the data before putting it in JSON, which increases its size by 33% and adds an extra layer of processing on each end.
There is another standard serialization format you can use called CBOR.  It's binary in nature and supports a byte string.  There are libraries for many languages.
Comment: @PanuLogic The best thing to do is just to send the file itself.  If you can't do that and must send some sort of structured data, CBOR is incredibly well supported.  It's been standardized for years (https://tools.ietf.org/html/rfc7049), and Wikipedia lists many implementations (https://en.wikipedia.org/wiki/CBOR#Implementations).
Comment: Thanks for the link on CBOR. What if efficiency is not a concern?  Say I need to do it just for a few small images, occasionally? My concern is more portability of the images and other binary content, than efficiency


Expected number of shots for a game to end

Question: A basketball player plays a shooting game. He gets +1 point if he scores a basket and -2 points if he misses. He starts with 0 points. The game ends when the player reaches +10 or -10. What is the expected number of shots taken for a game to end, given a player scores a basket with probability p.
Comment: You have to specify the probability of the player to score a basket.
Comment: @Phani Raj I did "given a player makes a basket with probability p." Sorry if the problem is a little hard to read.
Answer: For $-11\le n\le 10$, let $e_n$ denote the expected number of rounds until a score $\le -10$ or $\ge 10$ is reached when starting with a score of $n$.
Clearly, $e_{-11}=e_{-10}=e_{10}=0$ while for $-10<n<10$ we have $e_n=1+pe_{n+1}+(1-p)e_{n-2}$. This gives you $19$ linear equations in $19$ unknowns.


Using jQuery to iterate across like named checkboxes

Question: I am trying to use jQuery each() to iterate across a group of checkboxes named supplier_type[].  They all have unique ids so I could just re-write this to handle an array of unique ids but I wanted to figure out where I went wrong here.
The alert shows that while intIndex sees the correct number of elements this always holds the first element.
function setUp(){
    $( 'input[name=supplier_type[]]' ).each(
        function( intIndex ){
            var type = $(this+':checked').val() + 'Table';
            $("#"+type).show("slow");
            alert($(this+':checked').val());  // sees first one each iter
        }
    );
}

So how do I address the correct element?  Do I need to use bind()?
Thanks!
// Edit
Working version based on Drew Wills response.  Thanks Drew!
function setUp(){
    $( 'input[name=supplier_type[]]' ).each(
        function( intIndex ){
            if($(this).attr('checked')) {
                var type = $(this).val() + 'Table';
                $("#"+type).show("slow");
            }
        }
    );
}

Answer: I'm not sure I understand your question 100%, but I'm very suspicious of the following style of selector:
$(this+':checked')

I'm guessing you want to know the value of the 'checked' attribute, which would be more like...
$(this).attr('checked')

Comment: Thanks for the reply.  Am I misusing this?  http://api.jquery.com/checked-selector/
Comment: The ':checked' selector matches instances that are checked, it doesn't tell you whether a given instance is checked or not.  What do you get if you do alert(this+':checked')?  I'm surprised that this concatenated string matches anything at all.


Help with proof of a converging sequence.

Question: I am having a hard time understanding this proof (leading up to Newtons method) about why a sequence must converge. English is not my native language so I will do my best to use the correct mathematical terms.
Theorem: Suppose that a Function $f(x)$ has the property $f(x) = x$ Suppose that this function also has the property of being differentiable in the interval $I$ and that there is a root $a$ to $f(x) = x$ in $I$. Further suppose that:
(1) There is a number $c < 1 $ & $|f'(x)| < c$ when $x \in I$
(2) $f$ "mirrors" the interval $I$ in itself.
then $a$ is the only root to $I$ and $x_n = f(x_{n-1})$ converge towards $a$ for every $x_o$ in $I$.

Now what is should be proved is:
When only (1) is true on $f'$ the sequence will still converge if you start close enough to the root we are searching for. More precisely:
(1) is true and the root $a$ is localized to a subinterval $I_1 = ]a-\delta, a+\delta[$ of $I$ which is small enough that the interval $I_2 = ]a-3\delta, a+3\delta[$ is also contained within $I$.
Then the recursion sequence $x_n = f(x_{n-1})$ converge for every start value $x_o$ in $I_1$

In my book they prove this by saying:
Let $I' = [a-2\delta, a+2\delta]$ then $I_1 \subseteq I' \subseteq I_2$. $f$ will then "mirror" the interval $I'$ in itself. If $x \in I'$ then:
$|f(x) - a| = |f(x) - f(a)| = f'(\xi)(x-a) \le c|x-a|$
This makes that $f(x) \in I'$. According to the theorem this will make the $x_n = f(x_{n-1})$ converge for each $x_o$ in $I'$ and especially for each $x_o \in I_1$.
If someone could explain the proof to me I would be very happy!
Thank you for your time!
Comment: For (2) above: I'm wondering if you mean the image of $f$ is $I$, and/or $f: I \to I$, with $f$ being onto $I$?
Comment: I've changed [tag:algebra] tag to [tag:algebra-precalculus], since we don't use algebra tag anymore, see [meta](http://meta.math.stackexchange.com/questions/473/the-use-of-the-algebra-tag/3081#3081) for details.
Comment: @Julian that seems to deprecate the level of this question. I'd say either "calculus" or "real analysis"?
Comment: I am struggling with the translation here. But another way of putting it is that: $f$ makes the image of the interval $I$ into itself. Is that more clear?
Comment: @amWhy: Let's just say both.
Comment: @Lukas: Yes, it does. You're saying that $f[I]\subseteq I$, yes? (By the way, where you have *derivable* the correct word is *differentiable*.)
Comment: Yes that would be it.
Comment: @amWhy Sorry, just looked at the question and saw that it is not abstract-algebra.
Comment: @LukasArvidsson: If $x \in [0,1)$, can you see why $x^n \to 0$? Try an find an 'error estimate' for $f(f(...(f(x))...))$.
Comment: I assume that Property (2) just means $f(I) \subset I$ so the iteration stays in the region for which Property (1) applies.
Comment: I understand why $x^n \rightarrow 0$ What I don't understand is how they prove the usefulness of the specific intervals $I_1, I', I_2$
Comment: I don't either. Having $|f'(x)|\leq c < 1$ and $f(I) \subset I$ is sufficient to show both uniqueness and convergence. The point here is that $f$ is a contraction map, ie, $|f(x)-f(y)| \leq c |x-y|$ with $c<1$.
Comment: I am sorry I forgot to add in the section "Now what should be proved is" is that only (1) is true not (2). And with the proof they try get around that "problem"
Comment: Well, now I don't really follow the details, but then I would guess that the whole point is to find an interval $I'$ so that $f(I') \subset I'$ on which $f$ is a contraction. I assume they are leading up to Newton's method?
Comment: Yes that would be it as far as I understand. Yes newtons is a just a page away :)
Comment: Do you see that if $f(I') \subset I'$ (I' a closed interval) and $|f'(x)| \leq c < 1 $ on $I'$ will produce the desired results?
Comment: I would appreciate it very much if you would like to elaborate a bit more on that! :)
Comment: OK, give me a minute...
Answer: This is a standard result known as the contraction mapping theorem. It is true in much more generality and is a very useful analytical tool. It is used to prove Newton's method (or equivalently the implicit function theorem), existence and uniqueness of solutions to ODEs, and much more. The technique is very useful, and has many generalizations (eg, to show continuity of solutions of a 'parameterized' fixed point map, which can be used to show continuity of solutions of parameterized ODEs). It is worth understanding well.
Suppose $f(I') \subset I'$, where $I' \subset \mathbb{R}$ is a closed interval, and $|f'(x)|\leq c< 1$ for $x \in I'$. The key condition here is $c<1$.
Then if $x,y \in I'$, the mean value theorem gives $|f(x)-f(y)|\leq c|x-y|$ .
First note that the set of 'local fixed points' $\{x \in I'| f(x) = x\}$ contains at most one point, for if $a,a' \in I'$ and $f(a) = a$, $f(a') = a'$, then we have $|a-a'| = |f(a)-f(a')| \leq c |a-a'|$, and the only way this can be true is if $a=a'$.
Now suppose $x_0 \in I'$ and $x_{n+1} = f(x_n)$. We want to show that $x_n$ converges to some $\hat{x}$.
If $x_n$ converges, then since $x_n \in I'$ and $I'$ is closed, then $\hat{x} \in I'$. Furthermore, by continuity of $f$, we have $f(\hat{x}) = \hat{x}$, and this must be the unique fixed point in $I'$ by the above remark.
So now we must show that $x_n$ converges. Note that since $I'$ is closed, it is complete and so all we need to do is show that the sequence is Cauchy. This is the key point of the proof here.
We have $|x_{n+2}-x_{n+1}| = |f(x_{n+1})-f(x_n)| \leq c |x_{n+1}-x_n|$, repeating shows that $|x_{n+1}-x_n| \leq c^n |x_1-x_0|$.
So we have (I'm assuming $n>m$ here, there is no loss of generality in doing so): $|x_n -x_m|\leq |x_n-x_{n-1}|+|x_{n-1}-x_{n-2}|+\cdots |x_{m+1} -x_m|$, and using the estimate, we have $|x_n -x_m|\leq (c^{n-1}+\cdots+c^{m+1}+c^m)|x_1-x_0|$. Now, since $c^{n-1}+\cdots+c^{m+1}+c^m = c^m(c^{n-m-1}+\cdots+c+1) \leq c^m(1+c+c^2+\cdot) = c^m \frac{1}{1-c}$, we have  $|x_n -x_m|\leq c^m \frac{1}{1-c} |x_1-x_0|$. So, by choosing $n,m$ large enough, we can make this arbitrarily small, that is, the sequence is Cauchy. Hence it converges.
Since we know that if $x_0 \in I'$, then the sequence $x_n$ converges to the unique fixed point in $I'$.
Comment: Thank you very much! I will now dig into this! Great to know about the contraction mapping theorem as I now can try to understand it better! This has saved my day :)
Comment: You are very welcome, glad to be of help.


Server for android game

Question: I am going to create game for android, this game has multiplayer mode, so it should send ang get some data from server.
Lets assume that 5 players are playing this game.
Each player on his turn sends a word to server, server checks if this word is correct and then server sends this word to other players.
Also server has some kind of timer, and when times goes out it sends to all player then time is up.
Very simple.
Now what is my problem. I have never done web programming and I don't know how to implement server side. Google gived me several options:

Http server
Sockets server

What should I use? One of this options or something else?
Also what frameworks/libraries can be helpful in implimentation? I'd prefer python (like CherryPy if http server is good for my purpouses), but also I can do it on java or c++. Or on php (but I don't want to use it)
Update
After thinking for a while I used python tcp socket server. It seems to be most lightweighted solution for my needs. Also it is easy to interact with it from Java.
Answer: Have you considered using parse?
https://parse.com/
Another good option I like is NodeJS, however you will get alot of the same benefits such as Asynchronous Concurrency from Tornado (Python)
Comment: As I understand parse is for storing and retriving data, but I can't implement game logic using it. I need to check if words are correct on server side. About NodeJS I have to look I little bit more, maybe it can help me
Answer: Consider using Twisted Python and roll your own simple protocol using persistent connections.
Alternatively, use a normal HTTP(s) server like Apache or nginx and WSGI to tie in your python backend logic.  To make it appear as if you have a persistent connection (used to notify everyone of the "word" that was submitted or the expiration of a timer), you'll need to use something like AJAX.
Comment: If you're going to do it over http, you're going to need to handle the push portion of your application.  If you build your own protocol that maintains open connections to each player after they initially connect, you'll be able to notify them directly.  If you do it via http, you'll need to use something like AJAX to provide the illusion that the connection stays open.  Also, if you're going to do HTTP/AJAX, it's probably simpler to use Apache or nginx and wsgi for the python app behind it.
Comment: And does android have tools to develop communication with my own protocol?
Comment: I believe Twisted is available in ASE (http://code.google.com/p/android-scripting/) so you could write your client in Python as well. If you write the client side in Python, you would abstract out your protocol logic (basically, how to serialize and deserialize) and use that code on both the server and the client.  If you do it via http/ajax, I'd expect that stuff to be available in a standard android install.  With that said, my answer was directed at the server side of things and I don't have much experience with android development work.
Comment: Well, seems that I should try to make simple application with twisted and ASE, if I won't find something easier. And http/ajax solution looks like something very heave, but maybe I am wrong
Comment: The biggest disadvantage in the twisted/ASE solution on the client side is that it will be significantly harder for end-users to install (ASE requires side-loading or rooting) so keep that in mind.

Server for android game


Receber resultado de um ajax como retorno

Question: Dentro do seguinte cenário:
funcao1 = function() {
    $.ajax({
        success: function(data) {
                     return data;
                 }
    });
}

funcao2 = function() {
    var dados = funcao1();
}

É possível eu receber, mesmo que seja através de promises, o resultado do ajax da funcao1 na funcao2?
Comment: Veja na documentação o que a função `$.ajax` retorna.
Answer: Recomendo utilizar a solução do Adrian, por utilizar a API mais nova, do ES7, com async/await.
Mas você também pode fazer criando uma Promise estilo ES6, veja como ficaria:

funcao1 = function () {
    return new Promise((result, failure) => {
        $.ajax("https://api.nulbox.com", {
            success: function (data) {
                result(data);
            },
            error: function (err) {
                failure(err);
            }
        });
    });
}
funcao2 = function () {
    funcao1()
        .then(d => console.log(d))
        .catch (e => console.error(e));
}
funcao2();

Answer: A função ajax possui como retorno um objeto jqXHR que possui um método done. Ou seja, basta retornar esse objeto e utilizar o método quando precisar da resposta da requisição.

const request = function () {
  return $.ajax('https://jsonplaceholder.typicode.com/todos/1');
}

const response = request();

response.done(data => {
  console.log(data);
});

Leitura complementar:

Qual usar no Ajax, success ou done?
Answer: Você pode usar async/await? Se puder, fica simples, veja:
var funcao1 = async function() {
        var result
    var ajax = await $.ajax({
            url: 'https://api.nulbox.com',
        success: function(data) {
          result = data
        }
    });
    return result
}

var funcao2 = async function() {
    var dados = await funcao1();

    console.log(dados)
}

funcao2()

Veja o exemplo funcionando
  aqui.


Is there anyway to bring web @Context into JUnit (CXF+Spring)

Question: I am trying to create unit test environment to test RESTFul services (cfx+spring) in my dev environemnt. To test RESTFul Services, I require @Context within JUnit test cases. @Context should contain HttpRequest, HttpSession, ServletContext, ServletConfig and all other webserver related information.
I have setup the JUnit for the above, but when I run, @Context is coming as null. This could be because there is no webserver running and there is no @Context. I am just doubting whether there is a way to created sample web @Context and pass to JUnit. Any other ideas are welcome to bring web @Context into JUnit test cases.
Answer: You need to embed a web container.
Try for example Jetty as an embedded container.
This article contains useful information.
Comment: Thank you. I will try the option.
Answer: Spring has some help for mocking the web server environment and thus testing without a real web container.  See these Spring Framework docs on testing to get started.  I haven't used this in your context, but it may be helpful.


Why do I see different tabs for same C Major scale and which one should I use?

Question: I was reading 10 minute guitar workout and I'm doing some exercises to understand how to create a Cmaj6 chord for example, from a C major chord.
When I was reading online for tabs to understand which notes were the 4th, the 6th note etc from the C major octave I stumbled upon two websites with two different tabs for the first octave, although the notes are the same which makes both of them correct I assume:
http://www.guitarcommand.com/c-major-scale-guitar/
http://www.studybass.com/lessons/bass-scales/one-octave-major-scale/
The second scale sounds better to me for the D note, since I prefer it played on the E string 5th chord than open on the D string.
Could you tell me why I see different tabs? Is there a source you recommend for me to use a reference for this kind of exercise where I can see the notes a major scale is composed of?
Thank you in advance.
Comment: Do you mean 'the D note sounds better on the fifth FRET of the 5th STRING' ?
Answer: The first one is the "c-major scale in open position" -- note how it uses open strings.  The fingering used for this scale is tied to that specific position on the fretboard.
The second one is the "c-major scale at  the third fret" -- note that all notes are fretted.  This scale pattern can be moved up or down the neck to play different major scales.
In some respect the movable scales are more useful since you can use the same patterns at different locations up/down the neck to play in different keys, but you'll want to learn the open position scales too. (for some people learning the open position scales is easier since the nut is an extra "finger" that helps you).
Comment: Also note that one's from a "studybass.com" while the other's from "guitarcommand.com".  Even if you took the open position and moved it, it has more for the third and fourth fingers to do which may be more difficult on a bass.
Answer: As Dave states, the first is an open Cmaj scale, using as many open strings as possible. The second is actually on a bass, so there is no direct comparison.They are not in the same octave. However, if you pretended that those 4 strings were the bottom 4 on your guitar, then you could use the same positions as shown, and actually play the scale an octave higher than on bass. It will sound the same as the first one, but with all notes 'closed'. This can be moved up and down to produce many other major scales of one octave. Move the pattern up two frets, and you're in Dmaj. Up two more and it's Emaj. Do try to start playing the notes with your middle finger, and use the 'one finger per fret' trick. Your whole hand will encompass all the notes without moving up or down.
There are numerous different patterns for each scale, it's the way the guitar is configured. It is a mixed blessing, in that it can simplify changing to a different key, but seems complex because there are several patterns to learn which all give you the same end product - a scale. In other words, there are multiple places to play the exact same note. Only two for that low C (5th string 3rd fret and low E 8th fret).But get up to higher notes, like top E - top string open, 2nd string 5th fret, 3rd string 9th fret, 4th string 14th fret, 5th string 19th fret 6th string 24th fret - and that's without looking at another 5 harmonics !!So scales can be played wherever the set of notes can be found. Tricky.
Answer: Whenever you see scales notated in both standard music notation and tab, and the tab uses open strings, its almost always because it was entered on keyboard and then the notation software auto-generates the tab.
What you want is diagrams that show the pattern from the lowest note of the scale that is available in the hand position, to the highest note that is available in the hand position. You will start phrases on different notes in the scale at different times, so limiting your practice by just going root to root is not very useful. Plus you will reuse the major scale patterns eventually for 7 different scale sounds, which won't share that root.
Avoid auto-scale generators as they generate some really dumb patterns sometimes, go with ones made by humans who play guitar. This chart on my website is what you want:
C Major Scale- 5 CAGED Patterns


Simple question on factoring the difference of 2 perfect squares

Question:
(b) (i) Use the identity $A^2-B^2=(A-B)(A+B)$ to factorise the expression $5^{2k}-1$.

Do I just put the k as 1 so that the equation is 5^2 and 1^2
Thanks
Steve
Comment: No, there is no reason to think $k=1$.
Comment: You can think of $5^{2k}$ as $(5^k)^2$
Comment: Hi
Thanks for the help so would the factor be simply (5^k-1)(5^k+1)
Answer: For all real numbers A and B,
$$A^2-B^2=(A-B)(A+B)$$
Substituting $$A=5^k$$ and $$B=1$$,
$$(5^k)^2-1^2=(5^k-1)(5^k+1)
\implies 5^{2k}-1= (5^k-1)(5^k+1)$$
Note that 5^k-1 can be further factorised if k is a natural number.
In that case,
$$5^k-1=(5-1)(1+5^1+5^2+5^3+......+5^{k-1}) = 4*(1+5^1+5^2+5^3+......+5^{k-1})$$
Comment: @Steve If you are satisfied by the answer, you may consider accepting it.


Fade DIV with childrens to black and vice versa with jQuery

Question: I am looking for an effect similar to jQuery UI tabs opacity toggle.
<code>$('#content').tabs({
    fx: {
        opacity: 'toggle'
    }
});
</code>
How is it done? How can i fade a div (variable height, gradient background) and its children to black, replace its content and fade it back in?
Answer: Options abound:
http://api.jquery.com/fadeTo/
http://api.jquery.com/fadeIn/
good examples with specifics at each topic.
this link too gives example using opacity - http://forum.jquery.com/topic/apply-50-opacity-to-a-div
Comment: I now use a black wrapping div and fading out my content div. Thanks for the hint! I still would prefer a solution without a wrapper.
Answer: The background color can be animated if you use the color plugin
From the jQuery docs:

Animation Properties and Values
All animated properties should be
animated to a single numeric value, except as noted below; most
properties that are non-numeric cannot be animated using basic jQuery
functionality (For example, width, height, or left can be animated but
background-color cannot be, unless the jQuery.Color() plugin is used).
Property values are treated as a number of p
Comment: I´m using background-image to set my gradients which seems not supported by the color plugin.


What are the various rules for placement of goal kicks?

Question: I have seen goal kicks placed in various spots within the box, and then there are kicks where the goalkeeper can handle the ball and drop-kick it.
What determines these different cases?
Answer: These are all completely different situations.

A goal kick can only be taken within the goal area (the 6 yard box). (Law 16)
A drop kick means the ball is still in play. The goalie could as well throw the ball to a team mate.
Free kicks can be awarded almost anywhere on the pitch. They're taken from where the previous offence occurred. (Law 13)
Comment: Law 13.2, a free kick **can** be *awarded* anywhere on the field, just not *taken* (if for an attacker) inside the goal area.


Projeto de algoritmos por divisão e conquista

Question: Preciso projetar esse algoritmo utilizando o paradigma de divisão e conquista (indução forte). Não estou conseguindo sair do lugar...

Sejam A e B dois vetores de números inteiros tais que o número total de inteiros nos dois vetores é n, e x um número inteiro. Projete um algoritmo de complexidade O(n log n) para o problema de determinar se existem índices i e j tais que A[i] + B[j] = x".
Comment: É interessante mencionar que esse problema pode ser resolvido em O(n) com hashtables. Esse é basicamente o clássico [*Two Sum*](https://leetcode.com/problems/two-sum/description/) mas com a pequena variante de ser com 2 arrays em vez de 1,
Answer: O algoritmo seria algo mais ou menos assim:
função z(int[n] A, int[n] B, int x) {     // Linha 1
    C = copy(B)                           // Linha 2
    sort(C)                               // Linha 3
    int i, k = -1                         // Linha 4
    for (i = 0; i < n && k == -1; i++) {  // Linha 5
        k = binary_search(C, x - A[i])    // Linha 6
    }                                     // Linha 7
    if (k == -1) return [-1, -1]          // Linha 8
    j = indexof(B, C[k])                  // Linha 9
    return [i, j]                         // Linha 10
}                                         // Linha 11

Nesse algoritmo:

copy é a função que cria uma cópia de um array.
sort é a função que ordena um array.
binary_search é a função que procura por um elemento em um array ordenado usando a busca binária e retorna a posição onde o elemento é encontrado. -1 é retornado se o elemento não for encontrado.
indexof é a função que retorna em qual posição de um array (possivelmente desordenado) um determinado elemento se encontra.

A função retorna um par de elementos que correspondem às posições [i, j] dos elementos procurados. Caso não existam i e j tais que A[i] + B[j] = x, então [-1, -1] é retornado.
A ideia é você criar uma cópia ordenada de B chamada C. Com isso, você pode percorrer cada posição de A usando i como contador e procurando por meio de busca binária o elemento correspondente em C em uma posição k. Se a busca em C nunca for bem sucedida após todo o array A ter sido percorrido, então [-1, -1] é retornado. Senão, quando a busca binária for bem sucedida, o valor correto de i é determinado e então basta procurar em B o elemento em C[k] para descobrir o valor de j.

A complexidade da linha 2 é O(n).
A complexidade da linha 3 é O(n log n). Para tal, basta usar um algoritmo tal como o mergesort como implementação de sort.
O laço das linhas 5-7 é executado no pior caso O(n) vezes.
Cada iteração da linha 6 tem uma complexidade de O(log n).
Logo, a complexidade total do laço das linhas 5-7 é O(n log n).
A linha 9 tem complexidade O(n) no pior caso. Uma busca sequencial em B é suficiente.
As linhas 4, 8 e 10 tem complexidade O(1).

Logo, a complexidade total é O(n) + O(n log n) + O(1) + O(n log n) + O(1) + O(n) + O(1) e isso é O(n log n).
Há um porém apenas. Isso não é um algoritmo de divisão-e-conquista. No entanto, isso talvez venha a te servir ao menos como base para produzir um que seja.


Logistic linear mixed effects model with categorical predictors

Question: I've read a lot of threads on stack exchange but haven't exactly found what I'm looking for. Everyone seems to have a slightly different problem/issue.
First, lets have a look at my data:

120 Users
80 Items per User
Between factor with 4 levels
Within factor with 4 levels
Binary response variable

Now, usually one would perform a logistic regression. However, there are several issues with that:

Categorical predictors have to be dummy coded?
How do deal with the within-subject fator? -> lmm?
How would you plot this data?

As I think (but I'm not sure? correct me if I'm wrong) that one assumption of binary logistic regression is the independence of errors which is - again not sure - violated with within subject factor I'm trying to perform a linear-mixed effects model for my data. Now here begins the actual problem:
First: I know, that I want to model the between-subjects and within-subject factors as fixed effects.
However: which random effects should I implement?

Random intercept of each subject as it can be assumed that they differ in they're apriori knowledge of the items (it's a performance test).
Random intercept of the within-subject factor - as this is the reason for performing lmm in the first place?

My data is actually not nested, so there is no sense in creating a random effect like all the examples "school", "county" and so on...
other suggestions?

Okay my suggestion is to assume random intercepts of subjects (the first one):
lmm3 <- glmer(y ~ between * within + (1|user), data, family = binomial(link = "logit"))

But, first I would have to calculate the ICC 1 and ICC2 to support the use uf lmm.
for the ICC 1 I use the nullmodel:
lmm0 <- glmer(y ~ (1|user), data, family = binomial(link = "logit"))
tau2<-lme4::VarCorr(lmm0)[[1]][1]
icc1 <- tau2/(tau2+pi^2/3)

No, again two questions arise:

How do I calculate ICC2 for the logistic model? I know that there is a function for linear mixed models, but this is not the case here.
However, my ICC1 is only 0.03760069 so it seems that this above model doesn't make a lot of sense. What kind of model should I try then?

I thank you a lot for your inputs. You need more specific information I would be willing to prepare some data for you. I know that this is a rather theoretical issue so I'm looking forward to a discussion.
Kind regards,
David
Comment: The reason why you want to use random effects is to account for correlations, i.e., responses on the outcome `y` coming from the same user will be expected to be correlated. Now, why do you want to calculate ICCs? What is really your purpose?
Comment: I want to calculate the ICC1 to check how much of the total variance of my model is explained by the variance of the caused by the users just because they differ in their intercepts. This would justify the use of LMMs
Comment: There is a lot of controversy in using ICCs for mixed models, especially for categorical data; see, e.g., this post by Douglas Bates the main developer of **lme4**: https://stat.ethz.ch/pipermail/r-sig-mixed-models/2010q1/003363.html . If you want to see if you need to use the mixed model, you can compare with a likelihood ratio test (i.e., the `anova()` function) the logistic regression model without random effects, fitted by `glm(..., family = binomial())` with the mixed effects logistic regression fitted by `glmer(..., family = binomial())`.
Comment: Well, thank you Dimitris. This is quiet interesting as I wasn't aware that I'm allowed to compar a glm with a glmer. Seems to be a really straight forward solution for a topic that causes a lot of discussions^^
Answer: Since you have 120 users and 80 items per user, your model would have to treat user and item as random grouping factors.
Are the 80 items the same for each of your users? If yes, the random grouping factors user and item will be fully crossed, in which case the glmer syntax would include terms like
(1|user) + (1|item)

See https://nlp.stanford.edu/manning/courses/ling289/GLMM.pdf for more ideas on how to proceed.
Comment: Actually, the 80 items are basically the same for all of the users, but the users are supported by an aid to a different extent depending on which between-subject factor they belong. Does this mean I should only add the (1|user) as a random effect to the model? However, thanks for the paper, this seems to be exactly what I want to do.
Comment: Hi Isabella, we had this discussion back in October and now another question arose. What if the items are not the same for the between subject variables? Should am I still allowed to include the (1|Item) random effect? I suppose not or am I wrong?
Comment: Can't you include (1|user) and (1|item), as well as a predictor variable which quantifies the extent of aid received by each user?  (You need to capture the between-item variability somehow in your model.) Also, I'm assuming that you have multiple binary outcome values collected for each user by item combination.
Comment: yes I can, but the random effect of (1|item) is does not enhnace the model.
Comment: Sometimes we leave terms in the model because of substantive - not statistical - reasons.


Spring boot - 2 JNDI configuration

Question:
Posted my current configuration
Comment: I have removed batch-file tag. I am using boot- 1.5.2.RELEASE version
Answer: <code>@Configuration
public class Config {
    @Value("${spring.datasource.primary.jndi-name}")
    private String primaryJndiName;

    @Value("${spring.datasource.secondary.jndi-name}")
    private String secondaryJndiName;

    @Primary
    @Bean(destroyMethod = "") // destroy method is disabled for Weblogic update app ability
    public DataSource primaryDs() {
        JndiDataSourceLookup lookup = new JndiDataSourceLookup();
        return lookup.getDataSource(primaryJndiName);
    }

    @Bean(destroyMethod = "") // destroy method is disabled for Weblogic update app ability
    public DataSource secondaryDs() {
        JndiDataSourceLookup lookup = new JndiDataSourceLookup();
        return lookup.getDataSource(secondaryJndiName);
   }
}
</code>
Answer: I implemented this way and it is working
you can put your jndi values in one properties file and then load that property file in your bean defination.xml
jndi.properties
<code>#JNDI property for job repository
job.repository.db.connection=jdbc/pgDB
#JNDI property for application
application.db.connection=jdbc/db2Conn
</code>
Bean-defination.xml
<code><bean id="propertyPlaceholderConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath*:/properties/jndi.properties</value>
            </list>
        </property>
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    </bean>

<bean id="jobRepoDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="${job.repository.db.connection}" />
    </bean>

    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="${application.db.connection}" />
    </bean>
</code>

Spring boot - 2 JNDI configuration


Calculation of second order partial derivatives

Question: Let $$F\left( \frac{x}{z}, \frac{y}{z} \right)=0$$ determine a function $z=z(x,y)$. Show that $$\frac{\partial^2z}{\partial x^2} \cdot \frac{\partial^2z}{\partial y^2}-\left( \frac{\partial^2z}{\partial x\partial y} \right)^2=0.$$
I was frustrated in simplifying doing the second partial derivatives...
Comment: @HenningMakholm In fact, I could not simplify the answers...it is terribly mixed..
Answer: In order for the definition of $z(x,y)$ to make sense, we must assume that on each line through $(0,0)$ there is exactly one point with $F(x,y)=0$. This is possible (for example the locus of $F(x,y)$ could be a parabola with the origin on the inside), but in order for $z$ to be continuous everywhere, it seems to be more meaningful to suppose that each ray emanating from $(0,0)$ contains exactly one zero of $F$, and require that $z$ is positive.
Now let's first prove the property for the half-plane $x>0$:
Define $f(m)$ to be the reciprocal of the $x$-coordinate of the point on the line $y=mx$ (where $x>0$) that makes $F$ vanish. We can then write $z$ as
$$ z(x,y) = x f(y/x) $$
Assuming that $f$ is sufficiently smooth (otherwise we're in probably insurmountable trouble anyway), it is now easy to write down the partial derivatives of $z$ in terms of $x$, $y$, and the first few derivatives of $f$. After several terms cancel, I get
$$ \frac{\partial^2 z}{\partial x^2} = \frac{y^2}{x^3}f''(y/x)
\qquad \frac{\partial^2 z}{\partial x\partial y} = \frac{-y}{x^2}f''(y/x)
\qquad \frac{\partial^2 z}{\partial y^2} = \frac1x f''(y/x) $$
and it is now trivial to verify that the claimed identity holds.
This argument can be reused identically for the half-plane $x<0$ (except that $f$ will be different), and will again work for $y>0$ and $y<0$, by swapping every $x$ for $y$ and vice versa (which fortunately leaves the target identity unchanged).
This handles everything except for $(x,y)=(0,0)$, but $z$ can't really be defined there anyway, or at least not continuously unless $F=0$ in a neighborhood of $(0,0)$, so let's just assume we're not meant to handle this point anyway.


Hungerford Algebra Problem (Ch 1 Section 8)

Question: I stuck on the following problem from Hungerford's Algebra.
Let $H,K,N$ be normal in a group $G$ such that $G = H \times K$.   Show $N$ is in the center of $G$ or intersects $H$ or $K$ non trivially.
I tried to construct some type of group action on $N$ but it didn't lead anywhere.
Comment: I think that if two normal groups $H$ and $N$ have trivial intersection, then $HN=1$. Can you think of what we might do with that? (I'm not sure about that, but am more confident that $hn=nh$, which might be good enough).
Answer: Suppose that $N\cap H = N\cap K = \{1\}$ and let $hk\in N$. Try showing that $h\in Z(H)$ and $k\in Z(K)$. (For example, if $h\notin Z(H)$, you can derive a contradiction to $N\cap H = \{1\}$.)
Comment: Indeed that works
Comment: Is there some deeper theorem (general technique) that can prove this?


Using AJAX in menu and menu tab links

Question: I have a few pages with sub pages as tabs. Each pages are in a custom menu. I'd like to convert the menu links to load each page using AJAX, is this possible?
I know how to load a page using a regular AJAX link, but not a menu, or menu tab link. One way is to replicate the menu links using AJAX and binding the events to the corresponding menu links, which works, but there must be a better way?
Answer: Assuming I understand your question correctly, it is possible. This is how I would do it (not sure how much this differs from the way you mentioned). Obviously you would need to change your page callback function, which you set for the tab in hook_menu(), to return a json object rather than a rendered page.
At the end of your page callback function you should add something like this:
// Return the rendered view in a JSON object. The object will contain a property
// named "contacts", which containes the rendered view.  This will be sent to the
// browser and is accessable to javascript.
return drupal_json_output(array('contacts' => $view));
exit;

You would then need to include some javascript on the client-side to send an ajax request to the server using the URI/path you set for the tab in hook_menu.  This same client-side javascript would then process the returned data.
  currentMenuLink.click(function() {
      var updateContacts = function(data) {
        // The data parameter is a JSON object. Do something with the returned data here.
      };

      // Send ajax request.
      $.ajax({
        type: 'POST',
        url: this.href, // Which url should be handle the ajax request. This is the url defined in the  html tag
        error: function() {
          $('#namecards-get-contacts-by-nid-row-' + currentNid).show();
          $('#namecards-get-contacts-by-nid-cell-' + currentNid).html($('
An error has occurred while retrieving the list of contacts.  Please try again.  If the problem persists, please inform your website administrator.
'));
        },
        success: updateContacts, // The js function that will be called upon success request
        dataType: 'json', //define the type of data that is going to get back from the server
        data: 'js=1' //Pass a key/value pair
      });
      // return false so the navigation stops here and not continue to the page in the link.
      return false;
    }
  });

Comment: Thanks for the reply. I need to do this through the Drupal AJAX framework because I need to insert Drupal Forms, so would need all the behaviours, settings etc attached.
Comment: By Drupal AJAX framework, do you mean the AJAX component of Drupal Forms? Might be helpful if you describe a little more about what you want to do. Are you trying to load a form via AJAX? If that is the case you could always reattach any form related javascript behaviours at the end of your AJAX success callback.
Comment: Sorry, I realise my question didn't really provide much information. I think I got it working now though, thanks for your help.
Answer: I managed to get this working by manually adding AJAX to each menu item:
(function ($) {

Drupal.behaviors.test = {
  attach: function(context, settings) {
    $('#sidebar-first ul.menu a').addClass('use-ajax').addClass('ajax-processed').each(function () {
      var element_settings = {};
      element_settings.progress = { 'type': 'throbber' };
      if ($(this).attr('href')) {
        element_settings.url = $(this).attr('href');
        element_settings.event = 'click';
      }
      var base = $(this).attr('id');
      Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
    });
  }
};

Each of the menu items then checks to see if AJAX was used, if so it delivers the page using ajax_render().
    })(jQuery);
Comment: i am also stuck with same issue could you please help me in this this code is not working for me
Answer: I use hook_menu_alter() for this:
function THEMENAME_menu_link(array $variables) {

  //mlid - menu link ID. I want AJAX only some menu link
  if ($variables['element']['#original_link']['mlid'] == 1177) {
    drupal_add_library('system', 'drupal.ajax');
    $element = $variables['element'];
    $output = l('YOUR_LINK', $element['#href'].'/nojs', array('attributes' => array('class' => array('use-ajax'))));
    return '
' . $output . "
\n";
  }

  // render other items dy default way
  return theme_menu_link($variables);
}

Using AJAX in menu and menu tab links


Proof of $ \sup\limits_{n\in\mathbb{N}} (x_n+y_n) \le\sup x_n+\sup y_n$

Question: For sequence $(a_n)_{n\in \Bbb N}$ we define: $\sup_{n\in \Bbb N}  a_n=\{a_{n}:n\in\Bbb N\}$: prove that for each pair of sequences $(x_{n})_{n\in \Bbb N}, (y_{n})_{n\in \Bbb N}$ which are bounded from above
$$
\sup_{n\in \Bbb N} (x_n+y_n) \le \sup  x_n+\sup y_n
$$
and point out such pair of sequences, for which presented inequality is "$<$".
My attempt: let $a=\sup x_n$, and $b=\sup y_n$ and define the addition sequences as:
$(a_n)+(b_n):=(a_n+b_n)$

When quantity of elements $(a_n)$ different from $(y_n)$:

$\sup(x_n+y_n)=\max\{a,b\},\text{ and }\sup x_n+\sup y_n=a+b$, thus
$\max\{a,b\}\le a+b$ for all $a,b$.

When quantity of elements $(a_n)$ equals $(y_n)$:

$\sup(x_n+y_n)=a+b=\sup x_n+\sup y_n$

Does it makes sense?
Comment: Do you mean ''...we define $\sup_{n\in \mathbb{N}}a_n = \sup_{n\in \mathbb{N}}\{a_n: n\in \mathbb{N}\}$
Comment: Yes, thank you.
Comment: What do you mean by ''When quantity of elements $(a_n)$ different from $(y_n)$:'' what is $(a_n)$?
Comment: Hmm.. . You' re right. Now, I realised that it is nonsense, because $x_n$ and $y_n$ are infinite
Answer: Note that by definition supremum is the least upper bound.
Therefore it suffices to show that, $$ (x_n+y_n) \le \sup_{n\in \Bbb N}x_n+\sup_{n\in \Bbb N}  y_n$$ because that makes $$\sup  x_n+ \sup y_n$$ an upper bound for  $\{ (x_n+y_n)\}$, $n\in \Bbb N$
Since $$ x_n \le \sup_{n\in \Bbb N} \{x_n\}$$ and  $$ y_n \le \sup_{n\in \Bbb N} \{y_n\}$$ We get $$x_n+y_n \le \sup \{x_n\} +\sup \{y_n\}$$
Thus the least upper bound is less than or equal to this  particular upper bound.
Comment: This method is actually better than the one I presented since we don't know beforehand that $\sup(x_n+y_n)$ is bounded from above and this shows it
Comment: @OlofRubin Thanks for your attention and comment.
Answer: Here is a start on how one could proceed with proving this:
Let $\varepsilon>0$ be some arbitrary positive number. Pick $N$ such that
$$\sup(x_n+y_n)-\varepsilon<x_N+y_N$$
(why can we find such an $N$?). What upper bound can you place on the right-hand side?

Edit: This is only applicable if we beforehand know that $\sup(x_n+y_n)$ is finite.
Comment: $sup(x_n+y_n)-\varepsilon<x_N+y_N < sup \ x_n + sup \ y_n$?
Comment: precisely so what does this imply?
Comment: @matematiccc Since $sup(x_n+y_n)-ε0$, we must have $sup(x_n+y_n) \leq sup x_n + sup y_n$
Comment: yes! I thought that this answer is too trivial. Now, I'm thinking why such N exists.
Comment: You should look at the other answer this method (which is very powerful) only works if we beforehand know that $\sup (x_n+y_n)$ is bounded but we did not show it this way.
Answer: Let $a=\sup_{n\in\mathbb{N}}x_n$ and $b=\sup_{n\in\mathbb{N}}y_n$. Then, for every $n$,
$$
x_n\le a,\qquad y_n\le b
$$
and therefore $x_n+y_n\le a+b$, giving
$$
\sup_{n\in\mathbb{N}}(x_n+y_n)\le a+b
$$
because the supremum is at most equal to any upper bound.
It's generally false that $\sup_{n\in\mathbb{N}}(x_n+y_n)=\max\{a,b\}$. Take two constant sequences $x_n=1$ and $y_n=2$. Then $\sup_{n\in\mathbb{N}}=3\ne\max\{1,2\}$.
How do we find two sequences where the strict inequality holds?
Take $x_n=1$ when $n$ is even and $x_n=-1$ if $n$ is odd. Define $y_n=-x_n$.


Complex analysis: The taylor series for $\frac{z\cos z}{z-2}$ around $z=0$

Question: I'm stucking trying to solve the following problem:
Given a function $f$ given as $f(z)=\frac{z\cdot \cos z}{z-2}$ I am asked to show that the Taylor series for $f$ around $0$ is given as
$$f(z)=\sum_{k=0}^{\infty}a_kz^k $$
where $a_0=0$ and
$$a_{2k}=a_{2_k-1}/2 $$
$$ a_{2k+1}=\frac{\left(a_{2k}+\frac{(-1)^{k+1}}{(2k)!}\right)}{2}$$
My work so far:
Given
$$f(z)=\frac{z\cdot \cos z}{z-2}=\sum_{k=0}^{\infty}a_kz^k$$
it must be the case that
\begin{alignat*}{2}
z\cdot \cos z&=\sum_{k=0}^{\infty}a_kz^k(z-2)\\
&= \sum_{k=0}^{\infty}-2a_kz^k+a_kz^{k+1} \\
&= \sum_{k=0}^{\infty}-2a_kz^k+a_{k-1}z^{k} \\
&= \sum_{k=0}^{\infty}(-2a_k+a_{k-1})z^k \\
&= \sum_{k=0}^{\infty}(-a_k+\frac{a_{k-1}}{2})z^k
\end{alignat*}
From here I'm not sure how to proceed. I know that $z\cdot \cos z=z\sum_{k=0}^{\infty} \frac{(-1)^k}{(2k)!}z^{2k}=\sum_{k=0}^{\infty} \frac{(-1)^k}{(2k)!}z^{2k+1}$, but I'm not sure how this connects with what I've done so far.
Any tips are appreciated.
Answer: Observe that the function has a simple pole at $z=2$, so the series will converge for $|z| < 2$, in which region we have
$$\frac{1}{z-2} = -\frac{1}{2} \frac{1}{1-\tfrac{z}{2}}=- \sum_{n=0}^{\infty} \frac{z^n}{2^{n+1}}$$
We also, as you point out, have
$$z \cos(z) = z \sum_{n=0}^{\infty} (-1)^n \frac{z^{2n}}{(2n)!} = \sum_{n=0}^{\infty} (-1)^n \frac{z^{2n+1}}{(2n)!}.$$
So the Taylor series will be the product
$$f(z) = \bigg( - \sum_{n=0}^{\infty} \frac{z^n}{2^{n+1}} \bigg) \bigg( \sum_{n=0}^{\infty} (-1)^n \frac{z^{2n+1}}{(2n)!} \bigg).$$
Now, from this point, you might be able to find an expression for the $n$-th term in this series using the Cauchy product formula, or you could just write out the first few terms is that is satisfactory.
Comment: Thanks! I haven't really come across the Cauchy product formula in my course before, so I will have to look into that.
Answer: Hint:
$$
\frac{1}{z-2} = \sum_{n=0}^\infty \frac{-1}{2^{n+1}}z^n \quad\text{for } |z|<2
$$


Is it possible to find an explicit form of the solution to $y'=\frac{1-x+y}{x-y}$

Question: We want to solve the differential equation $y'=\frac{1-x+y}{x-y}$, What i did is define $z=x-y$, and then $y'=1-z'$, so overall we have
$1-z'=\frac{1-z}{z}$, or in other words $z'=\frac{2z-1}{z}$ This can be solved because $z$ and $x$ are separable:
$\int \frac{z}{2z-1}dz=\int dx$
I don't know any method to integrate the left side, so I'll be grateful if someone can show an analytic way to do that, but i managed to guess the integral: $\frac{1}{2}z+\frac{1}{4}\ln (2z-1)=x+c$
Now to revert back to our original $y$:
$\frac{1}{2}(x-y)+\frac{1}{4}\ln (2(x-y)-1)=x+c$
Is this the best we can do? Is there a way to find an explicit form for $y$? or an implicit equation like this is the best solution we can hope for in this situation
Comment: I think you'll find [this](http://math.stackexchange.com/a/941907/170231) approach very useful
Answer: There is a simple way to integrate the integral you have:
$$\frac{z}{2z-1} = \frac{1}{2}\frac{2z}{2z-1} = \frac12\frac{(2z-1)+1}{2z-1} = \frac12\left(1 + \frac1{2z-1}\right).$$
As for solving your equation for $y$, no, I do not think it is possible to get a closed form of $y$. I am not sure (there are theorems that tell you, but I don't know them), but the rule of thumb is that if an equation contains the variable both in the exponent and in line, or in your case, in the logarithm and in line, then a closed form solution is not likely.


cannot connect to hbase because of zookeeper

Question: for connect to hbase i write this code:
 Class.forName("com.salesforce.phoenix.jdbc.PhoenixDriver");
           conn = DriverManager.getConnection("jdbc:phoenix:localhost:2181");

but after running give me this errors:
13/08/22 09:14:14 INFO zookeeper.ZooKeeper:
Client environment:zookeeper.version=3.4.5-1392090, built on 09/30/2012 17:52 GMT
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:host.name=ubuntu
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:java.version=1.7.0_25
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:
java.vendor=Oracle Corporation
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:
java.home=/usr/local/jdk1.7.0_25/jre
13/08/22 09:14:14 INFO zookeeper.ZooKeeper:
 Client environment:java.class.path=/home/ubuntu/Phonix/phoenix-2.0.0-client.jar:
/home/ubuntu/Downloads/hbql-0.90.0.1/hbql-0.90.0.1-src.jar:/home/ubuntu/Downloads/
 hbql-0.90.0.1/hbql-0.90.0.1.jar:/home/ubuntu/Downloads/protobuf-java-2.4.1.jar:
/home/ubuntu/NetBeansProjects/hbase-phoenix/build/classes
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:java.library.path=
/usr/local/jdk1.7.0_25/jre/lib/amd64:/usr/local/jdk1.7.0_25/jre/lib/i386:
/usr/java/packages/lib/i386:/lib:/usr/lib
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:java.io.tmpdir=/tmp
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:java.compiler=<NA>
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:os.name=Linux
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:os.arch=i386
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:os.version=
3.2.0-23-generic-pae
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:user.name=ubuntu
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:user.home=/home/ubuntu
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Client environment:user.dir=
/home/ubuntu/NetBeansProjects/hbase-phoenix
13/08/22 09:14:14 INFO zookeeper.ZooKeeper: Initiating client connection,
connectString=localhost:2181 sessionTimeout=180000 watcher=hconnection
13/08/22 09:14:14 INFO zookeeper.RecoverableZooKeeper:
The identifier of this process is 4944@ubuntu
13/08/22 09:14:14 INFO zookeeper.ClientCnxn: Opening socket connection to server
localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
13/08/22 09:14:14 WARN zookeeper.ClientCnxn: Session 0x0 for server null, unexpected
error, closing socket connection and attempting reconnect
java.net.ConnectException: Connection refused
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:708)
at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport
    (ClientCnxnSocketNIO.java:350)
at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1068)
13/08/22 09:14:15 WARN zookeeper.RecoverableZooKeeper:
Possibly transient
 ZooKeeper exception:org.apache.zookeeper.KeeperException$ConnectionLossException:
 KeeperErrorCode =
 ConnectionLoss for /hbase/hbaseid
13/08/22 09:14:15 INFO util.RetryCounter: Sleeping 2000ms before retry #1...

I cannot understand what is the problem.
I install hbase 0.94.10 and zookeeper 3.4.5 individually and i am not sure configuration is true.can you guide and help me how configure them correctly
Answer: did you ensured to copy the phoenix server jar (its called only phoenix-.jar, I think it should be phoenix-2.0.0.jar in your case) to all of your region servers?
Also ensure that the location of the phoenix jar is appended to the HBase classpath. You need to put the following maybe in the hbase-env.sh of all your region servers:
HBASE_CLASSPATH=$HBASE_CLASSPATH:/path/to/phoenix-2.0.0.jar

Afterwards you need to restart the cluster. Then phoenix will work.
You can also read this installation guide of their github project page.
UPDATE:
I just saw that they updated their documentation. Thw last version of the documentation was more straigh-forward, but I think you will manage...
Answer: Adding answer for anyone still looking:
Your jdbc connection string must look like:

jdbc:phoenix:zookeeper_quorum:2181:/hbase_znode
   OR;
jdbc:phoenix:zookeeper_quorum:/hbase_znode

(By default zookeeper listens at port 2181.)
zookeeper_quorum - Can be comma-separated server-names(must be fully qualified DNS names)
hbase_znode - hbase or hbase-unsecured
e.g.

jdbc:phoenix:server1.abc.com,server2.abc.com:2181:/hbase


SQL 2005 32Bit on 64Bit OS?

Question: UPDATE: My fault, i misread X86 and X64. We don't have a 64bit OS.
Hey all,
Quick question, our IT Dept have installed a 32bit version of SQL Enterprise on a 64bit OS. This works, quite well in fact, however is it sub-optimal?
The machines have 32gb of ram and 16 cores, can the 32bit version of SQL 2005 actually access all 32gb of ram? Or will it still have the 32bit limitaion?
Cheers,
D
Comment: This belongs on ServerFault.
Comment: Absolutely correct, my apologies.
Answer: Definitely sub-optimal. See: 64-bit vs 32-bit Windows/SQL install. Is there a reason why they're not installing the 64-bit version?

SQL 2005 32Bit on 64Bit OS?


Oracle SQL: trying to create tables with certain constraints but not able to add record. where is it going wrong?

Question: These are the tables i am trying to create. i am not able to find the mistake here at all.
CREATE TABLE Pharmaceutical (
PharName     VARCHAR(30),
PharTelephone    VARCHAR(25),
PRIMARY KEY (PharName)
);

CREATE TABLE Doctor (
DID     VARCHAR2(20),
DName       VARCHAR2(50),
Specialty   VARCHAR2(70),
YearOfExp   NUMBER,
PRIMARY KEY (DID)
);

CREATE TABLE Patient (
PID     VARCHAR2(20),
PName       VARCHAR2(50),
PDOB        DATE,
PAddress    VARCHAR2(70),
PPostalCode VARCHAR2(12),
FamilyDoctor    VARCHAR2(20),
PRIMARY KEY (PID),
FOREIGN KEY (FamilyDoctor) REFERENCES Doctor(DID)
);

CREATE TABLE Drug (
PharName    VARCHAR2(30),
Tradename   VARCHAR2(30),
Formula     VARCHAR2(70),
PRIMARY KEY (PharName, Tradename),
FOREIGN KEY (PharName) REFERENCES Pharmaceutical(PharName)
);

CREATE TABLE Prescription (
DID     VARCHAR2(20),
PID     VARCHAR2(20),
PharName    VARCHAR2(30),
Tradename   VARCHAR2(30),
PrescriptionDT  DATE,
Quantity    NUMBER,
CONSTRAINT checkQuantity CHECK (Quantity>0 AND Quantity<31),

PRIMARY KEY (DID, PID, PharName, Tradename, PrescriptionDT),
FOREIGN KEY (DID) REFERENCES Doctor(DID),
FOREIGN KEY (PID) REFERENCES Patient(PID),
FOREIGN KEY (PharName, Tradename) REFERENCES Drug(PharName, Tradename),
);

i also use drop.sql, to drop the tables:
DROP TABLE Pharmaceutical PURGE;
DROP TABLE Doctor PURGE;
DROP TABLE Patient PURGE;
DROP TABLE Drug PURGE;
DROP TABLE Prescription PURGE;

thank you!
P.S. --> removed the 'add' from the add contraint part. this is the error i get:
SP2-0734: unknown command beginning "PRIMARY KEY ..." - rest of line ignored.
getting this error for the last table's primary key and all of it's foreign keys, so assumed that the problem is with the contraint but i may be wrong.
Comment: @NewbeeDev - your statement is completely incorrect. You can only have one primary key, but the primary key can consist of multiple fields. Thanks.
Comment: if you are using oracle then you have to write 'CONSTRAINT' before PRIMARY KEY and/or FOREIGN KEY too
Answer: In the definition of table Prescription, the last line before the ending ); reads
FOREIGN KEY (PharName, Tradename) REFERENCES Drug(PharName, Tradename),

Get rid of the trailing comma.
Best of luck.