Working with large networkx graph and Flask webserver

Question: I'm trying to create a Flask web app that can query a NetworkX graph, to return the shortest paths (using Dijkstra's algorithm, plus Yen's algorithm for the k-shortest paths).
Here is my sample code (stripped of error handling et c., and only showing the Dijkstra implementation), which returns the path if you submit a GET request to localhost:3000/d?source=a&target=b:
import csv
import json
import networkx as nx
from flask import Flask, request

app = Flask(__name__)
G = nx.Graph()

@app.route('/d')
def dijkstra():

  global G

  source = request.args['source'].lower().strip()
  target = request.args['target'].lower().strip()

  path = nx.dijkstra_path(G, source, target, weight='weight')

  return json.dumps(path)

if __name__ == '__main__':

  global G

  with open('nodes.csv', 'rb') as f:
    reader = csv.reader(f)
    node_list = list(reader)

  for i in nodes:
    G.add_node(i[0])

  with open('edges.csv', 'rb') as f:
    reader = csv.reader(f)
    edge_list = list(reader)

  for i in edges:
    G.add_edge(i[0], i[1], weight=i[2])

  app.run(host='0.0.0.0', port=3000, use_reloader=False)

The graph is very large (one million nodes, twenty million edges), so I am currently populating from CSVs it as the app loads, rather than building it for every request. This takes about five minutes when run locally on my MacBook Pro (3GHz, 16GB RAM). Lookups take different amounts of time, but generally around fifteen seconds, and performance generally degrades after a certain amount of use, meaning I have to restart the app.
Question one: as this is slow and pretty memory intensive, is there a way to store this graph so that I don't have to generate it every time, then hold it in memory?
Question two: am I approaching it the right way, by using G as a global variable?
I haven't worked with graphs this large before, so am aware my implementation is probably far from ideal, and would be grateful for any thoughts about how to make this perform better/more reliably!
Comment: PS here are sample timings from a version of the script that logs each stage, so you can see where the time is being spent: **3.6** seconds from start to load 1,014,896 nodes; 99.0 seconds from start (∴ **95.4** seconds) to load 20,025,902 edges; 101.3 seconds from start (∴ **5.9** seconds) to add nodes to graph; 330.9 seconds from start (∴ **229.6** seconds) to add edges to graph.
Answer: Did you try using caches available in the Market?

Flask Cache  This library exploits redis caching
Redis Cache
Or you can even use Python Pickles

Create a background script which updates these caches or pickles and your request only loads and sent the data inside it.
EDIT
As OP have also found the Builtin Pickles Method on NetworkX
enter link description here
To compare the speed for pickling and directly dealing with CSV Check this link
Edit 2
When you pickle the entire data structure, you are limited by system RAM. You can, however, do it in chunks.
streaming-pickle can be a solution for pickling objects larger than memory on board. Because problems occur while unpickling but you can use this approach to overcome that as well.
or with the Redis approach, if you want data to be held under the request is finished you can look for Redis Cluster
This is one big hell of a questions :D depends on what you actually need.
Comment: Thanks for the quick reply! Looks like NetworkX has a function for reading/writing pickles (https://networkx.github.io/documentation/networkx-1.9.1/reference/readwrite.gpickle.html). Is that what you meant? Will this not create the same memory problems when the whole graph has to be loaded?
Comment: Wunderbar, if it has the picke write built in :D. You can compare the response time here https://stackoverflow.com/a/37012035/6198978

Pickles and HDF5 are much faster than CSV.
Comment: Trying it out now—will let you know. Thanks again! :)
Comment: No luck :( it spent about 20 minutes trying to create the pickle, then I got a `Killed: 9` message. Any other ideas?
Comment: StackOverflow or OutofMem? Whats the error does it show?
Comment: Literally just `Killed: 9`, which is a SIGKILL that "cannot be caught or ignored" (http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html). My guess would be out of memory :(
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170863/discussion-between-noor-ali-jafri-and-chris).
Comment: Summary: this was a huge help for reducing the initial load time, as `networkx.read_gpickle()` loads the graph in about 75 seconds, vs the current average of 350. So thank you very much indeed!

I still have an outstanding question about whether my approach is correct or not, though: holding a huge graph like this in memory makes things run pretty slowly, and performance degrades after a while. Is there a better way to work with such a large graph?
Comment: Thank you! You have definitely answered question one for me. I now have a pickle that loads in a quarter of the time.

Next up: what do you think about the approach of loading the whole graph into memory? Is this the only way to go, or is there a better way that will preserve continuous performance?
Comment: Yup check the edit I have mentioned about the streaming pickle.
Comment: Finally got a solution that works pretty well (still needs some optimisation, but definitely "good enough" for now), thanks to your very kind help. Thank you so much! :D
Comment: Anytime ;) i love such problems


What's the interval that I need to transpose from C minor to E minor?

Question: Would this be a minor third of a major third? Sorry if this is a simple question, it's been a while since I studied music theory.
For an example, suppose there was an Fmaj chord within the C minor music piece. When this is transposed to E minor, does this chord become Amaj or Amin?
Comment: If it's been a while since you studied theory, a picture of the sheet music would give you more accurate answers.  How do you know the piece is in C minor, and not some other mode?
Comment: I was playing by ear with some guitar chords as a backbone so there's no sheets. The question was answered but thanks.
Answer: The fact that they're both minors (they would be, you're transposing!) is a red herring.
The interval is between C and E, which is M3 - a major third. Everything - chords and dots need to move up by 4 semitones.
In key C minor, F major is IV. Transposing to key E minor, IV is now A major. Majors transpose to majors, minors to minors, augs to augs, etc. - the transposition certainly won't affect the 'flavour' of the chord - only its name.
Comment: Thank you! Got it. Also I apologize, the website doesn't let me upvote you.
Comment: You will be able to once you reach a specific level of reputation, keep trying, I gave you a +1.


LINQ to Twitter Support Xamarin.iOS?

Question: I wonder if anyone try using LINQ to Twitter 3.0 beta with Xamarin.iOS ? Joe Mayo provide an example of how using the library with Xamarin.Android However i can't seems to get that work on IOS > it's compiling, but it crashes at runtime because it's looking for not-existing assemblies
Answer: I wrote a blog, LINQ to Twitter Runs On Xamarin.iOS. A couple days ago, I also posted v3.0 as a pre-release on NuGet.

LINQ to Twitter Support Xamarin.iOS?


Extracting href using bs4/python3?

Question: i'm new to python and bs4, please go easy on me.
#!/usr/bin/python3
import bs4 as bs
import urllib.request
import time, datetime, os, requests, lxml.html
import re
from fake_useragent import UserAgent

url = "https://www.cvedetails.com/vulnerability-list.php"
ua = UserAgent()
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
snkr = requests.get(url,headers=header)
soup = bs.BeautifulSoup(snkr.content,'lxml')

for item in soup.find_all('tr', class_="srrowns"):
    print(item.td.next_sibling.next_sibling.a)

prints:
CVE-2017-6712
CVE-2017-6708
CVE-2017-6707
CVE-2017-1269
CVE-2017-0711
CVE-2017-0706

can't figure out how to extract the /cve/CVE-2017-XXXX/ parts. purhaps i've gone about it the wrong way. i dont need the titles or html, just the uri's.
Comment: `print(item.td.next_sibling.next_sibling.a.href)`
Answer: BeautifulSoup generally has too many historical variants for filtering and for fetching things, some of which are more annoying than others. I ignore most of them because it's confusing otherwise.
For attributes I prefer get(), so here  item.td.next_sibling.next_sibling.a.get('href'), because it returns None if there is no such attribute, instead of giving an exception.
Answer: I am also facing a same issue at initial stages of webscrapping, based on my experience i am sharing here
Great try, for you specific requirements pls try this below code
#python programming language
import bs4 as bs
import urllib.request
import time, datetime, os, requests, lxml.html
import re
from fake_useragent import UserAgent

url = "https://www.cvedetails.com/vulnerability-list.php"
ua = UserAgent()
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
snkr = requests.get(url,headers=header)
soup = bs.BeautifulSoup(snkr.content,'lxml')

for item in soup.find_all('tr', class_="srrowns"):
   print(item.td.next_sibling.next_sibling.a.get('href'))# you can get only this /cve/CVE-2017-XXXX/ type of links
   print('https://www.cvedetails.com'+item.td.next_sibling.next_sibling.a.get('href'))
#you try this one too, you will get as a working link

( or )
you need to get all href link in one run then try this one
images = []
for item in soup.find_all('a', href=True):
   images.append('https:'+item['href'])
   print(images)

also, dont use fake user agent use pyuser_agent, fake useragent wont work on linux os and server too, not support currently may be future update, it will be supported.

Extracting href using bs4/python3?


Find the dual problem of $\min_x\{||x-a_1||+||x-a_2||+||x-a_3||,a_i\in\mathbb{R}^n\}$

Question:
Find the dual problem of
$$\min_x\{||x-a_1||+||x-a_2||+||x-a_3||,a_i\in\mathbb{R}^n\}$$

I've tried the following but got stuck
$$\min_x\{||x-a_1||+||x-a_2||+||x-a_3||,a_i\in\mathbb{R}^n\}=\min_{x,z_i}\{||z_1||+||z_2||+||z_3||,a_i\in\mathbb{R}^n\,z_i=x-a_i\}$$
and the Lagrangian is:\
$L(x,z,\lambda)=  ||z_1||+||z_2||+||z_3||+\sum_{i=1}^3\lambda_i(z_i-x+a_i)=\sum_{i=1}^{3}z_i\lambda_i+||z_i||-x\sum\lambda_i+\sum\lambda_ia_i$
from $-x\sum\lambda_i$ we can deduce that $\sum \lambda_i=0$ else we get $-\infty$.
Now when I try to solve for each $z_i$ I get $\frac{\partial L}{\partial z_i}=\lambda_i+\frac{z_i}{||z_i||}=0$
and I'm not sure how to continue from here.
Any hint?
Answer: Based on your arguments, the remainder is to pay attention to the following quantity,
\begin{align}
F(\lambda)=\inf_{z\in \mathbb R^n} (\langle z, \lambda \rangle +||z||).
\end{align}
This quantity can be quantified using the notion of conjugate function. Recall that the conjugate function of $f$, denoted by $f^*$, is defined by
\begin{align}
f^*(y)=\sup_{x \in \mathbb R^n} (\langle x, y \rangle -f(x)).
\end{align}
Now, $F(\lambda)$ can be rewritten in term of conjugate function of $f(x)=||x||$ as follows
\begin{align}
F(\lambda) & =\inf_{z\in \mathbb R^n} (-\langle z, -\lambda \rangle +f(z))\\
           & = - \sup_{z\in \mathbb R^n} (\langle z, -\lambda \rangle - f(z))\\
           & = - f^*(-\lambda).
\end{align}
Here, in the case $f(x)=||x||$, $f^*$ is
\begin{align}
f^*(\lambda)=
\begin{cases}
0, & \text{ if } ||\lambda||_*\leq 1.\\
+\infty, & \text{ if } ||\lambda||_*> 1.
\end{cases}
\end{align}
Where $||\cdot||_*$ is the dual norm of $||\cdot||$. To see how to obtain such formula for $f^*$, see the first answer here.
Comment: I'm not familiar with conjugate function
Comment: In my answer, the conjugate function is defined explicitly in term of dual norm. I hope that know about it. Anyway, in most of duality results in optimization, conjugate function is the main tool!
Comment: We haven't learnt this yet and I guess in more advanced courses I will.Can you solve this only with norm duality and from where I stopped or give some hint??
Answer: According to the request of the host, I propose here an answer without using the notion of conjugate function. However I have to admit that the idea behind the computations is of conjugate function.

Recall that the Lagrangian function is
\begin{align}
L(x,z,\lambda)=\sum_{i=1}^{3} \langle z_i,\lambda_i\rangle +||z_i||-\langle x, \sum_{i=1}^3\lambda_i\rangle +\sum_{i=1}^3 \langle \lambda_i, a_i\rangle,
\end{align}
where $x, z_i, \lambda_i \in \mathbb R^n$ for $i=1,2,3$.
We claim that the dual problem is

$$\sup_{\lambda} \inf_{x,z} L(x,z,\lambda)
=\sup_{\lambda\in D} \sum_{i=1}^3 \langle \lambda_i, a_i\rangle. \label{eq1} \tag{1}$$

where
\begin{align}
D=\{\lambda=(\lambda_1, \lambda_2, \lambda_3): \sum_{i=1}^3\lambda_i=0 \text{ and }
||\lambda_i||_*\leq 1 \text{ for } i=1,2,3\}.
\end{align}
Here $||\cdot||_*$ is the dual norm of $||\cdot||$ in $\mathbb R^n$ and defined as
\begin{align}
||u||_*:=\sup_{||v||\leq 1} \langle u,v\rangle.
\end{align}

Proof of \eqref{eq1}.
We now focus on $\inf_{x,z} L(x,z, \lambda)$.
We claim that
$$
\inf_x -\langle x, \sum_{i=1}^3\lambda_i\rangle =
\begin{cases}
0, & \text{ if } \sum_{i=1}^3\lambda_i=0,\\
-\infty, & \text{ otherwise.}
\end{cases}
\label{eq2} \tag{2}$$
and
$$
\inf_{z_i} \langle z_i, \lambda_i \rangle +||z_i||=
\begin{cases}
0,       & \text{ if } ||\lambda_i||_* \leq 1,\\
-\infty, & \text{ if } ||\lambda_i||_* > 1.
\end{cases}
\label{eq3} \tag{3}
$$
If \eqref{eq2} and \eqref{eq3} hold true, we obtain the dual problem \eqref{eq1}.
Since the host already know how to prove \eqref{eq2}, we now only concentrate on \eqref{eq3}.
To simplify the notations, in \eqref{eq3} we shall remove the index $i$, i.e.
we are going to prove
$$
\inf_{z} \langle z, \lambda\rangle +||z||=
\begin{cases}
0,       & \text{ if } ||\lambda||_* \leq 1,\\
-\infty, & \text{ if } ||\lambda||_* > 1.
\end{cases}
\textbf{ for $z, \lambda$ are in $\mathbb R^n$ from here on.}
\label{eq4} \tag{4}
$$
Let $\lambda'=-\lambda$, we have
$$\inf_{z} \langle z, \lambda\rangle +||z||=-\sup_{z} \langle z, \lambda'\rangle -||z||.$$
Case 1. If $||\lambda'||_*\leq 1$, we have
$$\sup_{z} \langle \frac{z}{||z||}, \lambda'\rangle \leq ||\lambda'||_*\leq 1.$$
Here the first inequality holds due to the definition of dual norm.
Thus
$$\sup_{z} \langle z, \lambda'\rangle -||z||\leq 0.$$
Furthermore, the equality holds if we take $z=0$.
Case 2. If $||\lambda'||_*> 1$, from the definition of dual norm,
we deduce the existence of some $z$ such that $||z||\leq 1$
and $\langle z,\lambda'\rangle >1$.
Now, we have
$$\sup_{t\in \mathbb R} \langle tz, \lambda'\rangle-||tz||
=\sup_{t\in \mathbb R} t(  \langle z, \lambda'\rangle-||z||) =+\infty.$$
Note that $||\lambda'||_*=||\lambda||_*$, all together tell us that \eqref{eq4} is true.
Hence, \eqref{eq1} is true.
Comment: Thank you very much I appreciate this
Comment: you're welcome!
Comment: maybe you could take a look here?
https://math.stackexchange.com/questions/3972913/find-a-dual-problem-with-one-dual-decision-variable-to-the-problem-of-finding-th?noredirect=1#comment8196950_3972913


Getting jQuery to work in new build WordPress theme

Question: I am new to jQuery and have tried to get scripts to work to no avail. I would like to simplify my script to just see that my theme is in fact recognizing my scriptfile.js
My js file is just:
var success = 'SUCCESS!';

  jQuery('nav .home a').hover(function()
  {
    echo(success);
  });

my functions.php file has this:
<?php
function add_my_script() {
wp_enqueue_script(
'preview',
 get_template_directory_uri() . '/js/scriptfile.js',
array('jquery')
);
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );
?>

My header.php contains:

I am not getting any errors in firebug, but no output either.
Answer: Not sure if this is the problem but first of all your selector is not exactly right.
var success = 'SUCCESS!';

jQuery('nav .home a').hover(function(){ ... });

nav should be .nav for class or #nav for id
echo(success);

Unless echo() is a function somewhere it will not work. If you want to show an alert message use alert(success)
Answer: I believe what's happening is that your script file is being included fine but the way it's written the hover event attachment will happen before the DOM is ready. Try this, simply say alert(success); in your js file and see if the alert pops up. If it does, then wrap the hover event handler in a function in your script file and call that function from the document.ready function handler in your header.php. By the way, what's the echo function? Probably you are looking for alert.


Proof Hints: Teichmüller-Tukey Lemma

Question: Synopsis
Why this is NOT a duplicate (as far as I'm aware).
After having read the other posts on StackExchange about this lemma, many of them rely on concepts like well-ordering and other things I haven't learned yet. All I have learned so far is the axiom of choice and basic cardinality with nothing related to partial ordering or finite characters. So I hope this is enough justification for asking another question about this lemma. Please provide me with hints that don't utilize the concepts mentioned above.
Exercise
(Teichmüller-Tukey lemma) Assume that $\mathscr{A}$ is a nonempty set such that for every set $B$, $$B \in \mathscr{A} \Leftrightarrow \text{every finite subset of $B$ is a member of $\mathscr{A}$.}$$ Show that $\mathscr{A}$ has a maximal element, i.e., an element that is not a subset of any other element of $\mathscr{A}$.
What I've Tried
I started with the following attempt to apply Zorn's lemma:

Consider a chain $\mathscr{B} \subseteq \mathscr{A}$. We wish to show
that $\bigcup \mathscr{B} \in \mathscr{A}$. Let $x$ be a subset of
$\bigcup \mathscr{B}$. Then for all $x' \in x$, there exists a set $B
\in \mathscr{A}$ such that $x' \in B$. So $\{x'\} \subseteq B$ and
$\{x'\} \in \mathscr{A}$. Since $\{x'\}$ is a subset of $x$ and $\{x'\} \in \mathscr{A}$, then $x \in \mathscr{A}$ since it satisfies the requirements for $\mathscr{A}$. So $\bigcup \mathscr{B} \in \mathscr{A}$ and Zorn's lemma guarantees a maximal element.

Upon further examination, though, I realized that I haven't necessarily proved that every subset of $x$ was in $\mathscr{A}$, but only all singleton subsets. So I thought I might have to do something with $\bigcup x$ or maybe invoke the form of the axiom of choice that guarantees a choice function. But I didn't know how to proceed and I confused myself quickly. As such, I would appreciate any hints in showing that $\bigcup \mathscr{B} \in \mathscr{A}$ (assuming that Zorn's lemma is the right path towards the solution). Thank you.
Answer: You need to use the fact that $\mathscr{B}$ is a chain. You want to show that every finite subset of $\bigcup\mathscr{B}$ is a member of $\mathscr{A}$, so let $F$ be a finite subset of $\bigcup\mathscr{B}$. For each $x\in F$ there is a $B_x\in\mathscr{B}$ such that $x\in B_x$. $\mathscr{B}$ is a chain, and $F$ is finite, so $\{B_x:x\in F\}$ has a maximum element $B_{x_0}$. But then $x\in B_x\subseteq B_{x_0}$ for each $x\in F$, so $F\subseteq B_{x_0}$. Finally, $B_{x_0}\in\mathscr{A}$, so $F\in\mathscr{A}$, as desired.
Comment: @mijucik: Being a chain in this context simply means that $\mathscr{B}$ is linearly ordered by $\subseteq$. Thus, the sets $B_x$ for $x\in F$ can be linearly ordered by $\subseteq$. If $|F|=n$, say, we can index $F$ as $\{B_1,\ldots,B_n\}$ in such a way that $B_1\subseteq B_2\subseteq\ldots\subseteq B_n$, and $B_n$ is then the maximal element of $\{B_x:x\in F\}$. Every finite subset of a linearly ordered collection automatically has both a maximum and a minimum element.
Comment: @mijucik: I'm really not at all sure that you need to prove that a finite chain has a maximum element, but if you feel that it's necessary, a proof by induction on the cardinality of the chain would work.
Comment: @mijucik: You're welcome.
Comment: Where do you get the fact that $\{B_x: x \in F\}$ has a maximum element? I haven't encountered chains much yet to be honest, so I was wondering if you could elaborate a little more on that.
Comment: I see. That makes sense now. Sorry I deleted my past comments because I thought my need for a proof to be unnecessary. Thank you, though, for the suggestion.

Proof Hints: Teichmüller-Tukey Lemma


Getting the profile2 user fields?

Question: i am writing a simple multistep form using ctools on drupal 7. Everything seems to work but i have a one last problem before i finish the task. How can i access the custom user fields (or fieldset i am not sure about the terminology). I've tried to do that by using the function below but it doesn't works and the property is always empty;
function helper_get_default_value_from_profile($fieldset, $key){

  $uid      = helper_is_user_logged_in();
  $account  = user_load($uid);
  $profile  = profile2_load_by_user($account, "cv");

  if(!property_exists($profile, $fieldset))
    return 0;

  if(empty($profile->$fieldset))
    return 0;

  $fieldset_ref = $profile->$fieldset;
  $id           = $fieldset_ref["und"][0]["value"];
  $fieldset_data = field_collection_field_get_entity($id);

  if(!property_exists($fieldset_data, $key))
    return 0;

  if(empty($fieldset_data->$key))
    return 0;

  $user_prop = $fieldset_data->$key;
  return $user_prop["und"][0]["value"];
}

Answer: It seems like you want to retrieve the value of a single field from a field collection. And that the field collection you want to retrieve a field from is a field of a 'cv' profile2.
The returned value of profile2_load_by_user($account, "cv"); is a Profile entity object. When $fieldset is the (machine) name of a field collection field, then you can retrieve its value using $items = field_get_items('profile2', $profile, $fieldset) (see field_get_items()). This will return an array of field collection values (or FALSE if there is no value for the field). The values are arrays containing a value entry which is the entity id of a field collection entity. You can load the field collection entity for an ID using field_collection_field_get_entity(). Finally, using $key as field name, you can retrieve the values of one of this field collection entity's fields using field_get_items() again.
$items = field_get_items('profile2', $profile, $fieldset);
if ($items) {
  $item = reset($items);
  if (!empty($item['value'])) {
    $field_collection = field_collection_field_get_entity($item);
    if ($field_collection) {
      $items = field_get_items('field_collection', $field_collection, $key);
      if ($items) {
        $item = reset($items);
        return !empty($item['value']) ? $item['value'] : 0;
      }
    }
  }
}
return 0;

Getting the profile2 user fields?


Distribution of random sample of confidence intervals containing the true mean

Question: Given 50 random samples, each of size 25, from a normal distribution with mean 20 and standard deviation 5. From each of the 50 samples, you can find a 90% confidence interval for the mean. Let Y be a random variable indicating how many of the confidence intervals containing the mean. What is the distribution of Y?
My friend and I are having a heated discussion about this. I think it is binomially distributed with 50 observations and probability of success 90%. My friend claims it is normally distributed with mean 45 and standard deviation 1.
I think this because Y has a fixed number of observations (50), each observation has two outcomes, and their probabilities are fixed (probability of containing the mean is 90%).
Comment: Your reasoning is pretty good. :-) What is your friend's argument?  Although you both agree on the expectation of $45$, you differ on the standard deviation (yours is $\sqrt{0.1\times 0.9\times 50}=2.1$): how does your friend obtain the value of $1$? (To be generous, we must understand your friend's answer to be an *approximation*: after all, that Normal distribution has *no* chance of yielding an integral outcome!) Have you thought of actually carrying out this procedure (with a simulation) to see who is right?
Comment: I don't know his reasoning, I also got 2.1 as the standard deviation, though. I'm pretty new to statistics so i don't know how to carry out a simulation. Care to explain?
Answer: Your reasoning is good.  The purpose of this answer is to show how you can check it out.  It's a very useful skill, because we all make mistakes--and this allows us to find them in private before they become embarrassing :-)
The process described below is the important thing to follow, because it can be used over and over again to address all kinds of statistical questions, both simple and sophisticated.  I am using R because it is free and popular, but the same approach will work in other statistical computing platforms, such as Python, Mathematica, Matlab, or whatever.
The heart of the question concerns a confidence interval for a sample from a Normal distribution.  So, we begin with code to compute a CI of a set of numbers z and check whether it covers the mean mu with confidence level 1-alpha:
covers <- function(z, mu=0, alpha=0.10) {
  n <- length(z)
  abs(mean(z) - mu) <= qt(1 - alpha/2, n-1) * sqrt(var(z) / n)
}

This computation should look familiar, involving the mean, variance, and length of z along with a comparison to a critical Student t-value computed with qt.  The comparison results in a value of 1 when true and 0 otherwise: this is the output of covers.
To simulate one experiment we need to (1) generate random samples z; (2) do this 50 times over; and (3) count how many of those 50 samples have CIs that cover the mean.  As in much of mathematics and computer science, the correct expression is developed from the inside out, so the following line executes these operations in the order (3)-(2)-(1) using sum (which, by summing the zeros and ones returned by covers, is precisely the count associated with the random variable $Y$), apply, and rnorm, respectively:
n <- 50
k <- 25
mu <- 20
sum(apply(matrix(rnorm(k*n, mu, 5), nrow=k), 2, covers, mu=mu))

To make it a little more readable and a lot more flexible I have placed the numbers 50, 25, and 20 in variables.  Changing the values of these variables lets you play with variations of the problem.
Running a simulation calls for repeating this operation over and over and collecting the results.  Do this by wrapping the preceding within a call to replicate:
sim <- replicate(1000, {
  sum(apply(matrix(rnorm(k*n, mu, 5), nrow=k), 2, covers, mu=mu))
})

The argument 1000 specifies how many independent runs to perform.  Because I have made no effort at computational efficiency, this will take a few seconds for a thousand iterations.  But a thousand will be more than enough.  All these results are collected into the array named sim for further analysis.
Finally, we should plot the results and perhaps perform a few tests, as if such formalities really mattered:
hist(sim, freq=FALSE, breaks=min(sim):(n+1)-1/2, ylim=c(0, dnorm(0.9*n, 0.9*n, 1)),xlab="Y")
curve(dnorm(x, 0.9*n, 1), col="Red", add=TRUE)
points(min(sim):n, dbinom(min(sim):n, n, 0.9), pch=19, col="Blue")

Over a histogram (via hist) I have superimposed the putative Normal density function (via curve) as well as the (correct) Binomial distribution (via points).  Clearly the Normal distribution isn't even a good approximation to the results: although its peak is in the right place, its standard deviation is far too small.

A $\chi^2$ test amply supports the visual impression that the binomial distribution (blue dots) is the true underlying distribution:
chisq.test(tabulate(sim+1, n+1), p=dbinom(0:n, n, 0.9), simulate.p.value=TRUE)

The output is

X-squared = 10.0457, df = NA, p-value = 0.7441

The large p-value says the simulation results cannot be distinguished from 1000 independent draws from a Binomial$(50, 0.9)$ distribution.  (Your output will differ slightly because the random values in your simulation will differ from mine.)
Comment: Wow, thanks! Good verification to a possible answer through simulation. Thorough answer.


How to Show Representations of an Infinite Group are not Equivalent?

Question: I have unitary representations of an infinite group (but finitely generated) on an infinite dimensional Hilbert space. I would like to show that two representations are not equivalent. I am guessing I would need to find some invariant property of an representation and then show the two representations do not share the same invariant property. However after quite a bit of searching on the internet, I could not find any invariants that apply to representations on an infinite group. All I could find were invariants of representations of finite groups.
Are there are any invariants of representations of infinite groups? Are there any other methods of proving two representations are not equivalent? Also in general, I would like to learn more about representations of infinite groups. Could you recommend some resources I could look at?
Comment: This is a much too broad question.  Perhaps if you described the two representations you have in mind people could narrow down on a specific technique.
Comment: @Ruy The representation and the Hilbert space is not easily described. It would take a while to fully describe it here. Would it be possible to just provide some examples of methods that can be used to prove that two representations are not equivalent? I understand it won't be able to be applied to all cases, but it will help me understand what kind of approaches work and get a flavour of the techniques used. At the moment, I have very little idea on how to approach this question.
Answer: To fix notation let $u_1$ and $u_2$ be two unitary representations of the group $G$ on Hilbert spaces $H_1$ and $H_2$.
One of the most elementary reasons why $u_1$ and $u_2$ might fail to be unitarily equivalent is spectra:  if there is an element
$g$ in $G$ such that the spectrum of $u_1(g)$ differs from the spectrum of $u_2(g)$, then clearly $u_1$ and $u_2$ are
not unitarily equivalent.
This is not such a fine invariant, though, since representations if infinte groups often involve only  unitary operators
with full spectrum, but of course this is a start.
The representation theory of $G$ is equivalent to the representation theory of the Banach $^*$-algebra $\ell ^1(G)$, in the
sense that each $^*$-representation of the latter restricts to a unitary representation of $G$ and,  conversely,  every
representation $u$ of $G$ integrates to a representation $\pi $ of $\ell ^1(G)$ according to the formula
$$
  \pi (f) = \sum_{g\in G}f(g) u_g, \quad \forall f \in  \ell ^1(G).
  $$
The advantage of working with $\ell ^1(G)$ is the availability of a linear structure.  For example,  the kernel of the
integrated representation $\pi $ is a two-sided ideal in $\ell ^1(G)$,  and is thus an invariant for the representation $u$
from which $\pi $ has been integrated.
The envelopping C$^*$-algebra of $\ell ^1(G)$,  called $C^*(G)$,  is also a very useful gadget because, like $\ell ^1(G)$, its representation theory is
also equivalent to the representation theory of $G$. However   it  has several  advantages due to the fact that its
representation theory is highly developped.
To be a bit more precise,
given a unitary representation $u$ of $G$, the integrated representation $\pi $ on $\ell ^1(G)$ extends to
$C^*(G)$ due to the universal properties of the envelopping C$^*$-algebra, and if $\rho $ denotes this
extension, then again the kernel of $\rho $ is an invariant of $u$.
Given the finer structure of $C^*(G)$, the kernel of
$\rho $ carries much more information about $u$.  For instance, if two unitary representations $u_1$ and $u_2$ give rise to
representations $\rho _1$ and $\rho _2$ of $C^*(G)$ with the same kernel, then $u_1$ and $u_2$ are mutually weakly contained in
each other in the sense that, for every $\xi $ in $H_1$, the  positive type function on $G$ given by
$$
  g\in   G\mapsto \langle u _1(g)\xi ,\xi \rangle \in {\mathbb C}
  $$
can be approximated by positive type functions coming from vectors in the representation space of $u_2$, and vice-versa.
Another very useful algebraic invariant is the commutant of a unitary representation $u$,  defined to be the set $u(G)'$
formed by all
bounded, linear
operators $T$ commuting with every $u_g$.
$u(G)'$ is  a von Neumann algebra and it carries a lot of information about multiplicities of sub-representations of
$u$.  For instance, $u(G)'$ is isomorphic to ${\mathbb C}$ iff $u$ is irreducible while $u(G)'$ is abelian iff $u$ is multiplicity
free.
The von Neumann algebra generated by $u(G)$, namely the  commutant of $u(G)'$, is a further very important invariant.
Given the rich theory of classification of von Neumann algebras  in types, many invariants can be extracted from $u(G)''$.
Comment: (1) Yes,  if $V$ is a unitary such that $u_1= Vu_2V^{-1}$,  then it follows easily that $\pi _1(f)= V\pi _2(f)V^{-1}$,  for all
$f$ in $\ell ^1(G)$,  so $\pi _1$ and $\pi _2$ must have the same kernel. (2) A nice reference is: Pedersen, G.K.; C*-Algebras and Their Automorphism Groups.
Comment: Thanks, these are all really great examples. I am not familiar with some of these concepts such as enveloping C*-algebras, so I will take some time to read up on these and fully digest your answer. Just want to clarify one thing, so are you saying that if the kernel of the integrated representations from two unitary representations ($u_1, u_2$) are not equal, then $u_1$ and $u_2$ are not equivalent? Also would you be able to recommend some resources to learn more about these concepts?
Comment: Sorry, this may be a silly question, but if $u_1$ and $u_2$ are equivalent (not necessarily unitarily equivalent), then aren't their kernels also equal? Why consider the integrated representations and only restrict to unitarily equivalent representations?
Comment: If $\sup_g\|u_g\|<\infty$ one may still define the integrated form but otherwise the sum may not converge.  One can always define the integrated form on the subalgebra of $\ell^1(G)$ formed by the finitely supported sequences, aka the group algebra, but I suspect its kernel will carry even less information.


What to bootstrap for hypothesis testing

Question: I have a small question about the concept behind hypothesis testing using bootstrap. Assume that I need to evaluate two independent population mean differences: population a and population b. My doubt is the following:

Should I apply bootstrap on a single population, and check the difference of the mean after that?
Mean[BOOT(a)-BOOT(b)]

Alternatively, should I compute di difference: Mean(a)-Mean(b) and then apply bootstrap?
BOOT[Mean(a)-Mean(b)]

I used this code by using the second approach:
set.seed(123)
a <- rnorm(100)
b <- rnorm(100)
hist(a)
hist(b)

c = a-b
hist(c)

boot_1 = function(R,dati_oss){
  n = length(dati_oss)
  media_boot = vector("numeric",R)
  for(i in 1:R){
    ind = sample(1:n,replace=T)
    media_boot[i] = mean(dati_oss[ind])
  }
  return(media_boot)
}

res=boot_1(500000,c)

hist(res)

stat = matrix(c(mean(c), mean(res), mean(res)-mean(c), sqrt(var(res)),
              as.vector(quantile(res, c(0.025,0.975)))), 1, 6)
colnames(stat) = c("Observed", "Mean-boot", "Bias", "SE", "0.95LCI", "0.95UCI")
row.names(stat) = c("Mean")
stat

Comment: Did you try running your code? I get an error. Also, your code doesn't actually match your method 2.
Comment: @gung where did you get the error?
Comment: After running `res=boot_1(500000,c)`.
Comment: @MichaelM Thanks, I just wanted to know if approach 1 or 2 is correct.
Comment: @gung I don't have this problem, try with fewer reps res = boot_1 (5000, c)
Answer: The basic principle to apply, quoting @MichaelChernick, is: "Sampling with replacement behaves on the original sample the way the original sample behaves on a population."
Think about how you analyzed the original sample. You took the sample, calculated the mean of each of the 2 groups, and determined the difference between their mean values to get an estimate of the a-b difference.
So you proceed similarly with each bootstrapped resample: resample from the original sample, calculate the mean of each group, and determine the difference between the means of the two groups as represented in the resample. Do this a large number of times to estimate the distribution of a-b differences. Compare the mean of the bootstrapped a-b differences against the a-b difference found in the original sample to estimate the bias in the original a-b difference.
Note that the way you design the resampling might depend on the original study design. If you had two independent populations from which you took samples, then the resampling should proceed comparably, within each of the populations. If you sampled from a mixed population in which individual cases were labeled as belonging to population a versus b, then you should resample from a pool of all the cases in the original sample.
Answer: Without going into the coding of it, consider what happens if you calculate Mean(a)-Mean(b) first (proposal 2). You calculate Mean(a) and get a single number, then you calculate Mean(b) and get a single number. Then you take your two numbers, and calculate Mean(a)-Mean(b) to get a single value for your difference. No matter how many times you sample/bootstrap this single value, you will get the same number. Try it out!
Whereas if you take multiple samples of your population A and population B, then calculate the difference of means of your samples (proposal 1) you will get slightly different combinations nearly every time you sample (assuming you don't re-set the random seed at the wrong point in your code), so you will get a range of values for the difference.
I would consider proposal 1 to be a form of bootstrapping, but I wouldn't say the same about proposal 2!


Why ie7 lacks of text-decoration: underline on mouse over?

Question: Why ie7 does not apply text-decoration: underline on mouse over ?

      TEST

Comment: IE7 usage is so minimal I wouldn't worry about it.
Comment: this doesn't directly apply but it has some comments on a similar issue|http://forums.whirlpool.net.au/archive/1395829
Answer: Try changing overflow to visible , just to see if it shows in ie7. And also add !important.
Also, you have a lot of extra lines in your hover that aren't necessary since they are the same as in your .main. So you can clean that up by removing those lines if you want.
.main:hover{
         padding: 0 10px;  //you don't need this line
     height:45px; // nor this one
     float:left; // nor this one
     color:#191919;  //nor this one
     text-align:center; // nor this one
     overflow: visible;
         list-style: none; // nor this one
         text-decoration: underline !important;
}

Answer: Did you try to apply the style on actual anchor tag?
a:hover{
     padding: 0 10px;
     height:45px;
     float:left;
     color:#191919;
     text-align:center;
     overflow:hidden;
     list-style: none;
     text-decoration: underline;
}

Answer: I believe with the newer versions of CSS, the text-decoration value was transformed from having only a single input to multiple i.e. the ability to use 'color, line, and style'. Using MDN as a reference, it states that text-decoration is now considered a 'shorthand property' which is no longer supported in IE. More information is found on the link I provided in the text.
I think the alternative is to use text-decoration-style, which is more specific and should be supported.
I hope this is correct, if not.. I can delete it :)
Comment: The MDN page is very confusing as regards to browser support information. Surely the transmogrification to a shorthand in some CSS drafts does not change the way things work in IE 7!
Comment: I could only hope so, I was just unsure but it seems like you fixed the problem just fine :)
Answer: IE 7 implements text-decoration wrong in some situations: setting text-decoration: none on an inner element may prevent the underline set on an outer element from appearing under the inner element. It is intuitively understandable, but against the specification.
As a workaround, set the underline for both the outer element and the inner element.
For the messy code in the question, the minimal fix would be to add the following CSS rule:
.main:hover a { text-decoration: underline !important; }

In this fix, the !important specifier is needed because the inner element has text-decoration set in a style attribute.
Answer: Use this :
text-decoration: underline !important;


Strongly monotone and cocoercive

Question: A map $f:\mathbb{R}^n\rightarrow\mathbb{R}^n$ is $m$-strongly monotone if
$$
(x-y)^{\sf T}((f(x)-f(y)) \geq m \|x-y\|_2^2
$$
for $m > 0$ and is $\delta$-cocoercive if
$$
(x-y)^{\sf T}((f(x)-f(y)) \geq \delta \|f(x)-f(y)\|_2^2
$$
for $\delta > 0$. I am working on a proof where I need instead the following property:
$$
(x-y)^{\sf T}((f(x)-f(y)) \geq m \|x-y\|_2^2 + \delta \|f(x)-f(y)\|_2^2\,.
$$
for $m, \delta > 0$.
Is there a standard name for this property, or some results? I can see that it is implied by $f$ being both $2m$-strongly monotone and $2\delta$-cocoercive, but this ends up not being useful for my problem. Moreover, I can see that it is stronger than $f$ being both $m$-strongly monotone and $\delta$-cocoercive.
Answer: The property you stated is equivalent to $f$ being strongly monotone and Lipschitz continuous; searching for this combination of terms will bring up a number of papers. It doesn't have a single-word name, since "Lipschitz strongly monotone" is short enough, and self-descriptive.
Here's a justification. If $f$ is $L$-Lipschitz and $m$-strongly monotone, then
$$(x-y)^{\sf T}((f(x)-f(y)) \geq m \|x-y\|_2^2 \ge mL^{-2}\|f(x)-f(y)\|_2^2$$
hence
$$(x-y)^{\sf T}((f(x)-f(y)) \geq \frac{m}{2} \|x-y\|_2^2 + \frac{m}{2L^{2}}\|f(x)-f(y)\|_2^2$$
Conversely, if
$$(x-y)^{\sf T}((f(x)-f(y)) \geq m \|x-y\|_2^2 + \delta \|f(x)-f(y)\|_2^2\,$$
then $$\|x-y\|_2 \|f(x)-f(y)\|_2 \geq \delta \|f(x)-f(y)\|_2^2\,$$
hence
$$\|f(x)-f(y)\|_2  \le \delta^{-1} \|x-y\|_2$$

Strongly monotone and cocoercive


Usar Sintaxe Alternativa muda o desempenho?

Question: Usar a Sintaxe Alternativa para estruturas de controle traz enormes mudanças na quantidade de linhas de code de um projeto, mas existe algum mudança em desemepenho?
Comment: Não ⊂(▀¯▀⊂) ⊂(▀¯▀⊂)
Comment: Dificilmente ...
Comment: Faz diferença mesmo é na legibilidade do código. Se você usar o operador ternário para controle de fluxo, o código fica bem menos legível.
Answer: Dificilmente isso faria algum efeito no desempenho. O PHP e outras linguaguens de script já perdem desempenho(comparada as compiladas) por serem interpretadas. Desempenho deve ser o quando encontrar algum gargalo no sistema(lentidão), mas primeiro é necessario mensurar isso, senão como vai saber?
Answer: A quantidade de script a mais é muito pequena (pode se dizer insignificante), então dessa forma o processamento será rápido e sem visíveis mudanças.


Need help styling a TabNavigator in Flex

Question: I have a tab navigator control and I would like to make all of the tabs a certain color, say blue...
How can this be done?
I have tried through the following CSS:

TabNavigator
{
    tabStyleName: "tabs";
}
.tabs {
    backgroundColor:#6588b9;
}

but it only seems to work with the selected tab...
I then tried to do it programtically:

for(var i:int=0; i<num_of_tabs; i++)
    tn.getTabAt(i).setStyle("backgroundColor","blue");

Yet the same thing happens (only the selected tabs shows the blue background)
What can I do so that all the tabs are blue? Am I going to have to look into skinning?
Thanks.
Answer: I've got a project with styled tabs (I assume you mean the tabs themselves, and not the content).  I'm sure there's other ways, but this is what I seem to have ended up with:
.myTabStyle {
    tabStyleName: "myTabs"
}
.myTabs {
    backgroundColor: #ff0000;
    fillColor: #000000;  /* this is the tab widget itself, not the content */
}
<mx:TabNavigator ... styleName="myTabStyle" .. >

There's several places in Flex where you have to use CSS styles to refer to other styles to drill into the widget you want (another example is setting the titlebar style on a TitleWindow).
I hope this helps.
By the way, I've seen occasional "tearing" on Mac & Windows, FireFox, IE, Safari, Flash 9 and 10 with large fonts & colored tabs--I'm not sure if this something I'm doing, something about the larger fonts, or the colored tabs themselves--but just a heads-up.  This only happens when building with the Flex 3 SDK (never saw it with Flex 2).


How to add a custom attribute to the script tag via drupal_add_js?

Question: As part of API implementation of Queue-it framework, I need to add extra custom attribute data-queueit-c into script tag, e.g.

I'm aware you can add other attributes such as defer, however this one is custom.
I've tried the following code using drupal_add_js, but without luck:
drupal_add_js('//static.queue-it.net/script/queueconfigloader.min.js',
  [
    'type' => 'external',
    'data-queueit-c' => 'MyClientID',
  ]);

How this can be achieved?
Answer: It's old but I have the same problem (adding "crossorigin" attribute) and this is my answer :

There is an issue about it here : https://www.drupal.org/project/drupal/issues/1664602
@kenorb solution can't work because "drupal_add_js" add "script" tag automatically.
But... you can try this workaround (a little dirty) :
close the script tag and open yours without closing

.
drupal_add_js('//--><!]]></script>";
drupal_add_js($js_code, 'inline');

Comment: The alternative looks like a real pain. `drupal_get_js` is very selective about what attributes it will use, so you'd need to re-implement that whole function and at the same time convince the system to use your new version instead. Not worth the hassle IMO
Comment: This does not seem to work, here is what i get :

//-->
Comment: @Thony This solution is for Drupal 7, maybe you're using 8.
Comment: No I am using 7


Java program crashing when it overwrites an existing .txt file?

Question: I'm making a simple text based game where you have to type commands to preform certain actions. I recently added a feature to the game that allows you to save your progress. But for some reason if you try to save your game over an existing save file it crashes. Here is the code that saves the game (when it fails to save it says "There was an error when trying to save game data. The game will now close." like expected):
import java.util.Formatter;
import javax.swing.JOptionPane;

public class Gamesave {
    private static Formatter gamesave;
    private static Formatter firstTimeSave;
    private static Formatter attackpoints;
    private static Formatter defensepoints;
    private static Formatter skillpoints;
    private static Formatter wins;
    private static Formatter loses;
    private static Formatter money;
    // Attackpoints, defensepoints, skillpoints, wins, loses, money
    public static void openFile(){
        try{
            attackpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_attackpoints.txt");
            defensepoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_defensepoints.txt");
            skillpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_skillpoints.txt");
            wins = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_wins.txt");
            loses = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_loses.txt");
            money = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_money.txt");
            gamesave = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+".txt");
            firstTimeSave = new Formatter("c:\\FightNight\\Game Data\\firstTimeSave.txt");
        }catch (Exception e) {JOptionPane.showMessageDialog(null, "There was an error when trying to save game data. The game will now close."); System.exit(0);}

    }

    public static void addRecords(){
        attackpoints.format("%s",MainClass.attackpoints);
        defensepoints.format("%s",MainClass.defensepoints);
        skillpoints.format("%s",MainClass.skillpoints);
        wins.format("%s",MainClass.wins);
        loses.format("%s",MainClass.loses);
        money.format("%s",MainClass.money);
        firstTimeSave.format("%b", MainClass.firstTime);

    }

    public void closeFile(){
        attackpoints.close();
        defensepoints.close();
        skillpoints.close();
        wins.close();
        loses.close();
        money.close();
        gamesave.close();
        firstTimeSave.close();
    }

}

Here is the code that calls the classes:
static class SaveAction implements ActionListener{
        public void actionPerformed (ActionEvent e){
            try{
                Gamesave.openFile();
                Gamesave.addRecords();
                save.closeFile();
                JOptionPane.showMessageDialog(null, "Your game has been saved.");
            }catch (Exception e1) {JOptionPane.showMessageDialog(null, "Sorry, that is an invalid response.");}
        }
    }

Another note, when the game is launched for the first time on a computer it creates the directories for the save files and anything else needed. Thank you for any help!
The stack trace:
java.io.FileNotFoundException: c:\FightNight\Saves\null\null_attackpoints.txt (The system cannot find the path specified)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.util.Formatter.<init>(Unknown Source)
    at Gamesave.openFile(Gamesave.java:16)
    at CommandLine$SaveAction.actionPerformed(CommandLine.java:93)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Comment: Please copy the stack trace launching from command line.
Answer: It seems all your GameSave methods are static, save for the closeFile method. However all reference the same fields. Try make closeFile static. It seems to reference static fields after all.
And of course, call it like the other methods, as in: GameSave.closeFile, not someInstanceOfGameSave.closeFile.
Finally, if that doesn't work, add the line e.printStackTrace(); before showing your message dialog and print the resulting stack trace as an edit of your question.
Edit
Make sure you check for nulls in your closeFile method as well.
Comment: Thank you very much for the help, I managed to fix it thanks to you!
Answer: It is because you have nulls in your file path. Notice the first line of your error stack
 java.io.FileNotFoundException: c:\FightNight\Saves\**null\null**_attackpoints.txt (The system cannot find the path specified)

There is no possible way that you can have a null in the file path name. So, with that being said, you need to go back and fix the objects that are containing the information in this part of the code. Also notice this:
at Gamesave.openFile(Gamesave.java:16)

This line tells you exactly where the error is..
So, lets check that method...
 try{
        attackpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_attackpoints.txt");
        defensepoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_defensepoints.txt");
        skillpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_skillpoints.txt");
        wins = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_wins.txt");
        loses = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_loses.txt");
        money = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_money.txt");
        gamesave = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+".txt");
        firstTimeSave = new Formatter("c:\\FightNight\\Game Data\\firstTimeSave.txt");
    }catch (Exception e) {JOptionPane.showMessageDialog(null, "There was an error when trying to save game data. The game will now close."); System.exit(0);}

I'm not seeing a way that this class accesses the static class "MainClass"'s newProfileName variable....so there is most likely the reason as to why you are not getting the proper information in the file name..
I'd say to update the newProfileName inside the try/catch block, to keep it up to date...
something like so
  try{

        MainClass.newProfileName = //accessed information from whereever you get your new profile name in the Code....
        attackpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_attackpoints.txt");
        defensepoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_defensepoints.txt");
        skillpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_skillpoints.txt");
        wins = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_wins.txt");
        loses = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_loses.txt");
        money = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_money.txt");
        gamesave = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+".txt");
        firstTimeSave = new Formatter("c:\\FightNight\\Game Data\\firstTimeSave.txt");
    }catch (Exception e) {JOptionPane.showMessageDialog(null, "There was an error when trying to save game data. The game will now close."); System.exit(0);}

The system is getting a null in the file name, which cannot be. Null means it is nothing, an d has no directory position...so find a way to update that variable, and that should fix it...
Hope this helps!
Comment: Okay, no problem :) just a little clarification on how to read the errors and apply them is all :)


Completely factoring $a^3 + b^3 + c^3 - 3abc$?

Question: How do I completely factor $a^3 + b^3 + c^3 - 3abc$ over the complex numbers? The first thing I did is factor this into $(a + b + c)(a^2 + b^2 + c^2 - ab - bc - ac)$. But I am not sure how to factor $a^2 + b^2 + c^2 - ab - bc - ac$ over the complex numbers. Can anyone help me?
Comment: Have you seen [this](https://math.stackexchange.com/questions/475354/how-to-show-that-a3b3c3-3abc-abcab-omegac-omega2ab-omega2?rq=1)?
Comment: Hint: As you might know from your inequalities training, $a^2 + b^2 + c^2 - bc - ca - ab = \dfrac12\left(x^2 + y^2 + \left(x-y\right)^2\right)$ where $x = b-c$ and $y = c-a$. So now you need to factor a homogeneous polynomial in two variables $x$ and $y$. This is tantamount to factoring a (non-homogeneous) polynomial in one variable.
Comment: [Here](https://www.amazon.co.uk/Mathematical-Olympiad-Treasures-Titu-Andreescu/dp/081768252X/ref=sr_1_1?dchild=1&keywords=mathematical+olympiad+treasures&qid=1604233692&sr=8-1) is another one, pages 3-4 in preview mode.
Answer: $a^3+b^3+c^3-3abc=(a+b+c)(a+b\omega+c\omega^2)(a+b\omega^2+c\omega)$, where $\omega$ is the root of $x^2+x+1=0$.


Load iframe and reset document location at the same time

Question: Load iFrame and reset document location at the same time.
I'm making a video album for a DVD present to family members. The video's will be displayed in an iFrame similar to YouTube's, with thumbnails below representing the various videos.
I've got the videos loading into the iFrame correctly, but I can't seem to get the onclick function to work more than once to bring the iframe back into to viewing position when I get to the bottom rows of the video thumbnails.
I'm very new to using JavaScript and can't seem to figure out how to make both events happen at the same time, load the new video and bring the iframe back into it's original viewing position.
Here's the code I'm using to change the frames which works flawlessly:

Here's the code I attempted to use with the a href on click function that works flawlessly (only once per page load) which I need to somehow work into the original frame loading code.

description here

I know it must be very easy for someone who knows what they're doing with JavaScript, but for me at this time, it's extremely frustrating as I don't yet have enough knowledge to build my own scripts, and have not successfully been able to marry the code into one script or figure out how to circumvent the onclick problem.
Help! How do I put the document location function into the onload function and bypass the onclick problem and bring the iFrame window back into the viewable portion of the screen on load?
Comment: Do you have a link to the page?
Answer: I'm not sure if I understand correctly, but what I got is this:
You have a page with an iframe at the top.There are many links, going down;
If someone clicks on one of them, the chosen video loads into the iframe

Also, there is the onclick which will call toFrame() to "scroll" the page back up again.
I think if you just place an anchor like

before your iframe and change your toFrame() function to be
function toFrame(){
    location.hash = "#topOfPage";
}

It should always scroll up to there.
EDIT:
Ok, I looked at it again, recreated it in html files and found the following to work for me:
function toFrame() {
    location.hash = '';
    location.hash = '#videotop';
}

It seems to be important to reset the location to empty, otherwise it wont scroll.
Now you're welcome :) (I hope this works for you)
Comment: @Geoffrey Burdett
(I do not have a link to the page, it's being built local for use on a DVD, as the initial question states.)
Comment: **@Palatiner** The original question also shows the anchor #videotop in the toFrame() function, and as far as I can tell, "location.hash = "#topOfPage"; basically does the same thing as the original coding of the toFrame() function, so by making the suggested change, the onclick problem persists and so does my dilemma.

The basic problem is that the **onclick no matter how I code it, scrolls the page back to the anchor only on the 1st click** on any of the group of linked thumbnail images.
Comment: On any successive clicks on the same or other thumbnail links, the video loads but the document does not scroll back to the anchor above the iframe.

How do I load the video and scroll back to the anchor **without using the onclick, which** apparently **works only ONE TIME per page load.**
Comment: Really, all I need to know is how to put function 'loadsource()' and function 'toFrame()', or their equivalent, into the same script so that it loads the iframe and scrolls the document back to the anchor above the iframe when the href tag is clicked. Can anyone help?
Comment: You could try to get rid of the ``<a href="../vpages/video-21.htm" `` completely and make it call a modified version of ``loadsource()`` in an onclick attribute. See if that works more than once and you might gain some insight. Also, you should try debuggin you javascript. If you don't want to bother with breakpoints, just but the line: ``debugger;`` anywhere you want to break and attach the javascript debugger. What browser do you use anyways?
Comment: **@Palatiner ** I've tried this code in Chrome, Firefox and IE10 with the same results in all browsers.

I don't know how to use a debugger yet, as I'm still working on my first "Hello World!" JavaScript!

I'm just stumbling through finding code snippets I can piece together to make my wife happy by finishing this project that she dreamt up. What do you mean by a modified version of loadsource()?
Comment: Based upon what I've been able to learn about the onclick attribute, it seems like many people have the same problem of the onclick firing only once per page load. Isn't there a way to call the iframe load and the #anchor from the same script without using the onclick attribute?

I see it happening on other pages on the internet, but it's buried deep in special js coding that I can't figure out.

Thanks for your attempt to help me get through this.
Comment: You should definitely look into jQuery. It will make your life *so much* easier. Forget the "modified version" of that function. Go jQuery! It will make your wife happy :D If you need help (once you figured out the basic stuff like selectors and events), I'll gladly be there for you!
Comment: Look at the anwer again, I changed it!
Comment: **Palatiner** Thanks for taking the time to look over the code again and make the revision to your first suggestion.  It now works in all three major browsers.  Now I can get on to learning JavaScript (in whatever free time I can redirect after I finish this project,) and actually code my first "Hello World!" script!  As I had originally suspected, the project was just a few simple lines of code away from the finish line.  It's amazing what you can  do with a little bit of specific knowledge. Thanks a bunch for all your help with this!


Are we still limited by TCP Window Size when we want to fully utilize bandwidth from far away servers?

Question: According to this website, as soon as round-trip time is increased, we lose a bit of our real-time capacity throughput to distant servers using default TCP Window size of 64KB.
My network bandwidth is 240mb/60mb down/up. I live in a third-world country where all CDN servers available is 2000-4000km away from me, and my round-trip time to the closest CDN server is 82ms which means my maximum attainable speed due to distance is just around ~6Mbit/s assuming the server is using default 64KB TCP window size.
I understand that opening multi download streams to certain server can help achieve max bandwidth, but sadly even with having simultaneous 32 streams at once, my download speed is still not able to reach max potential speed to the distant server.
So what can I do in this case to achieve full speeds to those servers assuming no local server is available?
Answer: TCP uses window size and it's built-in ramp-up process, and increasing the window size is the first step to send bigger packets on the same path and thus have bigger and more packets "on-the-wire" and not having to wait for them to be received and then acknowledged. Another way to not have to worry about the ramp-up and other TCP mechanisms is to tunnel your traffic over a more effective protocol like UDP (as long as you don't suffer from transmission errors like drops etc), and therefor optimize the traffic by using a tunnel that is already running "optimally" with full performance and no handshaking needed.
In Linux you can increase the memory for the send buffers, start by looking at net.core.rmem_max/wmem. It could be worth to look at other guides around performance optimisation, if you are indeed running Linux: Sane value for net.ipv4.tcp_max_syn_backlog in sysctl.conf or search for "tune linux for high latency connections".
I don't have much experience with windows, so if that is what you are using then you are on your own, but I assume there are loads of information regarding the network stack optimisation there as well, I just can't point to them.
Comment: *send bigger packets*  Just be really careful using jumbo packets if you don't control the entire network path. [**IP Fragmentation Considered Fragile**](https://tools.ietf.org/id/draft-ietf-intarea-frag-fragile-14.html)
Answer: The default TCP Window Size maximum is 64 kilobytes. However, it was realised long time ago that it is insufficient for today's networking requirements.
Therefore TCP Window Scaling was invented and documented in RFC 1323. It specifies a scaling factor starting from 1 and ending up to 16384. This means that maximum effective TCP Window Size can be 16384 * 65535 bytes = 1,073,725,440 bytes, that is, one gigabyte.
The actual window scaling factor is determined in the TCP handshake, and the scaling factor is used through the connection.
You can use WireShark to examine what is the true TCP Window Size in your TCP connections.


Drupal Commerce add multiple products to cart at once with different attribute values

Question: I'm developing a shop based on Drupal Commerce which sells customizable objects.
I'd like to be able to order t-shirts of a certain type in different colors an sizes (like 5 orange ones size XS, 10 blue ones size L...).
This would normally be done by going to the product page, selecting "orange" as the color, "XS" as the size, adding it to the cart, then going back to the product page...but this is too complicated.
So I'm wondering what is the cleanest approach to achieve this.
Here is an example of the result I would like to obtain (choose a color, then a size, then a quantity, do it as many times as you need, then only click add to cart) :
http://www.objetrama.fr/tee-shirt-personnalise-femme-melrose-150-gr-m.html
I think this could be done by finding a way to send multiple add to cart requests from the same page using ajax (tried this approach with not much success).
Another solution would be to create a custom add to cart function which accepts multiple products with different attribute values.
Answer: Since your not sending a single SKU, you could just overwrite the validate and submit handler for the add to cart form and then, using the existing validate and submit handlers as a blueprint, write your own logic to add multiple products. You'll want to make sure you create line-items for each of the variants your adding to the cart so that pricing is calculated properly, but it should be a fairly straightforward process.


What is done to used balls in cricket

Question: What is done to worn out balls? Are they recycled, reused or do they end up in the landfill?
Answer: Cricket balls when they have been used in matches are generally kept by teams to be used as spare balls should the ball need to be changed as it has been damaged or lost.
If they are not suitable for this or if enough spares are around players and coaches will keep them for practice use.
Once they are no good at all even for practice, I have seen a number of uses from knocking in bats, dogs toys etc.  They would normally be thrown in the ordinary rubbish as I am not aware of anyone that could recycle a ball.
Having said that I've never thrown a ball away and I have played for 5 years and umpired for 20.

What is done to used balls in cricket


Find key in array is not finding the text while it is there

Question: I have an large array. I need to find the needle of a specific text.
Therefore I use:
$afmeting = array_search('extmax', $lines);

When I echo $afmeting  there is nothing there. But when I use print_r on the array I see it is there (needle 41). So what might be wrong?
Array ( [0] => 0 [1] => section [2] => 2 [3] => header [4] => 9 [5] => acadver [6] => 1 [7] => ac1027 [8] => 9 [9] => acadmaintver [10] => 70 [11] => 105 [12] => 9 [13] => dwgcodepage [14] => 3 [15] => ansi_1252 [16] => 9 [17] => requiredversions [18] => 160 [19] => 0 [20] => 9 [21] => lastsavedby [22] => 1 [23] => user [24] => 9 [25] => insbase [26] => 10 [27] => 0 [28] => 20 [29] => 0 [30] => 30 [31] => 0 [32] => 9 [33] => extmin [34] => 10 [35] => 0 [36] => 20 [37] => 0 [38] => 30 [39] => 0 [40] => 9 [41] => extmax [42] => 10 [43] => 260 [44] => 20 [45] => 150 [46] => 30 [47] => 0 [48] => 9 [49] => limmin [50] => 10 [51] => -26 [52] => 20 [53] => -15 [54] => 9 [55] => limmax [56] => 10 [57] => 286 [58] => 20 [59] => 165 [60] => 9 [61] => orthomode [62] => 70 [63] => 0 [64] => 9 [65] => regenmode [66] => 70 [67] => 1 [68] => 9 [69] => fillmode [70] => 70 [71] => 1 [72] => 9 [73] => qtextmode [74] => 70 [75] => 0 [76] => 9 [77] => mirrtext [78] => 70 [79] => 1 [80] => 9 [81] => ltscale [82] => 40 [83] => 1 [84] => 9 [85] => attmode [86] => 70 [87] => 1 [88] => 9 [89] => textsize [90] => 40 [91] => 0.2 [92] => 9 [93] => tracewid [94] => 40 [95] => 05 [96] => 9)

print_r gives: [41] => extmax
var_dump gives: [41]=> string(8) "extmax "
EDIT after alle tips and tricks:
Thank you all for contributing, so when I use this code all should be ok?
$afmeting = array_search('string(8) "extmax "', $lines, true);

But still no value when I echo $afmeting.
Comment: Please copy and paste the array. Don't attach images as we can't use them
Comment: Use `var_dump` to see more information of your array, `print_r` can be misleading.
Comment: The *needle* is generally the term used for the subject to search (`'extmax'`). The `41` thing here, is generally called the *key*.
Comment: So two problems perhaps: your value actually *isn't* `"extmax"` but `"extmax "` (in fact, `string(8) "extmax "` says there's one other hidden character in there for a total of `8` characters), and potentially it'll match the numbers first due to type juggling (see duplicate).
Comment: @Muiter, a lesson for the future, try to paste the output of the array in one row using *echo "" just before the statement. It's not really helpful to read a extensively big array in one line like that.
Comment: Again, `var_dump` tells you that the string is 8 characters long, which obviously doesn't work for either "extmax" nor "extmax ". There's some other hidden character in there. Debug your string. Perhaps look at its raw bytes: `echo bin2hex($lines[41])`.
Comment: No, you're don't search for `'string(8) "extmax "'`. Your string isn't `'string(8) "extmax "'`. That is merely the debug output of `var_dump` telling you that the value is a `string` with `(8)` characters and the value `extmax `.
Comment: Thank you for explaing this @decese.
When I use `extmax` or `extmax ` I still see no result ?
Answer: $array=array(0=>'0',1=>'section',3=>'header',4=>'extmax');

$afmeting = array_search('extmax', $array);

echo $afmeting;

The error is happening because of your "int" records in the array. If you mark all your array values as string, you will get your array key result. The above code will return you the array key 4. Instead if 0 was an int value it would not return the array key that your needle is located.
A solution to this is after you get your array you use array_map function to convert all your array field to string like below:
$array=array(0=>0,1=>'section',3=>'header',4=>'extmax');

$array = array_map('strval', $array);

$afmeting = array_search('extmax', $array);

echo $afmeting;

This will provide you with the right key.
Edit
Another solution is to use parameter $strict of array_search and set it to true
$array=array(0=>0,1=>'section',3=>'header',4=>'extmax');

$afmeting = array_search('extmax', $array, true);

echo $afmeting;

This will also provide you with the right array key.
More about array_search function you can find here!!!
Comment: The much easier solution is to use `$strict` search mode.
Comment: PHP doesn't have named arguments. `$strict=true` is nonsense and/or doesn't do what you think it does. Just do `array_search('extmax', $array, true)`.
Comment: You are right. I will also add it as a third improved solution. Thanks for mentioning
Comment: Didn't know that i was always using strict parameter like this. Edited my answer and will look further into this. Until now everytime i used it like $strict=true it worked fine for me but if you mention that it's wrong i will investigate on that. Thanks for pointing out.


Setting media playback info in MacOs not working

Question: I'm a newbie in ObjC and MacOs development.
My final goal is understand how setting playback info works from ObjC to try to implement that later on Rust (using generated ObjC runtime bindings).
So right now I'm trying to write small piece of code on ObjC that would set playback info (without actually playing anything).
I have found https://github.com/MarshallOfSound/electron-media-service/blob/master/src/darwin/service.mm and used it as a base.
Here's code I have right now:
<code>#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import <objc/runtime.h>
#include "MediaPlayer/MPNowPlayingInfoCenter.h"
#include "MediaPlayer/MPRemoteCommandCenter.h"
#include "MediaPlayer/MPRemoteCommand.h"
#include "MediaPlayer/MPMediaItem.h"
#include "MediaPlayer/MPRemoteCommandEvent.h"

@interface NativeMediaController : NSObject { }
@end

@implementation NativeMediaController
- (MPRemoteCommandHandlerStatus)remotePlay {
    NSLog(@"Play");
    return MPRemoteCommandHandlerStatusSuccess;
  }
- (MPRemoteCommandHandlerStatus)remotePause {
    NSLog(@"Pause");
    return MPRemoteCommandHandlerStatusSuccess;
  }
- (MPRemoteCommandHandlerStatus)remoteTogglePlayPause {
    NSLog(@"PlayPause");
    return MPRemoteCommandHandlerStatusSuccess;
  }
- (MPRemoteCommandHandlerStatus)remoteNext {
    NSLog(@"Next");
    return MPRemoteCommandHandlerStatusSuccess;
  }
- (MPRemoteCommandHandlerStatus)remotePrev {
    NSLog(@"Previous");
    return MPRemoteCommandHandlerStatusSuccess;
  }

- (MPRemoteCommandHandlerStatus)remoteChangePlaybackPosition:(MPChangePlaybackPositionCommandEvent*)event {
    NSLog(@"ChangePlaybackPosition");
  return MPRemoteCommandHandlerStatusSuccess;
}

- (MPRemoteCommandHandlerStatus)move:(MPChangePlaybackPositionCommandEvent*)event {
    NSLog(@"Move");
  return MPRemoteCommandHandlerStatusSuccess;
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        NativeMediaController* controller = [[NativeMediaController alloc] init];

        MPRemoteCommandCenter *remoteCommandCenter = [MPRemoteCommandCenter sharedCommandCenter];
        [remoteCommandCenter playCommand].enabled = true;
        [remoteCommandCenter pauseCommand].enabled = true;
        [remoteCommandCenter togglePlayPauseCommand].enabled = true;
        [remoteCommandCenter changePlaybackPositionCommand].enabled = true;
        [remoteCommandCenter nextTrackCommand].enabled = true;
        [remoteCommandCenter previousTrackCommand].enabled = true;

        [[remoteCommandCenter playCommand] addTarget:controller action:@selector(remotePlay)];
        [[remoteCommandCenter pauseCommand] addTarget:controller action:@selector(remotePause)];
        [[remoteCommandCenter togglePlayPauseCommand] addTarget:controller action:@selector(remoteTogglePlayPause)];
        [[remoteCommandCenter changePlaybackPositionCommand] addTarget:controller action:@selector(remoteChangePlaybackPosition:)];
        [[remoteCommandCenter nextTrackCommand] addTarget:controller action:@selector(remoteNext)];
        [[remoteCommandCenter previousTrackCommand] addTarget:controller action:@selector(remotePrev)];

        NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
        [songInfo setObject:[NSString stringWithUTF8String:"Test title"] forKey:MPMediaItemPropertyTitle];
        [songInfo setObject:[NSString stringWithUTF8String:"Test artist"] forKey:MPMediaItemPropertyArtist];
        [songInfo setObject:[NSString stringWithUTF8String:"Test albumtitle"] forKey:MPMediaItemPropertyAlbumTitle];
        [songInfo setObject:[NSNumber numberWithFloat:60.0] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
        [songInfo setObject:[NSNumber numberWithFloat:360.0] forKey:MPMediaItemPropertyPlaybackDuration];
        [songInfo setObject:[NSNumber numberWithFloat:112233] forKey:MPMediaItemPropertyPersistentID];

        [MPNowPlayingInfoCenter defaultCenter].playbackState = MPNowPlayingPlaybackStatePlaying;
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
        NSLog(@"End!");

        char input[50] = {0};
        printf("Enter anything to quit: ");
        scanf("%s", input);
    }
    return 0;
}
</code>
When this code is executed I see no effect in MacOs playing info widget.
Unfortunately right now I have no idea how to debug this or where can I find better ObjC example.
Answer: Finally, I found the reason that caused my problem playing with Apple Swift example.
There're two requirements to show playback widget (i didn't find them documented anywhere) that have been missing:

You should register a callback for at least one action (play, pause)
You should build your application as an App, not as Console. If your program is not shown in the dock as a running app - the playback widget wouldn't work.
Comment: @Felipe jFYI https://github.com/NovusTheory/xosms have just released 0.3.0 version with merged MacOS support, so maybe it could be an option for you now.

But this project is still not production ready and could have memory leakage at least on MacOS.
Comment: I'm trying to find a replacement for the `electron-media-service` module, one that works with code 13.2 (the one used by Github runners). Any ideas?
Comment: @Felipe Unfortunately, I don't know.

I know that NovusTheory started xosms project (https://github.com/NovusTheory/xosms) some time ago to create new elctron library for integration with media system on 3 OS (Win, Linux, MacOS).

I even made an PR (I'm pretty bad at Rust so my code is ugly and not production ready) to add MacOS support https://github.com/NovusTheory/xosms/pull/11

But I don't know if it works with Electron 13.2 . I also should say that this project not activeyly maintained now and should be considered as PoC.


How to make changes in HTML code and make them show up on site

Question: I am working on a Drupal 7 site that is being manged via Github.
I am trying to change the HTML code on one page. The HTML that I am changing is in the [appname]/sites/all/themes/[app] folder. The HTML in this file is identical to what is on the page if I were to go to the [siteurl]/user/login then navigate to the page and press edit. However when I change the HTML on my local branch and push it up to github and then deploy it using heroku it doesn't actually change the page.
My question is how can I change to way this page is displayed in code instead of changing the page on the drupal website itself.
Comment: I don't follow.
Comment: Sorry definitely my fault. The problem I am having is all the HTML for the website is saved in the SQL databse and I am wondering how I can make my changes to the HTML actually overwrite the SQL DB. Does that make more sense if so I will update my original question.
Comment: You shouldn't be saving all your HTML to SQL. Exactly because this does not allow your code to be version controlled. You need to use Drupal theme's template files and/or preprocess functions to add HTML markup to your pages/nodes.
Comment: Where are the template files saved in the drupal directory. Sorry I just was given this site and I'm brand new to Drupal.
Comment: For D7 is in `/sites/all/themes/YOUR_THEME/templates` folder
Comment: @NoSssweat all I see in this folder are randomly named files with the extension .tpl.php They don't have any HTML how am I supposed to edit these to change my HTML?
Comment: `They don't have any HTML` I highly doubt that. Look carefully at html.tpl.php, page.tpl.php and node.tpl.php
Answer: Look into using the Features module. This way, you can convert any configurations that are stored in the database to code, push them up to the repository, and then pull and revert all the features on your test and production site. You can add template work as a custom feature as well. You should stray away from editing code in Drupal and lean toward creating custom themes, modules and features. I would be no where without this module.


Level curves of powers of a sphere

Question: If we have $f(r) = r^n$, where $r^n = (x^2+y^2+z^2)^{n/2}$, and one wishes to examine the level curves of $f(r)$, namely $f(r) = k$ for some real number $k$, then one might proceed as follows: there would be two cases - (i) take $n>0$ and (ii) $n<0$.
Now, for case (i), taking $n=1$, we'll have the upper part of a sphere in 3-space of radius $\sqrt{k}$. Taking $n=2$, we'll obtain a whole sphere of radius $\sqrt{k}$. But what about taking $n > 2$? That's where I'm getting lost. What kind of a surface are we going to get?
For case (ii), it becomes even more complicated. For example, for $n=-2$, we'll have something like a "reversed sphere".
The question is that we can actually view these surfaces in two ways:
(1) For example, for $n=5$, we can arrive at $x^2+y^2+z^2=k^{2/5}$. For $n=-2$, we can arrive at $x^2+y^2+z^2=\frac{1}{k}$, and both are just spheres in 3-space.
(2) We can expand (for $n=5$) the expression $(x^2 + y^2 + z^2)^{5/2}= k$ and get a very long expression with powers of 4 and less.
Which approach is "more correct" - (1) or (2)?
Comment: As long as you agree that for real numbers, even roots denote positive values, the two are exactly equivalent (and therefore both are correct).
Answer: $\newcommand{\Reals}{\mathbf{R}}$If $n$ is a positive real number and $f_{n}:\Reals^{3} \to \Reals$ is defined by
$$
f_{n}(x, y, z) = (x^{2} + y^{2} + z^{2})^{n/2},
\tag{1}
$$
then the level sets of $f_{n}$ are spheres centered at the origin, independently of $n$. (The level set at "height" $0$ consists of the origin alone, but may be viewed as a sphere of radius $0$.)
Specifically, if $k \geq 0$, the set
\begin{align*}
f_{n}^{-1}(\{k\})
  &= \{(x, y, z) \in \Reals^{3} : f(x, y, z) = k\} \\
  &= \{(x, y, z) \in \Reals^{3} : x^{2} + y^{2} + z^{2} = k^{2/n}\}
\end{align*}
is the sphere of radius $k^{1/n}$ centered at the origin.
If $n < 0$, the formula (1) defines a function on "punctured" $\Reals^{3}$, from which the origin has been removed, but the level set analysis is the same: If $k > 0$, the set $f_{n}^{-1}(\{k\})$ is the sphere of radius $k^{1/n}$.
The underlying point of confusion in comparing Questions 1 and 2 may stem from a misconception. In fact, the expression $(x^{2} + y^{2} + z^{2})^{n/2}$ is not a polynomial in $(x, y, z)$ unless $n$ is a non-negative even integer.

As a general matter, if $u$ is a real-valued function on $\Reals^{3}$, such as $u(x, y, z) = r^{2} = x^{2} + y^{2} + z^{2}$, and if $f$ is a real-valued function of one variable, such as $f(u) = u^{n/2}$, then:

Every level set of $f \circ u:\Reals^{3} \to \Reals$ is a union of level sets of $u$.
If $f$ is monotone, then each level set of $f \circ u$ is a level set of $u$.
Comment: Awesome. Thanks

Level curves of powers of a sphere


how do I reverseproxy the hostname of a subdomain to a different domainname?

Question: I want to reverseproxy a subdomain to another domainname with the same hostname.
Example:
fitzefatze.sourcedomain.com should get the content of:
fitzefatze.targetdomain.com
This should be dynamic, so that every hostname will be translated to the target domain name.
I guess this could be done with the ProxyPass directive but I don't know how to get the host name for the target:
something like this

    ServerName *.sourcedomain.com
ProxyRequests Off
<Proxy *>
    AddDefaultCharset off
    Order deny,allow
    Allow from all #
</Proxy>

ProxyPass / $1.targetserver.com

Answer: There's the ProxyPassMatch directive, but it does specify the following restriction:

The URL argument must be parsable as a URL before regexp substitutions (as well as after). This limits the matches you can use. For instance, if we had used
ProxyPassMatch ^(/.*.gif)$ http://backend.example.com:8000$1
in our previous example, it would fail with a syntax error at server startup. This is a bug (PR 46665 in the ASF bugzilla), and the workaround is to reformulate the match:
ProxyPassMatch ^/(.*.gif)$ http://backend.example.com:8000/$1

I don't know if it will accept http://$1.targetserver.com as a valid URL before substitution -- try it out and let us know!
As mentioned by Shane, you could also use mod_rewrite, but you should be aware that the proxying done by mod_rewrite does not use connection pooling -- each new request will create a new proxy connection on the fly. Therefore you will not be able to benefit from the persistent connection pooling done by ProxyPass, nor will you able to fine-tune its behaviour with the per-connection-pool options that ProxyPass provides (keepalive, timeout, connectiontimeout, retry, min/max, etc.).
Note that there doesn't appear to be a matching ProxyPassReverseMatch directive for either alternative.
Comment: Excellent first post. Keep up the good work!
Answer: To do this, you'll need to use mod_rewrite..
RewriteCond %{HTTP_HOST} ^(.*)\.sourcedomain\.com$
RewriteRule ^/(.*)$ http://%1.targetdomain.com/$1 [P,L]

..and keep in mind, ProxyPassReverse won't work here so any 30x response will not be translated.


writing Cosines using De Moivre's formula

Question: Given the question:

Use De Moivre's formula to find a formula for $\cos(3x)$ and $\cos(4x)$ in terms of $\cos(x)$ and $\sin(x)$. Then use the identity $\cos^2(x) + \sin^2(x) = 1$ to express these formulas only in terms of $\cos(x)$.

I started out by rewriting $\cos(3x)$:
$\cos(3x)$+$i \sin(3x)$=($\cos(x)$+$i \sin(x)$)$^3$
This could then be written into
$\cos(3x) = \cos^3(3x)-3 \cos(x) \sin^2(x)$
or
$\sin(3x) = \cos^2(x) \sin(x)- \sin^3(x)$
Then to use the identity I would substitute $1-\cos^2(x)$ for the $\sin^2(x)$
and in the second I would substitute $\sin(x)$ for $\sqrt{1 - cos(x)}$ right and would need to separate the $\sin^3(x)$ into $\sin^2(x) * \sin(x)$ and substitute from there. I'm a lot less confident about the second equation substitution. Would this be the right way to go about doing this problem?
Comment: So, you want to express $\sin(3x)$ also in terms of $\cos(x)$ only? Your original question only asks for $\cos(3x)$ and $\cos(4x)$ to be expressed in such a fashion. The method is right, anyway.
Comment: I believe so since in the second part formulas was plural so it seemed to refer to both the formulas in terms of cos(x) and the sin(x) one. Thanks for the answer
Comment: You should not hope to express $\sin(nx)$ in terms of cosines, 'cause the sine function is odd and any polynomial in cosine will be even.
Answer: $${ \left( \cos { x } +i\sin { x }  \right)  }^{ 3 }=\cos { \left( 3x \right) +i\sin { \left( 3x \right)  }  } \\ \cos ^{ 3 }{ x } +3i\cos ^{ 2 }{ x\sin { x } -3\cos { x\sin ^{ 2 }{ x } -i\sin ^{ 3 }{ x } = }  } \cos { \left( 3x \right) +i\sin { \left( 3x \right)  }  } \\ \\ \cos { \left( 3x \right) =\cos ^{ 3 }{ x } -3\cos { x } \sin ^{ 2 }{ x } =\cos ^{ 3 }{ x } -3\cos { x } \left( 1-\cos ^{ 2 }{ x }  \right) =4\cos ^{ 3 }{ x-3\cos { x }  }  } \\ \sin { \left( 3x \right) =3\cos ^{ 2 }{ x } \sin { x } -\sin ^{ 3 }{ x }  } =3\left( 1-\sin ^{ 2 }{ x }  \right) \sin { x } -\sin ^{ 3 }{ x } =3\sin { x } -4\sin ^{ 3 }{ x } \\ $$
Comment: I got the same thing for the cos(3x) written only in terms of cos(x)
but it also wanted the sin(3x) one in terms of cos(x) only, and with that I'm not sure if I can take the square root of a negative to find what sin(x) is equal too. Thank you
Answer: You seem to have misunderstood what is meant by "formulas," based on your approach and comments. That said, the problem given to you is poorly phrased (perhaps due to a typo), so this is understandable. The problem should read as follows (with emphasis to make the adjustment clear):

Use DeMoivre's formula to find formulas for $\cos(3x)$ and $\cos(4x)$ in terms of $\cos(x)$ and $\sin(x).$ Then use the identity $\cos^2(x)+\sin^2(x)=1$ to express these formulas only in terms of $\cos(x).$

Your approach is just right for finding $\cos(3x).$ Unfortunately, without more information, it is impossible to unambiguously define $\sin(3x)$ in terms of $\cos(x)$ only, since $$\sqrt{1-\cos^2(x)}=\sqrt{\sin^2(x)}=\left|\sin(x)\right|,$$ so your substitution $\sin(x)=\sqrt{1-\cos^2(x)}$ needn't be correct. Fortunately, you aren't being asked to do such a thing. Rather, it remains only to find a formula for $\cos(4x)$ in terms of $\cos(x)$ and $\sin(x),$ then use $\cos^2(x)+\sin^2(x)=1$ to express the found formula only in terms of $\cos(x).$


What is the sum of the following series

Question: Is there any procedure or formula to calculate the sum?
$$\sum\limits_{n=1}^{\infty} n^{\pi}$$
Comment: That looks divergent to me
Comment: It sums up to infinity
Answer: You can certainly do an analytic comtinuation of the Riemann zeta function to an argument of $-\pi$.  People often do that with the argument $-1$ and claim that $1+2+3+4+...=-1/{12}$.  Formulas with which to do that are given in https://en.m.wikipedia.org/wiki/Riemann_zeta_function, specifically the Representations section.
BUT ...
Do not forget that the zeta function is defined by the familiar sum-of-powers formula only if that sum converges.  You can get a number from the representations alluded to above and call it $\zeta(-\pi)$, but that does not  mean you can call it the sum of a divergent series.
Comment: Good job mentioning both sides of the coin.
Answer: for each $N>0$,
$S_N=\sum_{n=1}^N n^\pi \geq\sum_{k=1}^N 1 \geq N$.
when $N \to +\infty$,
$S_N $ goes also to $+\infty$.

What is the sum of the following series


Find the values of $a\in \mathbb{Z}[i]$ such that $(2,1)$ and $(2+i,a)$ form a basis of $\mathbb{Z}[i]^2$.

Question: I'm trying to solve an exercise which asks me to determine for what values of $a\in \mathbb{Z}[i]$ $(2,1)$ and $(2+i,a)$ form a basis of $\mathbb{Z}[i]^2$ (where we're considering $\mathbb{Z}[i]^2$ as a module over $\mathbb{Z}[i]$).
I see that someone has asked the same question before:
For what values of $a\in \mathbb{Z}[i]$ do $(2,1)$ and $(2+i,a)$ form a basis of $\mathbb{Z}[i]^2$?
but this hasn't helped me. The answers given here rely on the fact that  $(2,1),(2+i,a)$ form a basis if and only if the matrix
$$\begin{pmatrix} 2 & 2+i \\ 1 & a \end{pmatrix}$$
has unit determinant in $\mathbb{Z}[i]$.
I've never seen this result (or anything of the sort before) and have no idea how I'd go about proving it.
Does anyone know of an alternative way to do this, or even the name of the result if it's a standard one or just some idea how you'd go about proving it?
I'd really appreciate any help you could offer.
Answer: The result you mention is not a deep one. Write down what it means to have a basis as an equation in matrix form and take an inverse. You'll see immediately where the condition of unit determinant comes from.
Answer: Left multiplication by the matrix $A := \begin{pmatrix} 2 & 2+i \\ 1 & a \end{pmatrix}$ defines a $\mathbb{Z}[i]$-linear map $\varphi: \mathbb{Z}[i]^2 \to \mathbb{Z}[i]^2$ that sends the standard basis $\pmatrix{ 1\\ 0}, \pmatrix{ 0\\ 1}$ to $\pmatrix{ 2\\ 1}, \pmatrix{ 2+i\\ a}$. So the vectors $\pmatrix{ 2\\ 1}, \pmatrix{ 2+i\\ a}$ form a basis iff $\varphi$ is invertible iff $A$ is invertible iff $\det(A)$ is a unit in $\mathbb{Z}[i]$. (This last implication can be proved using the standard cofactor formula for the inverse of a matrix.)


Angular 8 mat video player problem with progress bar

Question: i have problem with mat-video module into my project.
I'm trying to display a video and that works correct but a video progress bar takes 20% of full video width and i can't set full width.
Code:
HTML:
<mat-video #vid [ngClass]="ngclass" [src]="src" [title]="title" [autoplay]="autoplay" [preload]="preload"
  [loop]="loop" [fullscreen]="fullscreen" [download]="download" [quality]="quality" [keyboard]="keyboard"
  [color]="color" [spinner]="spinner" [poster]="poster" [overlay]="overlay" [(muted)]="muted"
  [showFrameByFrame]="showFrameByFrame" [(time)]="currentTime">
</mat-video>

TS:
ngclass = 'mat-video-responsive';
src = '../assets/video/nature.mp4';
title = 'Some title';
width = 600;
height = 337.5;
currentTime = 0;
autoplay = false;
preload = true;
loop = false;
quality = true;
download = false;
fullscreen = true;
showFrameByFrame = false;
keyboard = true;
color = 'primary';
spinner = 'spin';
poster = '';
overlay = null;
muted = false;

Effect:

I did everything as in the guide: mat-video npm
Answer: Had the same problem. This solved my problem:
:host::ng-deep .progress{
  background-color: unset !important;
}

:host::ng-deep mat-seek-progress-control{
  width: 100%;
}


Get Ldap server version with java

Question: I found this simple example with java how to connect to LDAP server:
<code>import javax.naming.*;
import javax.naming.directory.*;

import java.util.Hashtable;

/**
 * Demonstrates how to create an initial context to an LDAP server
 * using SSL. For this example to work, JSSE must be installed and
 * configured, and the issuer of the LDAP server's certificate must
 * be in the JSSE trust store.
 *
 * usage: java Ssl
 */
class Ssl {
    public static void main(String[] args) {
        // Set up environment for creating initial context
        Hashtable env = new Hashtable(11);
        env.put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://localhost:636/o=JNDITutorial");

        // Specify SSL
        env.put(Context.SECURITY_PROTOCOL, "ssl");

        // Authenticate as S. User and password "mysecret"
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
        env.put(Context.SECURITY_CREDENTIALS, "mysecret");

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);

            System.out.println(ctx.lookup("ou=NewHires"));

            // ... do something useful with ctx

            // Close the context when we're done
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
}
</code>
Is there any way to get the LDAP server and version when I'm connected?
Answer: Try looking at http://ldapwiki.willeke.com/wiki/Determine%20LDAP%20Server%20Vendor where we provide some methods we have found to generally work. There is no single method that works on all LDAP server implementations.
Also LDAP Version is too vague. Do you want: The LDAPSupported Version?  or The vendorVersion of LDAP?
Also, some rootDSE entries may not be available unless you are bound with an account with proper permissions.
Answer: Get the attributes of the rootDSE. Depending on the server, this information may be in there.
Comment: Your provider URL contains the rootDSE, so in this case just lookup("") from your initial context. That returns a DirContext for the rootDSE. Get the attributes from that. You'll find all sorts of interesting stuff there.

Get Ldap server version with java


Any alternatives to JSPs for open-id authentication in java Spring web applications?

Question: I am interested in making some sort of HTML page that displays the name of a user that was authetnicated through some openid authentication mechanism. I noticed the example in many places I see uses something like:
"j_spring_openid_security_check"
Ive read that JSPs are not recommended for web applications as JSFs are much more popular and I would like to if possible stick with standard HTML. Is there some way to be able to authenticate some other means by maybe calling some sort of service through some GET or POST to get the identity of the user so I wouldnt have to rely on JSPs for my web application?
Any examples/guides/approaches would be great.
Comment: JSPs will be converted to HTML by webserver. So at the end It is HTML only browser can understand. If you want to stick with HTML, it should work. HTML and Webserver both understands HTTP calls. So it should work.
Answer: You can use a multitude of technologies as views in Spring MVC, as mentioned in the documentation. If you're really set against JSPs, you could use Velocity or Freemarker templates, but there are plenty of successful enterprise applications that use JSPs as their view technologies: the Amazon Web Services forums being but one example.
Answer: This is example from my project of clean html text with username/password and openid login forms.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

    <form style="border: 1px solid red" action="../j_spring_security_check" method="post">

            Username <input id="j_username" name="j_username" type="text" />

            Password <input id="j_password" name="j_password" type="password" />

        <input type="submit" value="Login" />
    </form>
    <form action="../j_spring_openid_security_check" method="post">
        For Google users: <input name="openid_identifier" type="hidden" value="https://www.google.com/accounts/o8/id" /> <input type="submit" value="Sign with Google" />
    </form>

You have to change code
 <action="../j_spring_security_check">