Why are 7 non-compulsory tournaments included in Marin Cilic's ATP ranking?

Question: I understand that only 18 tournaments (19 if qualified for ATP Finals) are considered for ATP rankings of which 4 grand slams and 8 masters (excluding Monte Carlo) are compulsory. If a player fulfills the commitment of 4 ATP 500 (counting Monte Carlo if he plays), his best 6 results from other tournaments are counted.
But currently (16th March 2018), I see 7 tournaments (apart from compulsory tournaments) are counted in Marin Cilic's Rankings. It includes Monte Carlo, 3 ATP 500 and 3 other tournaments. Is it not violating the rule?
His ATP Rankings Breakdown is here. And here is Internet Archive snapshot from March 2018.
Comment: Under some conditions, the commitment can be reduced, see here: [Are Masters 1000 tournaments mandatory for top ranked players?](https://sports.stackexchange.com/q/3372) I'd guess that is is possible that Cilic already had 600 matches at the time.
Answer: I'm not 100% sure, but this could be a case of them using the Monte Carlo Open in place of the Canadian Open, which he pulled out of due to an injury sustained at Wimbledon.


For a discrete topological space $X$, is Perm$(X)$ a topological group as a subspace of product topological space $X^X$?

Question: Let $X$ be a discrete topological space and consider the product space $X^X$ (which is the space of all functions from $X$ to $X$) with product topology. Let $S(X):= \{ f: X \to X : f $ is bijection $\}$ . Then $S(X)$ is a subset of $X^X$ and $S(X)$ forms a group under the operation of function composition. My question is : Under the subspace topology inherited from $X^X$, does $S(X)$ form a topological group ?
Comment: Sorry, I misread your question.
Comment: So $X^X$ has the topology of pointwise convergence.
Comment: What did you try to prove this? The proof is quite straightforward given the fact that the topology is the one of pointwise convergence of nets.
Answer: Yes.
If $X$ is discrete, then the product topology on $X^X$ agrees with the compact-open topology, see Compact open topology on space of continuous maps from a discrete space is a product.
If function spaces are endowed with the compact-open topology, then it is well-known that the composition function $T : B^A \times C^B \to C^A, T(f,g) = g \circ f$ is continuous provided $B$ is locally compact. Discrete spaces are locally compact, so that $T : X^X \times X^X \to X^X$ is continuous, and therefore also the restriction to $S(X)$. Inversion on $S(X)$ can be treated by directly considering the topology of pointwise convergence: If you take a net $(f_\alpha)_{\alpha \in A}$ of bijections converging pointwise to some $f \in S(X)$, then $(f^{-1}_\alpha)$ converges pointwise to $f^{-1}$. This is true because for all $x \in X$ there exists $\alpha_0$ such that $f_\alpha(x) = f(x)$ for $\alpha \ge \alpha_0$ due to discreteness of $X$. Note that $A$ is any directed partially ordered set.
Comment: Can we prove the continuity of composition directly ?
Comment: Yes, this was done in the answer by user87690.
Answer: You can also prove this directly.
First, you should write down what does the continuity of the composition operation mean in your case:
For every neighborhood $W$ of $g ∘ f$ there is a neighborhood $U$ of $f$ and a neighborhood $V$ of $g$ such that $g' ∘ f' ∈ W$ for every $f' ∈ U$ and $g' ∈ V$.
It is enough to consider subbbasic neighborhoods $W$ – those when you prescribe a nontrivial open set at one coordinate $x ∈ X$. Since $X$ is discrete, $\{g(f(x)\}$ is open, so we want to find $U$, $V$ such that $g'(f'(x)) = g(f(x))$ for every $f' ∈ U$, $g' ∈ V$. Do you see how to choose $U$ and $V$?
The situation with the continuity of inverse is similar.
Comment: Sorry but I can't figure out $U$ and $V$. Please elaborate.
Comment: @misao: Its it clear how basic and subbasic open sets product looks? Is it clear what does it mean in out case when $X$ is discrete?
Comment: @misao: The product topology on $X^X$ has as a subbasis all products of $U_x$ where $U_x = X$ except for a single $x_0$ where $U_{x_0} = \lbrace y \rbrace$ for some $y \in X$.


Finding Functions

Question: Let $S=\{1,2,3,4,5\}$. Find the number of functions $f:S→S$ such that $f(f(x))=f(x)$ for all $x∈S$. How do I approach this problem? I have no idea(I kept putting values).
Answer: $f(x)=f(f(x))$ implies the range of $f$ is the set of elements $x$ such that $x=f(x)$.
To count the functions first select the range (The elements in $x$ so that $f(x)=x$).
Once you have done that you can map the other elements to any of the fixed points.
So when the range has size $i$ there are $\binom{5}{i}$ ways to select the range and then $i^{5-i}$ ways to select where to map the $5-i$ non fixed points.
Hence you want $\sum\limits_{i=1}^5 \binom{5}{i}i^{5-i}=5+80+90+20+1=196$
Answer: Well, say $f(x) = y$. Then you want to find $f$ such that $f(y) = y$. How many functions are there such that $f(y) = y$ for every $y \in S$?
Comment: We want $f(x)=f(f(x))$. Not necessarily $x=f(x)$

Finding Functions


Does bat tampering exist in cricket?

Question: I have been going through this post when I stumbled across this doubt.
Is there anything like bat tampering in cricket?
I did a quick search through the Lords Laws of cricket, however, I haven't found any.
If there exists something like tampering related to the bat, then is there an official name for that?
Answer: Essentially, no. So long as the bat conforms to Law 6, The bat, Appendix E, The Bat and any playing conditions under which the match is being played, "anything goes" (although the Laws are restrictive in what is allowed). In general, bats are set up to be as good as they can be at hitting the ball, so there would be no advantage to be gained from "tampering" with the bat.
One thing a batsman might want to do is to make the bat wider or longer, but it's hard to see how that could happen while they're at the crease without it being really obvious.
Comment: @TrueDub while some people may use the word "tampering", the Laws do not, nor do they suggest any explicit rule against the idea of it. Either a bat is legal or it is not - an illegal bat may not be used, and doing so probably contravenes Law 42 of nothing else.
Comment: Would you not consider that doing something to your bat that's against the laws (e.g. adding metallic tape) would be termed tampering? I appreciate we're talking about semantics here, but people can and do alter their bat's condition in an effort to make it perform better.
Comment: @Nij, as I said, semantics.
Comment: @TrueDub I don't think this is merely semantic. There are at least two ways in which "bat tampering in cricket" - a *de jure* phrase and/or action and/or offence, and a *de facto* action and/or committing the offence as described. Both of these things can be entirely independent of each other (laws against something that never happens, things that happen on which rules are silent). It may pay to clarify more exactly which one you mean, since this answerer as well as myself are apparently focused on the law aspects and you seem to want information only about the fact or absence of tampering.

Does bat tampering exist in cricket?


How to make a guitar backing track?

Question: I've read on many topics that it is very hard to make backing tracks for guitar. The only way to do it is to get access to the master tracks. Once it is mixed to the mp3 file, it is usually impossible to separate the guitar part.
But on Youtube, when I pratice a song, there are a lot of backing tracks available with pretty good quality (for example: Enter Sandman, The Loner). Do they really have access to the masters track? It is hard to believe.
If not, is it really impossible to make a backing track from the mp3 files?
Comment: For the person who downvoted my question, could you please explain why? I'm very open for the constructive discussion. But it makes me uncomfortable having a downvote without any explaination.
Answer: Some people do have access to MOG files which have all the tracks separated. These people usually work in studios and have access to such files, or pay money, or have the talent to actually create multi-channel and multi-instrument recordings.
There are a couple of good ways to get a backing track. If you just want something to jam to for lead composition or otherwise, then just convert the YouTube feed into mp3 at http://www.youtube-mp3.org/ . I use this all the time for rhythm practice and general jamming. After conversion to mp3, I import into the DAW - Scarlett 18i and Presonus Studio One.
For composition ideas and creating 'mock-up' tunes, I use Band-In-A-Box. This allows me to take a rhythm that closely matches the target rhythm for lyrics composed. From BIAB, I remove the instruments I do not want (rhythm and lead guitar, maybe keyboards), then export that into my DAW setup via WAV file.
For cover material, or practicing new cover songs, I go to http://www.karaoke-version.com/ and get the karaoke version of the cover and remove the guitar part. In that web site, you are able to customize the track, so you essentially get a true backing track of a popular song.
Also, for general past time and jamming, I use Jam Player on the iPad plugged into a Line 6 Amplifi 150. Line 6 finally got most of the bugs worked out, so awesome tool. Also plugged into the same Amplifi is a Trio, which is an awesome tool for jamming.
Finally, for traveling and just to have a portable drum machine, I take an electric guitar, full powered iRig setup, iPad, short cables and combine all that with a BeatBuddy and Looper. Besides the guitar itself, all of this packs into a small size and is great for traveling.
Comment: This comment is slightly off topic but you may have some insight.  I have looked at the BeatBuddy to use as a drum machine when I play without a drummer but the issue I had is that it's a pedal/stompbox style interface - yet to change songs you must turn the dial by hand.  Have you discovered an easier way to control song selection without having to bend over between every song (maybe with the i-pad somehow)?
Comment: True on the beatbuddy. Between each song, having to bend over and change songs in a live situation is a no-go. Nope, I don't know any way around that. However, you can get a beatbuddy feed into your DAW and record the output of the beatbuddy, create a playlist in order, then put a set list of recordings into your iPad (iTunes?).
Comment: I thought about that but as far as I can tell you would then lose control over your drum track.  No start, stop at will or change tempo mid song.  Also if you decide to do the extended version of a song because the audience seems to be really diggin it, pre-recorded will end at the pre-determined time - just like a backing track.  With beat buddy you can end the song early or make it last longer by repeating the last verse and chorus or just keep repeating the final chorus (like if folks get to singing along with "Friends in Low Places").
Answer: I would agree that completely separating the tracks from each other on an mp3 recording is impossible. However that depends on how it was mixed. Older rock and roll recordings (from the 60s and before, usually) often had different instruments completely panned to either the left or right channel (this was called "Big Mono") A good example of this would be The Who's 1971 album Who's Next, where the drums are usually on the right or the left, and the same going for the guitar. It is especially prevalent on jazz recordings of the 50s and 60s, e.g. John Coltrane's Giant Steps. Of course, recording technology advanced quickly and that technique stopped being used in the 70s.
So, assuming what you've got is an mp3 or wav or something similar, then you won't be able to completely separate the parts, unless the track is panned in big mono. There are some programs that help with transcribing and practicing songs, however. Search "music transcription software" and you'll find some tools to help with learning songs, if that's what you're after.

How to make a guitar backing track?


What causes my pipes to disappear in the middle of my Unity game camera?

Question: I have written code to delete the pipes once they are out of the game camera view but for some reason the pipes are disappearing once they reach the center of the camera instead of once they are out of the players view
I have written three scripts so far...
<code>    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UIElements;

    public class PipeScript : MonoBehaviour
    {
        public float moveSpeed;
        public float deadZone = -35;

        // Start is called before the first frame update
        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {
            transform.position = transform.position + (Vector3.left * moveSpeed) * Time.deltaTime;

            if (transform.position.x < deadZone)
            {
                Destroy(gameObject);
            }

        }

    }
</code>
... above is one of the two scripts i have written for the pipe in this script i have the command to destroy the gameobject once it reaches the deadzone. in the next script is for the spawner that spawns the pipes...
<code>    using JetBrains.Annotations;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEditor.Experimental.GraphView;
    using UnityEngine;

    public class PipeSpawnerScript : MonoBehaviour
    {
        public GameObject pipe;
        public float spawnRate;
        private float timer = 0;
        public float heightOffset = 10;

        // Start is called before the first frame update
        void Start()
        {
            spawnPipe();
        }

        // Update is called once per frame
        void Update()
        {
            if (timer < spawnRate )
            {
                timer = timer + Time.deltaTime;
            }
            else
            {
                spawnPipe();
                timer = 0;
            }

        }
        void spawnPipe()
        {
            float lowestPoint = transform.position.y - heightOffset;
            float highestPoint = transform.position.y + heightOffset;

            Instantiate(pipe,new Vector3(transform.position.x,Random.Range(lowestPoint,     highestPoint),0),transform.rotation);
        }
    }
</code>
... these scripts result in the pipe being destroyed in the middle of the game camera instead of out of view I am unsure of what the try next and have searched the internet and cannot find an answer.
I have also tried the onBecameInvisible method and the program wouldnt destroy the gameObject at all.
Comment: if you initially had `public float deadZone = 0;` in your code, but changed it later to `-35;`, the inspector might still have `0` serialized. You can use `...` -> `reset` or just change it in the inspector. This is often overlooked
Answer: I'm not too sure what you want. For future reference, consider stating your purpose when asking questions. Here are the two ideas I have of what I think you need:
I think what you want is occlusion culling. Occlusion culling boosts your performance, and suspends game objects so that they disappear and appear according to player's view.
If you actually DO want to remove the pipes entirely, try the following:
In your script, one of the things you can do is a physics.overlapsphere with a large radius (for distance), and manipulate the arc of the sphere to exclude the player's vision. You can then get all of the gameobjects with a specific tag (for example "pipes"), put them in a list, and destroy them using a foreach() loop.
Hope this helps.


Aggregating risk scores

Question: I have a model which calculates the risk of default on several essentially independent metrics. These are default probabilities between 0 to 1. 1 implying a high risk of default.
Now I wish to combine these scores into a single score. I naively started using an average of all scores but that doesn't give me the desired behavior when one score is very high and the others are low.
i.e. Say the component scores are 0.1,0.1, and 0.999. Essentially I want the aggregate score in this case to be close to 0.999 as well.
What might be a clean functional form to get this sort of behavior? i.e. When individual scores are low an average score is OK but when any one score shoots above a threshold value that score ought to dominate the aggregate.
PS. If someone has an R idiom for this then I am even happier.
Comment: You appear to be describing the *maximum.* However, your question does not supply enough information to determine and objectively support any particular answer. You are essentially asking your readers to guess the results of a modeling exercise in which you relate these metrics to actual default experiences. If you don't have such data, then we're all just guessing. Do you have relevant data? What are their nature?
Comment: @whuber I'll edit my question. No, it is not the maximum because when the individual scores are below a thresh-hold the averaging is the right behavior. It is only above the threshold that I wanted them any high value to swamp the rest. Maybe what I am needing is a functional form that transitions from the average to the maximum smoothly.
Comment: @whuber No I don't want the readers the guess the results of the models. I am only hoping someone can suggest a functional form with these properties.
Comment: They have no basis to suggest a functional form.  Your question is asking readers to make pure guesses.  (There are infinitely many possible such functions.) You need to supply sufficient information to allow people either to determine answers or to be able to explain how you could use that information to find an answer yourself.
Comment: @whuber OK. I will contemplate what else I can provide.
Answer: Just a guess, maybe you can try out something like
$(1 - score)^n = \prod_{i=1}^n{(1 - x_i)}$
Comment: Perfect! I think this works almost exactly like what I had in mind! Thanks!

Aggregating risk scores


How can I schedule in advance an update to a node, to occur at a given time?

Question: In a situation where I know that a specific change to the content of a specific node will need to be made on a specific date and time, is there any way to automate that change so that I do not need to make the change manually specifically at that date and time, but rather can prepare it in advance?
The Scheduler module allows for scheduling publishing and unpublishing nodes, and I am basically looking for some (hopefully lightweight) way to achieve a similar effect to the content of a node.
This is for Drupal 7 (though compatibility with the upcoming Drupal 8 is definitely a plus). Ideally it will also handle the components on Webform nodes (one of the things I want to be able to do is replace the list of options in a "select" component).
Answer: This could be done with a Rules Schedule:

The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

specifically this functionality: Flexible scheduling system that allows scheduling any component / action.
Comment: Okay... that looked promising at first, but unfortunately it has two problems. One, it seems quite heavy-weight for what essentially boils down to changing some text at a given time. Two, and this is something I completely forgot to mention in the question originally (sorry about that): it doesn't seem to handle webforms very nicely at all.
Comment: well, then it sounds like you will need a custom module
Comment: I'll see if anyone else can come up with a good suggestion. (A custom module is certainly an option, but it's definitely not my first option.) Still, have an upvote, because your answer clearly can be coaxed into doing what my question was asking for at the time of your answer.


Replace broken image icon with text

Question: I want to hide or remove the broken image icon whenever it pops up and replace that with text that reads: "Error with image." Right now, I have some jQuery that hides the broke image icon, but I cannot set and show the alt text this way. Do I need to have a replacement image or is there a way to show text whenever a broken image icon is hidden?
This is the jQuery code:

These are the fields in the table that are meant to show the image thumbnails:
<asp:ImageField HeaderText="Line dwg Thumb" DataImageUrlField="LineDrawThumbnail" NullDisplayText="error with image"  ControlStyle-Width="75px" ItemStyle-HorizontalAlign="Center">
 </asp:ImageField>
 <asp:ImageField HeaderText="Profile Thumb" DataImageUrlField="ProfileThumbnail" NullDisplayText="error with image" ControlStyle-Width="75px"  ItemStyle-HorizontalAlign="Center">
  </asp:ImageField>

Important side note: The database table that has the thumbnail images does not have any empty field for Profile Thumbnail or Line Draw Thumbnail--it just so happens that sometimes the thumbnail does not exist yet.
Comment: Why don't you add the property alt="error with image" to the images?
Comment: why can't you use alt?
Comment: If you know that sometimes a thumbnail won't exist, you should set a default image that says so.  Then, override that if the image is there.  You can't rely on any tag automatically displaying correctly on all browsers.
Comment: I've tried using alt text but the broke image icon still displays.
Comment: @SaraDeJaneiro why don't you fix the URLs? Seems like the only decent thing to do.
Comment: Fixing the URLs would take up a lot of time. We're talking a lot of images here. Plus, the images must be supplied by another person, and they have yet to send all the images needed it seems.
Answer: Your script is perfectly fine all you need to do is add text after you hide image

Replace broken image icon with text


Mostrar GIF enquanto página carrega

Question: Preciso que um GIF fique funcionando enquanto a página carrega. Eu já tentei alguns jeitos mas nenhum funcionou.
E que quando página carregar apareça o Concluído!.
Mais ou menos como o acontece neste site.
Comment: Tem o evento onload http://www.w3schools.com/jsref/event_body_onload.asp Ou tenta exibir o código fonte lá e ver como foi implementado.
Comment: Se quiser fazer sem dependências externas: http://pt.stackoverflow.com/questions/66039/como-colocar-uma-gif-antes-de-exibir-a-p%C3%A1gina-do-site/67568#67568
Comment: Também pode pensar em adicionar uma biblioteca de terceiros como pace.js
Comment: http://github.hubspot.com/pace/docs/welcome/
Answer: Na verdade o que acontece nesse site é que ele coloca por cima do conteúdo um DIV que cobre tudo e assim que o conteúdo é carregado (document.load) ele esconde o DIV com um efeito de fadeOut.
Refiz isso no JSFiddle pra ficar mais fácil (apesar que você irá ver melhor o efeito na sua página diretamente).
HTML

CARREGANDO

CSS
body {
    background: #000;
}
#preloader {
    position: absolute;
    left: 0px;
    right: 0px;
    bottom: 0px;
    top: 0px;
    background: #ccc;
}

JavaScript
$(document).ready(function(){

    //Esconde preloader
    $(window).load(function(){
        $('#preloader').fadeOut(1500);//1500 é a duração do efeito (1.5 seg)
    });

});

No lugar no "carregando" é só colocar sua tag  com um GIF que você quiser. Apesar de que já é possível fazer uma animação simples com CSS3 assim você não precisa usar imagem.
Comment: Muito bom, valeu mesmo.

Mostrar GIF enquanto página carrega


How to load into a normal page instead of the (blog-like) front page?

Question: I have my drupal site, loading the  page when I open the site. It is the normal behaviour, but I don't want it.
I have a different HOME page that I want to see when I open my site (instead of the  page with all my articles).
I still have the  page with articles and I have a link NEWS in my menu that points to it, because I want to keep the articles page.
I tried this:
<code>Configuration > Site information > Default front page > (I wrote "home")
</code>
But the NEWS link didn't point to the articles anymore, because it seems that now the page is my HOME page.
So, it loads the HOME page on opening, like I wanted, but now my articles page is not accessible via the NEWS link in the menu.
How can I see my HOME page as default page when entering the site "without" losing access to the page of articles?
Thanks
Answer: it is a bit confusing your question. But I try help you.
First, did you create a view called 'NEWS' (in Structure -> Views)? OK great, make this view accessible by url '/news'. (if not, make this sentence true).
Check if your 'HOME' view is set to < front> (url '/home', same url that you set in Site information page - with '/home') and make it accessible.

Then, edit the 'main content' block (in Structure -> Block Lay out) to only appear in NEWS page.

This is for drupal 8, but seems to be almost the same for drupal 7 (same modules, Block and Views).
PS: Edit your question and add a tag with your drupal version.


Aristarchus and the Moon's distance

Question: I'm trying to plug the number into the equation below, but I'm getting 67 earth radii instead of 60 radii. What am I getting wrong?
http://www.phy6.org/stargaze/Shipprc2.htm

Let $R$ be the radius of that circle and $T$ the time it takes the Moon to go around once, about one month. In that time the Moon covers a distance of $2\pi R$
An eclipse of the Moon occurs when the Moon passes through the shadow of the Earth, on the opposite side from the Sun (therefore, we must be seeing a full Moon). If $r$ is the radius of the Earth, the shadow's width is close to $2r$. Let $t$ be the time it takes the mid-point of the Moon to cross the center of the shadow, about 3 hours (in eclipses of the longest duration, when the Moon crosses the center of the shadow).

Assume the Moon moves around Earth at some constant speed. If it needs time $T$ to cover $2\pi R \approx 6.28R$, and time $t$ to cover $2r$, then
$$6.28 R / 2 r     =     T/t$$
From this Aristarchus obtained: $R/r \approx     60$
Comment: x @user: You're ignoring the word "about" in both places. Those are extremely rough values. With that kind of precision, ending up with rounding errors of about 10% shouldn't surprise anyone.
Comment: Where do you get numbers to plug in for $T$ and $t$?
Comment: The article I linked states that T is one month, and t is 3 hours. Unless I'm not reading it correctly?
Comment: In fact, due to the eccentricity of the Moon's orbit, the duration of an eclipse where the Moon crosses the center of the shadow can be as much as 12% shorter or longer than the average time, depending whether it happens close to apogee or perigee.
Answer: According to this article on Wikipedia, Aristarchus actually got a value of $20$.
You are not alone, however;

A similar procedure was later used by Hipparchus, who estimated the mean distance to the moon as 67 Earth radii, and Ptolemy, who took 59 Earth radii for this value.
Comment: Mmm, according to a paragraph below, it should be 80 Earth radii. Was Archimedes wrong? I need to be sure of the right value for an article I'm writing. Thanks in advance!
Comment: @Unix; if you carry on reading, it explains 'The disagreement of the work with Archimedes seems to be due to its taking an Aristarchus statement that the lunisolar diameter is 1/15 of a "meros" of the zodiac to mean 1/15 of a zodiacal sign (30°), unaware that the Greek word "meros" meant either "portion" or 7°1/2; and 1/15 of the latter amount is 1°/2, in agreement with Archimedes' testimony.'

Aristarchus and the Moon's distance


prevent automatic UILabel font changes after setting the attributedText

Question: I've figured out that if I set an attributed text to an UILabel, the predefined font will be changed to the font of the first character of attributed text. for example:
// the font size is set to 20 in Interface Builder
println(theLabel.font.pointSize);
var styledText = NSMutableAttributedString(string: "$100");
var smallFont = UIFont(name: theLabel.font.fontName, size: theLabel.font.pointSize / 2)!;
styledText.addAttribute(NSFontAttributeName, value: smallFont, range: NSMakeRange(0, 1));
theLabel.attributedText = styledText;
println(theLabel.font.pointSize);
// output:
// 20
// 10

I've no idea if it could be called a bug or not, but it causes problem in some cases.
Can anybody suggest a clean solution to obtain the default font that have set in the Interface Builder?
One solution to reset the font to predefined font is to set the text property of UILabel, because that causes the UILabel to switch to the plain text mode (no attributed text anymore).
theLabel.text = ""; // reset the font
println(theLabel.font.pointSize);
// output:
// 20

Answer: Let say that let myLabel: UILabel have a font size of 20. myLabel should display an attributed text: "foo bar", where "bar" has font size of 30.
If you change the font on myLabel, with the intention to change the font size of "foo" to not be 20, but rather 15 instead, you will notice that this results in your attributedText being messed up.
Inspired by @Majid's findings, if you set the text property before applying the font change. The attributedText stays intact, and now updated with a new "default" font!
func setFont(_ font: UIFont, keepAttributes: Bool = true) {
    // Store attributedText before it gets ruined by font change
    let attributed = attributedText
    if attributed != nil && keepAttributes {
        // This trick enables us to change "default" font for our attributedText.
        text = ""
    }
    // Apply font change
    self.font = font.font
    if keepAttributes {
        // Restore attribute text, now with a new `default` font
        attributedText = attributed
    }
}

Answer: NSMakeRange

Is responsible for choosing which characters
addAttribute

has an effect on. When you set
NSMakeRange(0,1)

it tells every character from the 0th character to the 1st character to be attributed. Which means only the first character can be attributed. Try setting it to
NSMakeRange(0,i)   //or     NSMakeRange(0,1000)

I set the alt. option to 1000 because it is an arbitrarily large number giving a guaranteed font change just in case "i" does not work
p.s. the // symbol refers to a helpful hint or comment the previous developers wrote down.


How to store game level objects in a Swift array?

Question: I want create an array with information of game level objects for my game. But I'm stuck in creating an appropriate array with this information to run this one later in a loop to place all game objects while loading this level.
This is my array:
let level1 =
[
    (
        id: 1,
        position: CGPointMake(0.5, 0.8),
        impulse: CGVectorMake(-40, 0)
    )
]
let level2 =
[
    (
        id: 1,
        position: CGPointMake(0.5, 0.8),
        impulse: CGVectorMake(-40, 0)
    ),
    (
        id: 2,
        position: CGPointMake(0.5, 0.8),
        impulse: CGVectorMake(-40, 0)
    )
]

And this is my load level func:
func loadLevel(levelNumber: Int = 1) {
    var level = [[String:AnyObject]]()

    switch(levelNumber) {
    case 1:
        level = level1 //Cannot assign a value of type '[(id: Int, position: CGPoint, impulse: CGVector)]' to a value of type '[([String: AnyObject])]'
    case 2:
        level = level2 //Cannot assign a value of type '[(id: Int, position: CGPoint, impulse: CGVector)]' to a value of type '[([String: AnyObject])]'
    case 3:
        level = level3 //Cannot assign a value of type '[(id: Int, position: CGPoint, impulse: CGVector)]' to a value of type '[([String: AnyObject])]'
    default:
        level = level1 //Cannot assign a value of type '[(id: Int, position: CGPoint, impulse: CGVector)]' to a value of type '[([String: AnyObject])]'
    }

    for s in level {
        var newShip = Ship(ship: ships[s.id! - 1], position: s.position)
        self.addChild(newShip)
        ship.physicsBody?.applyImpulse(s.impulse)
    }
}

I even do not know if this is a good approach to save/edit level object information.
And when I use:
var level = [id:Int, position:CGPoint, impulse:CGVector]() //Use of unresolved identifier 'id'

Comment: It's very vague. And what is your question?
Comment: @kostek, I added the error messages.
Answer: You have the wrong type for your level variable.  It is not an array of dictionaries.  It is an array of named tuples.  Try declaring level like this:
var level:[(id: Int, position: CGPoint, impulse: CGVector)]

If instead you put all of your levels in 1 big array, you can access each level with an array index and you won't need a big switch statement.  I recommend telling Swift the type of the array when you declare it:
let levels: [[(id: Int, position: CGPoint, impulse: CGVector)]] = [
    // level 1
    [
        (
            id: 1,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        )
    ],
    // level 2
    [
        (
            id: 1,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        ),
        (
            id: 2,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        )
    ]
]

func loadLevel(levelNumber: Int = 1) {
    // Subtract 1 since array indices start at 0.  This will crash with Array
    // index out of range if the level doesn't exist.  Take proper precautions.
    let level = levels[levelNumber - 1]

    for s in level {
        var newShip = Ship(ship: ships[s.id - 1], position: s.position)
        self.addChild(newShip)
        ship.physicsBody?.applyImpulse(s.impulse)
    }
}

Or you can make levels be a dictionary with the level number being the key:
let levels: [Int:[(id: Int, position: CGPoint, impulse: CGVector)]] = [
    // level 1
    1: [
        (
            id: 1,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        )
    ],
    // level 2
    2: [
        (
            id: 1,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        ),
        (
            id: 2,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        )
    ]
]

func loadLevel(levelNumber: Int = 1) {
    // Unwrap the level information.  This will crash if it isn't a valid
    // level number.  Take proper precautions.
    let level = levels[levelNumber]!

    for s in level {
        var newShip = Ship(ship: ships[s.id - 1], position: s.position)
        self.addChild(newShip)
        ship.physicsBody?.applyImpulse(s.impulse)
    }
}

Comment: Edited.  It is an array of named tuples.
Comment: Hehehe yeah - I read first version of answer and thought that might be a good idea to make a function that returns the correct level. Thank you for this great answer!


Override Another module's Template file using my Custom Module (Drupal 7)

Question: I'm willing to change the user-profile-item.tpl.php template provided by the user module.
I've created a new template file. Now my  question is:

Where do I put the new template user-profile-item.tpl.php template
file? I've created a custom module, should I place it right in the
custom module's directory?
Do I need anything to do so that Drupal
picks up my template file instead of the default template file?

PS I got this link did not understand. Sorry I'm a newbie :(
EDIT:
I solved this using preprocessors, I figured out that I can use preprocessors easily without changing template file. I wrote following preprocessor in my module to achieve what I was looking for.
function MYMODULE_preprocess_user_profile(&$vars){
//    dsm($vars); // prints nice debugging information
    $vars['user_profile']['charity_link'] = array(
    '#markup' => l('Add Charity!', 'my/custom/link' . arg(1)),
    '#weight' => 10
    );
}

Comment: Don't forget to write that as answer.
Comment: Duplicate of http://drupal.stackexchange.com/a/53689/6581 which has the cleanest solution as the answer.
Answer: I had to use the following snippet to get it to work. I think it may be due to the way I set up the original template.
<?php
//  unset the original template to set yours.

// Implement hook_theme_registry_alter
function MODULENAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['TEMPLATE_TO_OVERRIDE']['template'] = drupal_get_path('module', 'MODULENAME') . '/TEMPLATE_TO_OVERRIDE';
  $theme_registry['TEMPLATE_TO_OVERRIDE']['theme path'] = drupal_get_path('module', 'MODULENAME');

}

Comment: [Here](https://www.drupal.org/node/839376#comment-10180778) is explained with more details. Thanks!
Answer: This is easier to do in a custom theme.
As noted in the documentation, the registry keys for themes are set up in the following manner:
$theme_registry['user_profile'] = array(
  'variables' => array(
    'account' => NULL,
  ),
  'template' => 'modules/user/user-profile',
  'file' => 'modules/user/user.pages.inc',
  'type' => 'module',
  'theme path' => 'modules/user',
  'preprocess functions' => array(
    0 => 'template_preprocess',
    1 => 'template_preprocess_user_profile',
  ),
);

So basically, I believe you could simply replace theme path key with the path to your module, and your template would be used.
<?php
//  unset the original template to set yours.

// Implement hook_theme_registry_alter
function MODULENAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['TEMPLATE_TO_OVERRIDE']['theme_path']  =>
    drupal_get_path('module', 'MODULENAME'))
}
?>

Now, you would have to find the proper variable in $theme_registry, this code example is not working code. You would  also probably need to copy the original preprocess function in the module since the theme path is now overridden.
There is probably an easier way of doing this, but believe me doing this in a theme is way simpler, and less chances to break existing functionality of existing modules.
In a custom theme scenario, you would just need to have your copy of the custom template in your theme and it would be good to go.
Comment: Thanks for helping, @stefgosselin . Eventually (after Googling a lot) I found another way, I'll post it soon here.
Comment: @giga would you be able to post your other way, please. Thanks!
Answer: @stefgosselin is absolutely correct but need a little correction in code section.
i am writing the exact code which worked for me.
<?php
// Implement hook_theme_registry_alter
function MODULENAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['TEMPLATE_TO_OVERRIDE']['theme path']  =
    drupal_get_path('module', 'MODULENAME');
}
?>

just try to implement this code inside your custom module and it will definitely work.
Answer: Here is an example of mytemplate.tpl.php located in my module's templates directory overwrites toolbar.tpl.
/**
 * Implements hook_registry_alter().
 */
function lml_node_theme_registry_alter(&$theme_registry) {
  $module_path = drupal_get_path('module', 'my_module');
  // Override the default template with our own.
  if (isset($theme_registry['toolbar'])) {
    $theme_registry['toolbar']['theme path'] = $module_path;
    $theme_registry['toolbar']['path'] = $module_path . '/templates';
    $theme_registry['toolbar']['template'] = 'mytemplate';
  }
}


PHP: Link address of multiple array keys into another bigger array

Question: I want to combine 3 small arrays that have unique keys between them into 1 big array but when I modify a value in the big array I want it also to reflect in the corresponding small array.
For example I have these 3 small arrays:
$arr1 = ['key1' => 'data1', 'key2' => 'data2'];
$arr2 = ['key3' => 'data3', 'key4' => 'data4', 'key5' => 'data5'];
$arr3 = ['key6' => 'data6'];

I want to have a $bigArray that has each key's address linked/mapped to each value of the small arrays. So if I do something like:
$bigArray['key4'] = 'something else';

then it would modify $arr2['key4'] to the same value ('something else').
If I try something like:
$bigArray = [&$arr1, &$arr2, &$arr3];

It has the unfortunate effect of making a multidimensional array with the keys to the values mapped.
Comment: Why do you need this? Maybe you can revisit your logic? because there's no simple way to accomplish it. You need to loop over all the arrays and make pointers to actual values.
Comment: I appreciate the concern, you are right, every solution posted is very costly computation wise but this is my 3rd idea on how to solve my problem and it does not seem to be as cheap as I thought.
Answer: Two ways i found
<?php
error_reporting(E_ALL);

$arr1 = ['key1' => 'data1', 'key2' => 'data2'];
$arr2 = ['key3' => 'data3', 'key4' => 'data4', 'key5' => 'data5'];
$arr3 = ['key6' => 'data6'];

$big = [];
if (true) {
    foreach (['arr1', 'arr2', 'arr3'] as $v) {
        foreach (array_keys($$v) as $k) {
            $big[$k] = &${$v}[$k];
        }
    }
}
else {
    foreach ([&$arr1, &$arr2, &$arr3] as &$v) {
        foreach (array_keys($v) as $k) {
            $big[$k] = &$v[$k];
        }
    }
}

$big['key1'] = 'data1mod';
print_r($big);
print_r($arr1);

3rd way with function
$big = [];
$bindToBig = function (&$a) use (&$big) {
    foreach (array_keys($a) as $k) {
        $big[$k] = &$a[$k];
    }
};

$bindToBig($arr1);
$bindToBig($arr2);
$bindToBig($arr3);

Comment: I especially like your 3rd solution, it very easy to read and understand in a big program.

I was hoping that there would be a better solution than simply looping all the arrays but alas, PHP does not have the required constructs.
Answer: You can't bind data that way, but you can link them in the same object:
class ArrayLink {
    public $bigArray;
    public $linkedChildrenArray;
    protected $childrenArray;

    public function __construct( $childrenArray ) {
        $this->childrenArray = $childrenArray;
    }

    public function changeValueForKey( $arrKey, $arrValue ) {
        foreach ( $this->childrenArray as $key => $value ) {
            foreach ( $value as $subKey => $subValue ) {
                if ( $arrKey == $subKey ) {
                    $this->bigArray[ $subKey ]              = $arrValue;
                    $this->childrenArray[ $key ][ $subKey ] = $arrValue;
                }
            }
        }
        $this->linkedChildrenArray = (object) $this->childrenArray;
    }
}

As you can see, the $arr2 now need to be access from $arrayLink object:
$arr1 = [ 'key1' => 'data1', 'key2' => 'data2' ];
$arr2 = [ 'key3' => 'data3', 'key4' => 'data4', 'key5' => 'data5' ];
$arr3 = [ 'key6' => 'data6' ];

$arrayLink = new ArrayLink( array( 'arr1' => $arr1, 'arr2' => $arr2, 'arr3' => $arr3 ) );
$arrayLink->changeValueForKey( 'key3', 'new value for key 3' );

echo $arrayLink->bigArray['key3']; //new value for key 3
echo $arrayLink->linkedChildrenArray->arr2['key3']; //new value for key 3

Comment: Your solution is more a search instead of an actual map of the arrays. I appreciate the ingenuity for suggesting a search but if there are a lot of values to change then your solution becomes expensive computation wise and unfortunately that is my scenario. It would have made sense if I would have to change 1 or max 2 values.


Ajuda com $this e self em php

Question: abstract class BaseModel {
    public function find($params){
        $table = $this->$table;

        //...
    }
}

class User extends BaseModel {
    protected $table = "users";
}

se eu fizer:
$u = new User();
$u->find([]);

funciona nomalmente porque eu criei uma nova instancia da classe user.
mas se eu quiser fizer diretamente:
User::find([]);
eu não conssigo porque não a nenhuma referencia para o $this
como que eu resolvo isso?
Comment: Não entendi qual o problema a ser resolvido. É só não fazer o que não pode, Ou parar de usar OOP só porque está na moda. Afinal me parece que o que está tentando fazer é usar OOP onde não precisa, por isso está criando um problema. Mas sem maiores informações não posso garantir.
Comment: Repetir o que você já disse na pergunta não acrescenta nada. Pra quê o `find` precisaria do `$this`? Essa e outras informações básicas tem que estar no corpo da pergunta, senão não dá pra saber o que você está tentando fazer, e nem se o resto do código está certo. Sugiro antes de mais nada dar uma lida em [Ask], e depois [edit] a pergunta com as informações relevantes.
Comment: Mais fácil você explicar qual resultado quer obter, do que só mostrar a maneira que está tentando fazer. Se puder, clique em [edit] e explique melhor qual é o comportamento que o código deve ter. Aproveite e revise aquele `$protected` lá, que está um pouco "esquisito".
Comment: Entendi, a pessoa precisa mexer com laravel pra entender o que você está dizendo. Com certeza se `App\User::find(1)` funciona no laravel, a resposta é bem simples: o laravel não usa o `$this` no find. Aliás, nem faria sentido. Se precisar de `$this` num método estático, você já tem erro em outras partes do código.
Comment: Cada vez mais confirma o que eu disse inicialmente está tentando pegar algo que não é OOP e tentar fazer virar OOP à força. Não vai funcionar mesmo.
Comment: ja resolvi meu problema, os caras do tableless consseguiram me entender e me ajudaram em 2 min. sem complicação. obg pela atenção de vcs
Comment: Que bom que resolveu.Se quiser postar a solução aqui pra ajudar outras pessoas com o mesmo problema, pode publicar como resposta, faz parte das regras do site. E, desde que seja uma solução boa, que responda o que está na pergunta, e ensine certo as pessoas, pode receber votos positivos.
Comment: oque eu quero é poder usar a função find() como static, mas eu tambem quero poder instanciar a classe e usar o função find() normalmente.
Comment: Pra ficar mais claro é algo parecido com o laravel, tipo: na laravel eu posso fazer App\User::find(1); sem precisar instanciar uma classe App\User, da mesma forma que eu posso primeiro instanciar um obj App\User e depois usar o find ( $user->find(1) )
Answer: Pode resolver isso simplesmente mantendo da forma como já está fazendo
$u = new User();
$u->find([]);

O $this não pode ser acessado estaticamente. Por isso não funcionará fazer User::find([]);
É possível fazer o que pretende, mas não recomendado.
Se o intuito for meramente visual, para ter um código menor, esqueça isso. Ou se o intuito for prover um acesso inline, pode pensar em outra forma como method chaining ou simplesmente criar uma função:
function userFinD()
{
    $u = new User();
    return $u->find([]);
}

userFinD();

Mas se ficar incomodado em ter que criar uma função, também pode invocar inline uma rotina com múltiplas linhas. Para isso usa-se funções anônimas.
Como não sei ao certo o que realmente pretende fazer, evitarei detalhar sobre as opções citadas.
Comment: obg pela sua ajuda, mas eu decide usar outro metodo para esse meu proposito. ficou até melhor. de qualquer forma obgd!
Answer: SOLUÇÂO:
abstract class BaseModel {
    public function find($params){
        $table = '';

        if($this)
            $table = $this->$table;
        else {
            $u = new User();
            $table = $u->table;
            unset($u);
        }

        //...
    }
}

class User extends BaseModel {
    protected $table = "users";
}

Comment: Não entendi onde isso soluciona o que foi perguntado.

Ajuda com $this e self em php


How to physically bridge network interface KVM - Ubuntu 10.04

Question: I have a host installed Linux/Ubuntu 10.04 LTS on a Dell PowerEdge server with 4 NICs interfaces, so how can I dedicate a network interface for Guest Machine ?
Comment: Why not simply bridge it? What are you trying to achieve?
Answer: If you use libvirt, you have to use the passthrough mode, as explained in http://wiki.libvirt.org/page/Networking#PCI_Passthrough_of_host_network_devices
Answer: You will need to setup a network bridge interface on the host and have the virtual machines share the physical interface of the host. Although I am not certain about this, by default KVM uses NAT, so you have to manually configure the bridge. This involves installing some bridge related packages and modifying <code>/etc/network/interfaces</code> file. Please read this for a step by step instructions.
Comment: i already do this and this is my configuration, 'auto eth0
iface eth0 inet manual
iface br0 inet static
address 192.168.0.236
network 192.168.0.0
netmask 255.255.255.0
broadcast 192.168.0.255
gateway 192.168.0.253
bridge_ports eth0
bridge_stp off
bridge_maxwait 0
bridge_fd 0
auto br0
'


$f,g: \mathbb{R} \to \mathbb{C}, 2\pi $ periodic. Prove: if $f(x)=0$ for every $x$ around $x_0$ so $S_nf(x_0) \to 0$ when $n \to \infty$

Question: Let $f,g: \mathbb{R} \to \mathbb{C}$ $2\pi$ periodic , Riemann integrable in $[0, 2\pi]$.
I need to prove that if $f(x)=0$ for every $x$ around $x_0$ so $S_nf(x_0) \to 0$ when $n \to \infty$.
We define $S_nf(x_0)=\sum_{-n}^{n}\hat f(n)e^{inx_o}$ and $\hat f(n)=<f,e^{inx}>=\frac{1}{2\pi}\int_{0}^{2\pi}f(t)dt$, so I can't really see what makes the series 0 when n tends to infinity since $\hat f(n)$ does not depend on $x_0$ or other $x$'s around it.
Thank you very much
Answer: This is a direct consequence of theorem 8.14 in Rudin's 'Principles of Mathematical Analysis' and is actually made explicit in a corollary stated in the same section. (It's formulated there for $f:[-\pi,\pi] \rightarrow \mathbb{R}$, but that's just the same).
Comment: Thanks, but he does not prove it either.. How can I use the lipschitz theorem for proving that?
Comment: @Jozef ? - in my copy is a proof, if I recall correctly. I'll check when I get home.
Answer: For the favor of people who will be interested for an answer to this question:
According to Dirichlet theorem: $f$ applies Lipshcitz conditions in $x_0$, it is Differentiable and $f'(x_0)=0$ so there's a pointwise convergent to the average  of the limits in both sides, which is $f(x_0)=0$.
Another way to look at it is just by the theorem says that $||S_nF(x)-F(x)|| \to 0$.
Comment: According to your assumption $f(x) = 0$ in a neighbourhood of $x_0$. That is, there is a $\delta$-neighbourhood of $x_0$ where $f$ is $0$. So $|f(x)-f(x_0)|=0 $ in that neighbourhood, which trivially implies that the hypothesis of the theorem is true. There is no need to refer to a Dirichlet theorem here, your question is solved by an immediate application of theorem 8.14 in Rudin (for which a proof is supplied in my copy).
Comment: A proof for the theorem itself or the the this immediate application?
Comment: A proof for the theorem. As explained in my comment, the corrolary is an _absolutely trivial_ consequence of the theorem. Just check the hypothesis.


Render array doesn't render children

Question: I can't add a form to a node. Using the following code, the generated HTML show only the node. If I return $form, the form is rendered correctly. What is my mistake ?
function hook_menu() {
$items['presse/rss'] = array(
'title' => 'RSS',
'access callback' => TRUE,
'page callback' => 'press_rss_page',
'page arguments' => array('fr'),
'menu_name' => 'nav-fast-links-fr',
'file' => 'press.rss.inc',
'type' => MENU_NORMAL_ITEM,

);
FILE: press.rss.inc
function press_rss_page($lang) {
     $nid = variable_get('press_rss_nid_' . $lang, 0);
     $page = array();
     if ($nid) {
        $page = node_view(node_load($nid));
     }

     $path = $_SERVER['HTTP_HOST'];
     $path .= $lang == 'fr' ? '/presse/rss/' : '/press/rss/';
     $form['#weight'] = 1000;
     $form['container'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
     );

     $form['container']['all']['title'] = array(
        '#markup' => '
' . 'All the press room content' . '
',
         );
     $form['container']['all']['text'] = array(
        '#type' => 'textfield',
        '#title' => t('All the feeds', array(), array('context' => 'frontend')),
        '#value' => $path . 'all',
        '#disabled' => TRUE,
        '#id' => 'rss-1',
        '#attributes' => array(
        'onClick' => "this.select();",
        'readonly' => 'readonly',
),

);
  $page['form'] = $form;

   return $page;

}
Answer: Return your renderable page build with 2 entries, one for the node and one for the form:
return array(
    'node' => $page,
    'form' => $form,
);

Comment: Yes, it's returned the 2 entries, but I want the form embed in the div of the node
Comment: With your solution pageform. I want pageform.
Comment: You need to use `hook_node_view()` for that. Or search through the existing render array to find an appropriate place to inject the form.
Comment: Based on this drupal_render documentation, I think that added the $form to $page['form'] is ok... but it don't : "Renderable arrays have two kinds of key/value pairs: properties and children. Properties have keys starting with '#' and their values influence how the array will be rendered. Children are all elements whose keys do not start with a '#'. Their values should be renderable arrays themselves, which will be rendered during the rendering of the parent array. The markup provided by the children is typically inserted into the markup generated by the parent array."
Comment: That's correct, but you trying to add your $form on an already renderable array build of a node ... which works differently. You need to inject your form in the `content` part/array of the `node_view` return.
Comment: Isn't the $page is already the Content part of the node ? And how the renderable array build of a node is different ?

Render array doesn't render children


How to perform lock on desktop folder using java

Question: I have one folder on desktop with name of ABC. Now, I want to write an java program for this folder for security. I mean if any user click on ABC folder the before opening the ABC folder
it should ask for login first. If user is not valid then he cant open the ABC folder.
So I want to  perform this thing through java swing.
Answer: I don't think that this can be done using java. If it was possible, it would be an unholy mess anyway because you'd have to change the default handler for all folders to your java program, not just the folder that you want to protect. Also, it would be insecure because there would be nothing stopping people from using another file manager to open the folder, bypassing your security entirely.
You could, however, implement your own pseudo folder security by using java to encrypt files, but that would obviously not be a standard folder on your desktop.
Why do you insist on using java? Have you heard of truecrypt?
Comment: Tnx for reply. i do not know about truecrypt.


Existence of a monochromatic equilateral triangle on a 3-colour plane

Question: Given a $3$-colour plane, is it possible to give a geometrical representation to prove the existence of a monochromatic equilateral triangle i.e. an equilateral triangle all whose vertices are of same colour?
For a $2$-colour plane, we can prove the existence of such an equilateral triangle with the help of a regular hexagon.
For a $3$-colour plane, if no $2$ points at a fixed distance $d$ are of same colour, then also we can again prove the existence of such an equilateral triangle with the help of a regular hexagon.
But what if we don't have the above restriction, can we give an appropriate geometry to answer the question? All I know is that there will always exist a line segment of fixed length whose end points are of same colour.
Comment: Can you sketch the argument for two colours?
Comment: Consider a regular hexagon $ABCDEF$ with geometric center $G$. Let $G$ be of colour $1$. If all the vertices of the above hexagon are of colour $2$, then we are done, as $ACE$ is the required equilateral triangle. So, let one of the vertices of the hexagon, say $A$ be of colour $1$. Now, if $B$ or $F$ is of colour $1$, then we are done.

So, let $B$ and $F$ be of colour $2$. Now, if $D$ is also of colour $2$, then $BDF$ is our equilateral triangle. So, let $D$ be of colour $1$. If $C$ or $E$ is of colour $1$, then again we have either $GCD$ or $GDE$ as the required equilateral triangle.
Comment: So, let both $C$ and $E$ be of colour $2$.

Now, extend $AB$ and $DC$ each to intersect at $H$ (say). Then no matter which colour $H$ may have, we have the required equilateral triangle (either $BCH$ or $ADH$)
Answer: This can be done with two applications of van der Waerden's theorem. First, there must be ten points, equally spaced, of one colour (say colour 1).  Draw a large equilateral triangle with this base, giving 45 more points above it, each one the tip of an equilateral triangle whose other vertices have colour 1. So, none of these 45 points are colour 1.
In particular, the nine points just above are equally spaced and of colours 2 and 3 only, so there are three equally spaced points of one colour (by van der Waerden's again). From here, the argument in your second comment finishes the problem.
It might be worth noting your approach is ultimately similar to my second paragraph here - the existence of three points of the same colour is shown first, then a triangle placed on it.


"Blog Post" show from Mysql Database wtih Image

Question: How can I show my all "blog post" with images? Example:
Mysql table:
post_id | user_id | subject | message | image | img_name.

What is the php code to display all my posts with images in the index page? I used the following code but it doesn't display images, it shows only data. I would like to see something like this:

image | message is here
  image | message is here
  image | message is here

I used 3 pages

add_post.php(Html form)
add_post_process.php(process the add_post.php)
index.php (which shows my all post)

add_post_process.php:
<?php
include "db.php";
@$file = addslashes($_FILES['image']['tmp_name']);
$lastid= mysql_insert_id();
@$img = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$img_name = addslashes($_FILES['image']['name']);
@$img_size = getimagesize($_FILES['image']['tmp_name']);
$upload_path = './blogpostimg/';
$post_id = addslashes($_POST['post_id']);
$user_id = addslashes($_POST['user_id']);
$subject = addslashes($_POST['subject']);
$message = addslashes($_POST['message']);
$cat_id = addslashes($_POST['cat_id']);
$cat_name = addslashes($_POST['cat_name']);
$comment_count = addslashes($_POST['comment_count']);
$ch_img = addslashes($_FILES['image']['name']);
$query = "SELECT img_name FROM blog_post WHERE img_name = '$ch_img';";
$result = mysql_query($query) or die (mysql_error());
if(isset($subject, $message))
{
  $errors = array();
  if(empty($subject) && empty($message) && empty($file))
  {
    $errors[] ='all field required';
  }
  else
  {
    if(empty($subject))
      $errors[] = 'Subejct requried';
    if (empty($message))
      $errors[] = 'message required';
    if(empty($file))
      $errors[] ="SORRY, you have to be upload a image";
    elseif($img_size == FALSE)
    {
      $errors[] ="That's not an image";
    }
    else
    {
      if(mysql_num_rows($result) != 0)
      $errors[] = " You have to change this image name, already exit in our database";
    }
  }
  if(!empty($errors))
  {
    foreach($errors as $error)
    {
      echo "
";
      echo "
$error

";
      echo "
";
    }
  }
  else
  {
    if(!move_uploaded_file($_FILES['image']['tmp_name'],$upload_path . $img_name))
    {
      die('File Not Uploading');
    }
    else
    {
      $lastid = mysql_insert_id();
      $query = mysql_query("INSERT INTO blog_post VALUES ('', '',   '$subject',
        '$img','$img_name','$message','$cat_id','$cat_name','',NOW() )");
      if($query)
        echo "Successfully uploaeded your post";
      else
      {
        echo "Something is wrong to Upload";
      }
    }
  }
}
?>

index.php
<?php
include "db/db.php";
$upload_path = "/secure/content/blogpostimg";
$sql= mysql_query("SELECT * FROM blog_post");
while ($rel = mysql_fetch_assoc($sql))
{
  $id = $rel['post_id'];
  $sub = $rel['subject'];
  $imgname = $rel['img_name'];
  $img = $rel ['image'];
  $msg = $rel['message'];
  $date = $rel['date'];
  echo "
". "$sub" ."
". "
";
  echo "$imgname" ."
";
  echo '';
  echo "$msg" . "
";
  echo "$date" . "
";
  echo "
";
  echo "
";
}
?>

The mysql table structure is
post_id(int)
User_id(int)
subject(varchar)
image(blob)
img_name(varchar)
message(text)

Comment: possible duplicate of [php database image show problem](http://stackoverflow.com/questions/2577416/php-database-image-show-problem)
Answer: In your index.php you have . Instead of $upload_path, src needs to be the URL to your image.

I just noticed that you are storing the image itself in the database. There is no need to do this if you move it to a publicly accessible directory, e.g. /var/www/images/myimage.jpg
Comment: Hi, middus, thanks for your reply...i used this code... echo ''; but it's doesn't show.
Comment: That's probably because `$upload_path` is not a URL, it's a directory on your computer. And because `$img` seems to be a binary blob, not a filename.
Comment: Thanks a lot middus it's working. but it's show too many image, so that i changed my query..here is the query.....$sql= mysql_query("SELECT * FROM blog_post WHERE post_id = '$id' ORDER BY post_id DESC"); BUT it's show blank page. ?
Comment: Hey, I finally Solved my Problem, Thanks, Thanks a lot "middus".
Answer: change
echo '';

to
echo '';

that should do the trick..
I don't now if it matters in performanceways.. but howcome you use blob instead of a varchar.. 255 characters for a filename should be enough.
Comment: btw.. are the paths $upload_path = "/secure/content/blogpostimg";  and
$upload_path = './blogpostimg/'; equal
Comment: Well Burrhus, It's show something like that  [ ·ÿI,è"¡qx:Øà ŸI¸÷m律?ò!YôzwýŧþÛgþAQèbn»úü¥i'ý©$9¯a¼Òvg ] Doesn't show image. I used two column name, One is "image(Blob)" and other is img_name(varchar).
Comment: ahhh.. sorry.. my mistake.. the blob has to be converted. http://www.firebirdfaq.org/faq250/ -- I would propably change the type to varchar if possible


Google Pie Charts não é exibido quando os dados tem mais de um row

Question: estou tentando exibir um PieChart, porém, se a pesquisa no banco retorna somente uma linha, o gráfico é exibido. Se retorna mais de uma linha, o gráfico não aparece.
funcao que gera os dados do gráfico:
public function grpAplicacaoRecursos() {
// Estrutura basica do grafico
    $grafico = array(
        'dados' => array(
            'cols' => array(
                array('type' => 'string', 'label' => 'Descricao'),
                array('type' => 'number', 'label' => 'Valor')
            ),
            'rows' => array()
        ),
        'config' => array(
            'title' => 'Para onde vai meu dinheiro',
            'width' => 400,
            'height' => 250
        )
    );

    $dataAtual = new DateTime('now');
    $inicioUltimaSemana = date('Y-m-d', strtotime($dataAtual->format('Y-m-d').' -365 days'));

    $dados = $this->registry->conn->fetchAll('SELECT c.descricao descricao, sum(m.valor) valor '.
            'FROM movimento_conta m left join conta c on m.conta_id = c.conta_id where m.data '.
            'between ? and ? group by descricao ', array($inicioUltimaSemana, $dataAtual->format('Y-m-d')));

    foreach ($dados as $row) {
        $grafico['dados']['rows'][] = array('c' => array(
                array('v' => $row['descricao']),
                array('v' => $row['valor'])
        ));
    }
    // Enviar dados na forma de JSON
    header( 'Cache-Control: no-cache' );
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($grafico);
}

retorno da função:
{
"dados":{
  "cols":[
     {
        "type":"string",
        "label":"Descricao"
     },
     {
        "type":"number",
        "label":"Valor"
     }
  ],
  "rows":[
     {
        "c":[
           {
              "v":"teste1"
           },
           {
              "v":"554.890"
           }
        ]
     },
     {
        "c":[
           {
              "v":"teste2"
           },
           {
              "v":"2556.000"
           }
        ]
     }
  ]
},
"config":{
  "title":"Para onde vai meu dinheiro",
  "width":400,
  "height":250
}
}

script na página que exibe o grafico:

Alguém sabe me dizer o que estou fazendo de errado ?
Comment: Achou alguma solução? Poste como resposta para ajudar outras pessoas.
Answer: Por acaso você esperava ver algo assim:

Se for, é bem simples de resolver apesar de não ser lá muito óbvio: Seus valores decimais não decimais, são strings numéricas.
Muito provavelmente a culpa é da forma como o Google Charts interpreta a informação do JSON informado.
Se eu tivesse que adivinhar diria que por você estar definindo um type como number mas estar passando uma string, quando esse valor é convertido para número da regra que você definiu, deve resultar em algum valor inesperado.
Remova as aspas dos valores forçando o cast da variável para float e o gráfico deve aparece (deve porque eu modifiquei o JSON manualmente):
foreach ($dados as $row) {
    $grafico['dados']['rows'][] = array('c' => array(
        array('v' => $row['descricao']),
        array('v' => (float) $row['valor'])
    ));
}

Desprezar os zeros à direita da casa decimal também faz o gráfico aparecer, mesmo sem alterar o tipo da variável, mas os resultados que obtive foram diferentes.


How do I find the variance of $\overline{X}^2 - \frac{1}{n}$ where $X_i\sim N(\theta,1)$?

Question: I have a problem here. The question asks to compare the UMVUE and MVBE of $\theta^2$ considering a random sample $X_1,...,X_n$ from a $N(\theta,1)$ distribution.
I found out the Cramer Rao Lower Bound for the variance of an unbiased estimator for estimating $\theta^2$ to be $\frac{4\theta^2}{n}$. Since $\overline{X}$ came out to be a sufficient and complete statistic, I used this to get the UMVUE which is  $T = \overline{X}^2 - \frac{1}{n}$.
Now I have to find the variance of $T$.
Now,$Var[T]=Var[\overline{X}^2]$.
I see that $Z=n(\overline{X} - \theta)^2$ has a $\chi_1^2$ distribution. So,
 $Var[Z] = 2$
$\implies Var[(\overline{X} - \theta)^2]= \frac{2}{n^2}$
$\implies Var[\overline{X}^2 +\theta^2 - 2\overline{X}\theta] = \frac{2}{n^2}$
$\implies Var[\overline{X}^2] + Var[2\overline{X}\theta] = \frac{2}{n^2}$
$\implies Var[\overline{X}^2] = \frac{2}{n^2} - Var[2\overline{X}\theta]$
$\implies Var[\overline{X}^2] = \frac{2}{n^2} - \frac{4\theta^2}{n}=Var[T]$
The answer says that $Var[T] = \frac{2}{n^2} + \frac{4\theta^2}{n}$.
So where am I going wrong?
Edit: My teacher had used this method which I wasn't able to understand in two places. If someone could clarify this for me,would be great.
$Var[T] = Var[\overline{X}^2] = E[\overline{X}^4] - E^2[\overline{X}^2]$
$=E[\overline{X}^4] - (\mu^2 +\frac{1}{n})^2$
Now, $E[\overline{X}^4]=E[\overline{X} - \mu + \mu]^4$
$=E[\overline{X} - \mu]^4 + 4E[\overline{X}-\mu]^3\mu + 6E[\overline{X}-\mu]^2\mu^2 +4E[\overline{X}-\mu]\mu^3 +\mu^4$
$=3\frac{1}{n^2} + 0 + 6\frac{1}{n}\mu^2 + 0 + \mu^4$.
I can't understand how the first two terms came about in the last step.
Comment: Please explain though. Since I thought V(X+Y-Z) = V(X) + V(Y) + V(Z), where X,Y and Z are all independent distributed random variables.
Comment: You go for $\mathsf{Var}(\overline{X}^2-2\overline{X}\theta)=\mathsf{Var}(\overline{X}^2)+\mathsf{Var}(2\overline{X}\theta)$, but $\overline{X}^2$ and $2\overline{X}\theta$ are not independent.
Comment: Oh,damn. Okay,I see it now. Could you suggest a way to find the variance of T?
Comment: You could try out $\mathsf{Var}(X+Y)=\mathsf{Covar}(X+Y,X+Y)=\mathsf{Var}(X)+2\mathsf{Covar}(X,Y)+\mathsf{Var}(Y)$ (applying bilinearity of covariance). This for rv's $\overline{X}^2$ and $2\overline{X}\theta$. I do not exclude that it can be simpler because I only had a short look on your question.
Comment: I've edited the question to add some more information.
Answer: If $X_1,\dots,X_n$ are iid normal rvs with mean $\mu$ and variance $1$ then: $$Z:=\sqrt{n}\left(\overline{X}-\mu\right)=\frac{\sqrt{n}}{n}\sum_{i=1}^{n}\left(X_{i}-\mu\right)$$
has standard normal distribution so that $\mathbb{E}Z^{4}=3$ (see here).
That leads to $\mathbb{E}\left(\left(\overline{X}-\mu\right)^{4}\right)=\mathbb{E}\frac{1}{n^{2}}Z^{4}=\frac{3}{n^{2}}$
and $\mathbb{E}\left(\left(\overline{X}-\mu\right)^{3}\right)=\mathbb{E}\frac{1}{n\sqrt{n}}Z^{3}=0$


Hyper-V cluster VS regular cluster

Question: We need to choice between Hyper-V and regular cluster technologies. What is the advantage and disadvantage of these approaches?
Update:
We have to physical servers and want to build reliably solution using cluster approach. We need to clustering our application and DB (MS SQL). We know that we can use:

Regular Windows Cluster Service. Application and DB will be migrating from one node to other.
Hyper-V Failover Cluster. Virtual machine will be migrating from one node to other.
Combined variant. DB mirroring for MS SQL and Hyper-V for our application.

We need to make a choice between this approach. So we need to know advantage and disadvantage of these approaches?
Comment: I updated the question and tried to be more specific.
Comment: This is a bit of a non-question. What are you clustering? There's no such thing as a "regular cluster" as clustering is such a generic term it has no real meaning. Give us two clear examples, for example "A Hyper-V High Availability cluster with a SAN running a single instance of SQL Server that will be migrated to a secondary machine in the event of a failure", and "An SQL Server Cluster using Microsoft Clustering Service and SQL's native cluster, where the databases are stored on a replicated SAN". And that's just one common example. We need way more info.
Comment: are you trying to say hyper-v r2 the "product" vs regular windows 2008 r2 server running hyper-v in a clustered configuration.  Cuz if so then there is no difference technically.  If thats not your question then this is a  non-question..
Answer: I can't think of many instances where providing high availability at the machine level is better than providing high availability at the application level. If you have the budget, and your application supports is (like SQL does), then provide your HA at the application level.
Machine level HA really only has the benefits of reduced cost when you're trying to keep several services up and the ability to provide HA for applications and services that don't natively support it.
There are some great things you can do with application level HA that machine level HA won't let you:

You can update your operating system without suffering significant downtime. Machine level HA still requires that you reboot the VM in order to install updates. That's going to require more downtime than a simple service failover
Keep your system running even if you have OS level failures.
Be able to withstand application level disturbances. If you have a service fail and you're only failing over the VM, you're still down.
Comment: By "Machine level" you mean approach with virtual machine?
Comment: @Sasha - Yes. I mean a Hyper V cluster setup for VM high availability.
Answer: Clustering the hosts and clustering the guests provide similar benefits.  If one physical machine fails, another will provide a platform for getting your workload running again.
The main differences come in how the clusters are managed, and in what, exactly, happens at the moment of failover.
Host clustering:

You can configure groups of hosts that can run any VM.
Host failure results in the VM rebooting, hosted on a different physical machine.
Shared storage is required
The management of the cluster is at the host layer, and quite homogenous.  All workloads are given high-availability properties.
Intra-cluster communication happens very reliably.  It can't be interrupted because a VM didn't get CPU time or access to I/O.
Live migration depends on host clustering, so you probably are already on a path to enabling it.

Guest clustering:

Each individual VM needs to be configured as part of a cluster.
Each cluster is specific to the type of workload.  If the workload doesn't support clustering, you can't cluster at this level.
Shared storage is probably required, but might not be.
Intra-cluster communication is harder to guarantee, so failovers sometimes happen unnecessarily, particularly during live migration.  This might or might not matter to you.
Failover, when it happens, might be somewhat faster, as the OS doesn't have to boot.  For databases, though, this usually isn't the large part of the failover time.

I used to think that you should always cluster at the guest level, if you could.  Then people walked me through the management effort involved in that and showed me that it often makes a lot of sense to cluster at the host level.
Comment: You describe variants for Hyper-V, but what about regular Windows Cluster Service (application and DB will be migrating from one node to other). Does this approach has some advantages and disadvantages against using Hyper-V?
Comment: Sasha, that's exactly what I was referring to with the term "guest clustering."

Hyper-V cluster VS regular cluster


Facebook fan page photo's scraping

Question: We want to add a facebook fan page photo competition to our fan page. The meaning is that ppl can upload photo's and others can like them. The person with the most likes on his photo wins a price.
Now i was wondering if anyone knows a good idea on how to get a snapshot of all the photo's on a given moment. So that when we want to stop the contest we get an overview of the number of likes of all the persons.
Some good website scraping tools? maybe a usefull facebook app? some other alternatives?
greets,
Daan
Answer: I can think of some fancy ways to do this, but the easiest approach would be to just download the facebook fan page at the moment you want to stop the competition, so that you can view the results later.

Facebook fan page photo's scraping


Web service with application-level and user-level authentiation

Question: I need to create a Drupal site (D6 or D7 are both OK) with an API. The Services module is the obvious choice, but I couldn't yet figure out if it is possible to do what I want.
My site will contain users and a list of mobile apps that are known to the site. Every user has an 'activity log' on the site (probably a view of nodes where type = activity and user = current user). The users can use one or more of those apps on their mobile devices. When a user does something with an app, the app should connect with the site through the API and write a message (ie. create an 'activity' node) in the user's activity log.
As far as I can see, I will need two levels of authentication. On the application level, the mobile app should identify itself as one of the known apps. On the user level, the user must log in with his username and password, to make sure that his actions will end up in the correct activity log.
I have not yet figured out the best way to do this with Services and related modules. I hope someone can tell me:

if it can be done;
which version of Services I need;
which related modules could be used for authentication;
how to configure them.

Thanks!
Answer: Under D6, using Services 3.x
It may be more easy to consider that:

User authentication should be handled directly by Services (OAuth/API/Session)
Using an specific mobile app is a Permission:

in your module, in the resources definition, add a access_callback & access arguments:

Code:
<code>/**
* Implementation of hook_services_resources().
*/
function mymodule_api_services_resources() {
  return array(
   'myresource' => array(
     'retrieve' => array(
       'callback' => '_mymodule_resource_retrieve',
       'access callback' => '_mymodule_api_access',
       'access arguments' => array('Use registered mobile app'),
       'access arguments append' => TRUE,
       ...
</code>

add corresponding permissions in a my_module_permission() hook:
Code:
<code>/**
* Access callback for the resource.
*
* @param string $op
*  The operation that's going to be performed.
* @param array $args
*  The arguments that will be passed to the callback.
* @return bool
*  Whether access is given or not.
*/
function _mymodule_api_access($op, $args) { ... }
</code>
And then return false if the mobile app is not registered...
Comment: Thanks for your response. I'm going to give this a try and set up a proof-of-concept. Is there a specific reason not to use D7 for this?
Comment: Wait, I think I know why you're saying D6... The OAuth module hasn't been ported to D7 yet :-/
Comment: I had to use extensively Services for a D6 project... One of Services maintainer (Hugo Wetterberg) used to have a bunch of  [github repositories](https://github.com/hugowetterberg), have a look on there, you may find a WIP OAuth D7 port...
Comment: There's a OAuth port to D7 now


awesome wm/vicious widget: using a format function throws a bad argument error

Question: I am configuring the widgets in awesome wm (v3.5.5-1) using vicious (v2.1.3-1). I want to show the time in a widget. And then show the date in the tooltip when I hover over the time widget.
The following code using vicious in my rc.lua file works fine:
myclock = wibox.widget.textbox()
vicious.register(myclock, vicious.widgets.date, " %H:%M ")
myclock_tooltip =  awful.tooltip ({ objects = { myclock } })
vicious.register(myclock_tooltip, vicious.widgets.date, " %a %d %b ", 60)

However, when I try to combine the two vicious.register statements (based on the Format functions section of the vicious readme file):
myclock = wibox.widget.textbox()
myclock_tooltip =  awful.tooltip ({ objects = { myclock } })
vicious.register(myclock, vicious.widgets.date,
    function (widget, args)
        myclock_tooltip.set_text(" %a %d %b ")
        return " %H:%M "
    end)

I get the following error:
/usr/share/lua/5.2/vicious/widgets/date.lua:23: bad argument #1 to 'date' (string expected, got function)

Any suggestions where I'm going wrong?
Answer: Why do you need that format function at all? Doesn't the following work?
myclock = wibox.widget.textbox()
myclock_tooltip =  awful.tooltip ({ objects = { myclock } })
vicious.register(myclock, vicious.widgets.date, " %H:%M ")
myclock_tooltip_timer = timer({ timeout = 3600 })
myclock_tooltip_timer:connect_signal("timeout", function()
    myclock_tooltip:set_text(os.date(" %a %d %b "))
end)
myclock_tooltip_timer:start()
myclock_tooltip_timer:emit_signal("timeout")

This uses the "normal" vicious stuff for the widget and updates your tooltip with a seperate timer which fires once per hour.
Comment: Thanks for the sample code. I'd started looking into using timers and this gives me a good start. However, this code just sets the tooltip to the string " %a %d %b ". Also, it doesn't initialise the tooltip and it needs to be `myclock_tooltip:set_text`.
Comment: The following line can be used to initialise the tooltip and update it: `myclock_tooltip:set_text(os.date(" %a %d %b "))`.
Comment: Whoops & thanks. Added the missing `os.date` call, switched to `:set_text` and added a new `:emit_signal()` at the end to initialy set the text of the tooltip.
Answer: I don't believe you are doing anything wrong from a technical perspective. I think (and a quick look at the source confirms) that that widget just doesn't accept a function format.
It looks like some widgets take format strings (to be used by the widget function) and some accept format functions (to be called with the result of the widget function) but I don't see any clear indication from that README which are which.
Compare the worker function in date.lua against the worker function in uptime.lua for example.
The date.lua function uses the format argument in a call to os.date (which is what is generating the error you are getting, try calling os.date(function()end) locally).
The uptime.lua function does not use the format argument at all (presumably it gets called by vicious internally on the return value from that function.
It is probably worth asking to get the documentation updated to make this clearer (or fixing the documentation up yourself and submitting a patch for it).
Comment: Thanks for the guidance - very helpful. I'm new to Lua, so still getting used to the syntax.


Como setar a exibição do google maps por um formulario?

Question: Eu apliquei o javascript do viacep.com em um formulario, então quando o CEP é informado, ele completa dados como endereço sem numero, cidade, estado e bairro.
Eu gostaria de, com essas informações, exibir essa rua num google maps. Depois com um clique do usuario, colocar um marcador nesse mapa que completaria o numero da rua e a latitude e longitude desse marcador.
Abaixo, mostro q ja consegui por enquanto: apenas exibir o mapa com centro no estado de sp.
<form method="get" action=".">

        Cep: *
        <input class="input-field"  name="cep" type="text" id="cep" value="" size="10" maxlength="9" onblur="pesquisacep(this.value);" />

        Rua:
        <input class="input-field"  name="rua" type="text" id="rua" size="60" />

        Bairro:
        <input class="input-field"  name="bairro" type="text" id="bairro" size="40" />

        Cidade:
        <input class="input-field"  name="cidade" type="text" id="cidade" size="40" />

        Estado:
        <input class="input-field"  name="uf" type="text" id="uf" size="2" />

    </form>

Answer: Eu fiz exatamente isso em um formulário de cadastro de cliente, segue o que eu fiz que vai dar tudo certo

LEIA OS COMENTÁRIOS DO JAVASCRIPT

    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 19,
          center: {lat: -34.397, lng: 150.644}
        });
        var geocoder = new google.maps.Geocoder();
        geocodeAddress(geocoder, map);
      }

    function geocodeAddress(geocoder, resultsMap) {
     var ruaP = $("#logradouro").val() //CAMPO AONDE VOCÊ RECEBEU A RUA
     var bairroP =  $("#bairro").val() //CAMPO AONDE VOCÊ RECEBEU O BAIRRO
     var cidadeP =  $("#cidade").val() //CAMPO AONDE VOCÊ RECEBEU A CIDADE
     var estadoP  = $("#estado").val() //CAMPO AONDE VOCÊ RECEBEU O ESTADO
     var numeroP  = $("#numero").val() //CAMPO AONDE VOCÊ RECEBEU O NÚMERO
        var endereco = {
              rua: ruaP,
                bairro: bairroP,
                cidade: cidadeP,
                estado: estadoP,
                numero: numeroP
            }
        var address =  endereco.rua + " " + endereco.bairro + " " + endereco.numero + " " + endereco.cidade + " " + endereco.estado
        geocoder.geocode({'address': address}, function(results, status) {
          if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
              map: resultsMap,
              position: results[0].geometry.location
            });
          } else {
            alert('Geocode was not successful for the following reason: ' + status);
          }
        });
      }


KVM Networking - Multiple LANs

Question: I'm trying to set up some virtual servers with kvm and am struggling to work out what to do regards the network config. Currently I have 10 dedicated servers behind a firewall (asa 5505) - 2 of these dedicated servers I'd like to use as kvm hosts, each hosting 5 VMs.
In the past I've followed tutorials instrusting me to create a bridge (br0) to eth0 on the kvm host allowing them to get onto the network configured on the firewall. This brings me to my issue in that the 'inside' interface on the firewall has network/subnet of x.x.x.x/28 which doesn't provide enough ip's for the 10 dedicated + 10 virtual servers I'll have.
I suppose my question is what are my options and how could they be configured? One option would be to change the subnet mask however this will mean changing the site-site VPNs configured on the firewall and I'm very reluctant to do this.
I'm not sure if I should complicate things at this stage but:

some of the VMs need public IPs (which are the x.x.x.x addresses)
VM's on dedicated server 1 need to be able to talk to VMs on dedicated server 2
Comment: Contact your upstream provider and get more IP addresses, and some IPv6 while you're at it.
Answer: You can easily set up NAT routing rather than bridged routing on your KVM host.  However, this creates some issues you may need to address if you need inbound connectivity to guest VMs behind the NAT. You can set up rules on the KVM host to port-forward specific inbound traffic to specified guests, but (as with most NAT) unless you have some kind of load-balancing or other high-level traffic management layer, a port can only be forwarded to one guest.
Also, if you can segregate the VMs allocated to each host based on which other VMs they need to talk to, you may be able to get away with NAT without port-forwarding.
With all that said, if it were me and I controlled the address space I'd just change the subnet, adjust the VPN routing as needed, and use bridged networking.
Comment: Thanks for your advise. From what you say it sounds like it wouldn't be possible to have VM1 on Host1 with ip 192.168.122.101 talk directly to VM2 on Host2 with ip 192.168.122.102 without the use of port forwarding (or high-level traffic mgmt), is that right? My plan was to have one of the dedicated servers as a mysql vm host and the other as the web app vm host, so segregation would be tricky
Answer: I would stick to bridges, and (possibly) a separate VLAN for internal traffic, with an internal NAT/router to take care of NAT to the "inside" network and onwards.
A nicer solution would be to simply increase the subnet size of "inside"

KVM Networking - Multiple LANs


Correct Numbering for Scale Degrees

Question: For ever, I've only called scale degrees by their (Arabic) numbers. As opposed to chords, where I use Roman Numerals. Now, I've found out they really ought to have carets, or circumflexes over them. That seems somewhat superfluous, as those numbers can't mean much else.
Or - can they? They're supposedly to signify scale degrees. But the question springs up, which scale? Were it purely the major scale, it would make sense. But consider the note A, in scale with root C.
Major scale says A is ^6. Major pentatonic scale says ^5, chromatic scale says ^10 !
Somewhat confusing with or without '^'. Will someone please make some sense?
Comment: Related: [What are the degrees of a pentatonic scale called?](https://music.stackexchange.com/q/109905/21766)
Comment: > *"I've only called scale degrees by their (Arabic) numbers"* The roman numeral chord numbers refer to scale degrees; that is their whole purpose. The notation V7 means "the dominant 7th chord, rooted at the fifth degree of the scale". The roman numeral degrees came first, then the chord notation got applied to them. Scale degrees are also called by names like: tonic, supertonic, mediant, subdominant, ...
Comment: https://en.wikipedia.org/wiki/Degree_(music)#Major_and_minor_scales
Comment: @Kaz - aware of all that. Arabic numbers could refer to chords, too, it's just that I prefer not to go down that route. NNS does, and that's the way it is. I'll go your way, you go yours. Using RN means there's more to come - which actual chord will that 'root' be part of.
Answer: It's a convention that is most often used in circumstances where Arabic numerals can have multiple meanings. For example, imagine writing a paper that discusses scale degrees, finger numbers, and figured bass indications. The number 3 could apply to any of those, so adding a caret helps differentiate scale degrees from the other usages.
Scale degree usage presumes the scale itself is known, so they are used without ambiguity.
Comment: Also intervals. In formal text these would usually be spelled out ("major sixth"), but in casual written conversation (like here) "6" might get thrown around, and even in analysis it might be "M6," which I suppose raises the possibility that at some point you could be analyzing intervals without regard for their quality, and just using arabic numerals.
Comment: @AndyBonner note there are two naming convention. One uses "major" and "minor" 6. Another uses "natural" and "flat" 6. These are two different languages. And finally in casual speech one may say "sixth" to call any diatonic sixth.

Correct Numbering for Scale Degrees


Display every hour another content

Question: I want to show different content on my site every hour, I found this:
Fiddle:
<button onClick="getPhrase()">Show me a phrase for this hour</button>

window.getPhrase = function() {
    h = new Date().getHours(); //Get the current hour

    phrase = new Array(); //Create an array of phrases
    phrase[1] = 'Hello';
    phrase[2] = 'there';
    phrase[3] = 'this';
    phrase[4] = 'will';
    phrase[5] = 'show';
    phrase[6] = 'a';
    phrase[7] = 'different';
    phrase[8] = 'message';
    phrase[9] = 'depending';
    phrase[10] = 'on';
    phrase[11] = 'the';
    phrase[12] = 'hour';
    phrase[13] = 'of';
    phrase[14] = 'day';
    phrase[15] = 'that';
    phrase[16] = 'you';
    phrase[17] = 'look';
    phrase[18] = 'at';
    phrase[19] = 'it';
    phrase[20] = '!';
    phrase[21] = 'W';
    phrase[22] = 'X';
    phrase[23] = 'Y';
    phrase[24] = 'Z';

    document.getElementById('placeHolder').innerHTML = phrase[h-1]; //Show the array item relevant to the hour
}

But how can I display this without a button?
How can I remove the button?
Comment: ...don't use a button?
Comment: try using `setInterval` function.
Comment: Please use an array literal: `phrase = ['Hello', 'there', 'this', 'will', 'show', 'a', 'different', 'message', 'depending', 'on', 'the', 'hour', 'of', 'day', 'that', 'you', 'look', 'at', 'it', '!', 'W', 'X', 'Y', 'Z'];` Much shorter than that array declaration there.
Comment: When I remove Show me a phrase for this hour this, it doesn't work anymore.
Answer: With a timer. This will refresh the phrase every second.
setInterval(function() {
    h = new Date().getHours(); //Get the current hour

    phrase = new Array(); //Create an array of phrases
    phrase[1] = 'Hello';
    phrase[2] = 'there';
    phrase[3] = 'this';
    phrase[4] = 'will';
    phrase[5] = 'show';
    phrase[6] = 'a';
    phrase[7] = 'different';
    phrase[8] = 'message';
    phrase[9] = 'depending';
    phrase[10] = 'on';
    phrase[11] = 'the';
    phrase[12] = 'hour';
    phrase[13] = 'of';
    phrase[14] = 'day';
    phrase[15] = 'that';
    phrase[16] = 'you';
    phrase[17] = 'look';
    phrase[18] = 'at';
    phrase[19] = 'it';
    phrase[20] = '!';
    phrase[21] = 'W';
    phrase[22] = 'X';
    phrase[23] = 'Y';
    phrase[24] = 'Z';

    document.getElementById('placeHolder').innerHTML = phrase[h-1]; //Show the array item relevant to the hour
}, 1000);

Comment: Wouldn't it be overkill to run that function every second?
Also, I'd suggest adding some info about array literal notation: `phrase = ['Hello', 'there', 'this', 'will', ...... 'X', 'Y', 'Z'];        `.
Comment: It depends on the precision with which you want the switch from one phrase to the next to occur. Once every second is not that much.
Answer: this will call after every hour
javascript
function getPhrase(){
    var h = new Date().getHours(); //Get the current hour
    var phrase = new Array(); //Create an array of phrases
    phrase = ['Hello', 'there', 'this', 'will', 'show', 'a', 'different', 'message', 'depending', 'on', 'the', 'hour', 'of', 'day', 'that', 'you', 'look', 'at', 'it', '!', 'W', 'X', 'Y', 'Z'];
    document.getElementById('placeHolder').innerHTML = phrase[h-1]; //Show the array item relevant to the hour
}

setInterval(getPhrase,60*60*1000);

remove the button
html

Display every hour another content


Maximizing Area given Lengths

Question:
Problem:
Given a sequence of $n$ lengths, $L_1,L_1,...,L_n$ where each $L_k$ is the length of the $k$th side, I need to find a sequence of $n$ points, where $p_k=(x_k,y_k)$, such that $\operatorname{dist}(p_k,k_{k+1})=L_k$ and where $\operatorname{dist}(a,b)$ is the Euclidean distance between $a$ and $b$. So they way the sequence goes, $p_1=(0,0)$ then $p_2=(0,L_1)$. The points must correspond to the ordered clockwise vertices of the simple polygon having the maximum possible area for the given side lengths.

For example, if we were given the lengths $1,1,1$, then obviously this is an equilateral triangle. And the maximum area is given by the coordinates, $(0,0),(0,1),(\sqrt{1-0.25},0.5)$.
Another example, if we were given the lengths $1,2,1,2$, then we would get a rectangle with coordinates $(0,0),(0,1),(2,1),(2,0)$.
How would I work this out for large $n$ or in general for every $n$? Because I cannot think of a way past the case of a square/rectangle.
Comment: For your four point example it is a rectangle, not a square.  I suspect the answer is to make the points all fit on a circle, but am just guessing.
Comment: @RossMillikan Yes rectangle. Hmm. I was thinking along those lines too.
Comment: This problem need $\sum {L_k}\geq 2L_x$by triangle inequality.
Comment: Same question. http://math.stackexchange.com/questions/115338/calculating-the-area-of-an-irregular-polygon
Answer: This proof was given here.
Take the polygon and arrange it so that all the vertices lie on a circle:

Now, "glue" the red caps onto the side of the polygon:

Note that the perimeter around the red caps stays constant as I move the vertices. The area of the red shaded sections also stay the same. According to the isoperimetric inequality, the area of the total shape (both the red and white sections) is maximized when the polygon is cyclic. Ergo, the area of the polygon is maximized when the polygon is cyclic.
Answer: Theorem: For given sidelengths, a cyclic polygon has maximal area.
Proof: Let $\{p_k\}_{k=1}^n$ be the vertices of the polygon.
Set $v_k=p_k-p_{k-1}$ and $m_k=\frac12(p_k+p_{k-1})$, where $p_0=p_n$.
Since the polygon is closed,
$$
\sum_{k=1}^nv_k=0\implies\sum_{k=1}^n\delta v_k=0\tag1
$$
Since the $|v_k|$ are given, for $1\le k\le n$,
$$
v_k\cdot\delta v_k=0\tag2
$$
The area of the polygon is
$$
A=\frac12\sum_{j\lt k}v_j^R\cdot v_k\tag3
$$
where $(x,y)^R=(y,-x)$. Therefore,
$$
\begin{align}
\delta A
&=\frac12\sum_{j\lt k}v_j^R\cdot\delta v_k-\frac12\sum_{j\gt k}v_j^R\cdot\delta v_k\\
&=\sum_{k=1}^n(m_k-p_0)^R\cdot\delta v_k\tag4
\end{align}
$$
To maximize $(3)$ under conditions $(1)$ and $(2)$, that is, to guarantee that $(4)$ vanishes when $(1)$ and $(2)$ hold, orthogonality requires that there be constants $\lambda_k$ and a point $p$ so that
$$
(m_k-p_0)^R=p+\lambda_kv_k\tag5
$$
In other words, with $c=p_0-p^R$
$$
(m_k-c)\cdot v_k=0\tag6
$$
which translates to
$$
|p_k-c|^2=|p_{k-1}-c|^2\tag7
$$
Thus, all $p_k$ lie on a circle with center $c$.
$\large\square$
Answer: In general, if $A_1 A_2\ldots A_n$ is a $n$-sided polygon and the lengths $l_1,l_2,\ldots,l_{n-1},l_n$ of $A_1 A_2,A_2 A_3,\ldots,A_{n-1} A_n, A_n A_1$ are fixed, the maximum area is achieved by the cyclic polygon, i.e. the polygon having all its vertices on a circle. You may easily prove this fact through Lagrange multipliers or Steiner's symmetrization method. It is an istance of the isoperimetric inequality for polygons, that can be used to prove the usual isoperimetric inequality in the plane through a limit process.
Answer: About convex or concave, it's obviously convex polygon. By repeating this work, we get theorem which area of quadrilateral is max iff four points are on a circle. By using this theorem repeatedly, iff all points are on a circle, we get the area can be max.
When $L_k $ is on a plane of radius R, S is max.
If angle of chord L_k is $a_k$,
$$\displaystyle sin{\frac{a_k}2}=\frac{L_k}{2R}$$
$$\displaystyle\sum a_k=2\sum sin^{-1}{\frac{L_k}{2R}}=2\pi$$
$\displaystyle\sum \frac{L_k}{2R}\sqrt{1-(\frac{L_k}{2R})^2}=2\prod\frac{L_k}{2R}\tag1$
we get R by solving (1). therefore
$$S=\displaystyle\sum S_k=\sum \frac{RL_k}{2\sqrt{1-(\frac{L_k}{2R})^2}}$$
equation of (1) by https://in.answers.yahoo.com/question/index?qid=20140526080730AASjOAI
Comment: Sorry, but what is $S$?
Comment: S is area which is covered with $\sum l_k$.
Comment: So can you tell me or give an example how this would give me the answer to my example above

Maximizing Area given Lengths


A question regarding the comparison test for a particular series

Question: I came across this question and was able to get the right answer using the comparison the first time around, however a friend of mine solved it also using the comparison test but in a slightly different way and got a different answer. I'm unable to see how their answer is any wrong
We are asked to check the convergence of the following series
$$\sum_{n=1}^\infty \frac{1}{n(n+1)}$$
I took the n-th term of this series to be $u_n=\frac{1}{n(n+1)}$ and $v_n=\frac{1}{n^2}$
$$\lim\limits_{n \to \infty} \frac{u_n}{v_n} = \lim\limits_{n \to \infty} \frac{1}{1+\frac{1}{n}} =1(finite)$$
Which implies that $u_n$ and $v_n$ must converge or diverge together
Now let $w_n= \frac{1}{n}$
$$\lim\limits_{n \to \infty} \frac{u_n}{w_n} = \lim\limits_{n \to \infty} \frac{1}{n+1} =0(finite)$$
Hence $u_n$ and $w_n$ must also either converge or diverge together
However, $v_n$ converges while $w_n$ diverges which leads to a contradiction
Comment: $0$ must be excluded. In fact, if you would have chosen $\frac{w_n}{u_n}$ , the limit would not have been finite.
Answer: The first part is of course correct, however, the reason for why the second part is not, is because $c$ - the limit of the ratio - has to be strictly positive. To elaborate on @Peter's comment, the limit comparison test is symetric, in the sense that both series ($a_n,b_n$) either converge or diverge together. So if the limit test works for $a_n/b_n$, then it should also work for $b_n/a_n$. And in your case, $w_n/u_n=n+1$ diverges.