Can I install php8.0 on Ubutnu 16.04

Question: I'm trying to install php8 on Ubuntu 16.04.5 LTS.
Here is the list of commands and output that I ran:
apt-get update
apt install software-properties-common

--- these commands went fine when ran
add-apt-repository ppa:ondrej/php
output:
 Co-installable PHP versions: PHP 5.6, PHP 7.x and most requested extensions are included. Only Supported Versions of PHP (http://php.net/supported-versions.php) for Supported Ubuntu Releases (https://wiki.ubuntu.com/Releases) are provided. Don't ask for end-of-life PHP versions or Ubuntu release, they won't be provided.

Debian oldstable and stable packages are provided as well: https://deb.sury.org/#debian-dpa

You can get more information about the packages at https://deb.sury.org

IMPORTANT: The <foo>-backports is now required on older Ubuntu releases.

BUGS&FEATURES: This PPA now has a issue tracker:
https://deb.sury.org/#bug-reporting

CAVEATS:
1. If you are using php-gearman, you need to add ppa:ondrej/pkg-gearman
2. If you are using apache2, you are advised to add ppa:ondrej/apache2
3. If you are using nginx, you are advised to add ppa:ondrej/nginx-mainline
   or ppa:ondrej/nginx

PLEASE READ: If you like my work and want to give me a little motivation, please consider donating regularly: https://donate.sury.org/

WARNING: add-apt-repository is broken with non-UTF-8 locales, see
https://github.com/oerdnj/deb.sury.org/issues/56 for workaround:

# LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php
 More info: https://launchpad.net/~ondrej/+archive/ubuntu/php
Press [ENTER] to continue or ctrl-c to cancel adding it

gpg: keyring `/tmp/tmpw60tb7ap/secring.gpg' created
gpg: keyring `/tmp/tmpw60tb7ap/pubring.gpg' created
gpg: requesting key E5267A6C from hkp server keyserver.ubuntu.com
gpg: /tmp/tmpw60tb7ap/trustdb.gpg: trustdb created
gpg: key E5267A6C: public key "Launchpad PPA for Ondřej Surý" imported
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)
OK

apt update
output:
Hit:1 http://ppa.launchpad.net/nginx/stable/ubuntu xenial InRelease
Hit:2 http://ppa.launchpad.net/ondrej/php/ubuntu xenial InRelease
Hit:3 http://eu-west-2.ec2.archive.ubuntu.com/ubuntu xenial InRelease
Hit:4 http://eu-west-2.ec2.archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:5 http://eu-west-2.ec2.archive.ubuntu.com/ubuntu xenial-backports InRelease
Ign:6 https://packages.sury.org/php xenial InRelease
Err:7 https://packages.sury.org/php xenial Release
  404  Not Found
Get:8 http://security.ubuntu.com/ubuntu xenial-security InRelease [109 kB]
Hit:9 http://repo.zabbix.com/zabbix/3.4/ubuntu xenial InRelease
Hit:10 https://packagecloud.io/phalcon/stable/ubuntu xenial InRelease
Reading package lists... Done
E: The repository 'https://packages.sury.org/php xenial Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

After that while, I tried to install php8.0-fpm I got the following:
apt install php8-fpm

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php8-fpm

Also:
apt install php8.0-fpm

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php8.0-fpm
E: Couldn't find any package by glob 'php8.0-fpm'
E: Couldn't find any package by regex 'php8.0-fpm'

Answer: They did explicitly warn you in the output you posted above:

Only Supported Versions of PHP (http://php.net/supported-versions.php) for Supported Ubuntu Releases (https://wiki.ubuntu.com/Releases) are provided. Don't ask for end-of-life PHP versions or Ubuntu release, they won't be provided.

You should not be running 16.04 as it has passed end of life. Upgrade first to a currently supported Ubuntu release, and then you will be able to install PHP 8.0.
Comment: Ubuntu 16.04 is a LTS release, official end-of-life is April 2026 ( as per https://wiki.ubuntu.com/Releases ) so it does not explain why php8.0 is not available for that specific release.
Comment: @Crimbo I believe I did that already (a year ago or so), since activation of the ESM can be done using the *Register for personnal use* option. Maybe the "Pro" option is more complete but I doubt that.
Anyway, I have found a ppa to get PHP 7.4 on Ubuntu 16.04, event though it's pretty late. 7.4 is good enough for now for me: `ppa:jczaplicki/xenial-php74-temp`
Comment: @Ultraspider 100%. I've got php8.0 installed on my Ubuntu 16.04 server - I think due to applying for [ESM](https://ubuntu.com/security/esm)
Comment: thank you for the answer, I wanted to have it clear.
Comment: @Crimbo Hi, could you describe what you precisely enabled in the ESM to get PHP in Ubuntu 16.04 ??
I am using Ubuntu 16.04 and really need to upgrade PHP to the most recent version possible.
Thank you in advance for your answer ;) !
Comment: @YoannPageaud It looks like they have changed it since I enabled ESM. ESM is now a part of Ubuntu Pro, which you have to sign up to https://ubuntu.com/pro. Once you have signed up, you then [attach your subscription](https://ubuntu.com/server/docs/install/subscription)
Comment: Ar ok. Well my ESM seemed to stop working, I guess when they merged it with Ubuntu Pro
Answer: Xenial (Ubuntu 16) is only in standard support until 2021. After that, there is only extended security-only support. Which means your server is 'on life support' so to speak.
So extended-security support is meant to keep a server alive, not to update it with new features and new software.
Extended security support (ESM, or maybe called Ubuntu Pro these days) is a sort of 'paid for' support option. You can get it free for a limited number of installations, though. But it clearly 'is not for everyone'.
Ondrej (the maintainer of that PPA repository with PHP versions for Ubuntu) does not want to support versions that are outside standard support, which sounds perfectly fine by the way.
So you can't download any Xenial packages anymore, because he removed them. Maybe someone still has a Xenial server running with his php8.0 packages on there, but those packages will not be updated, so you are just as safe as to compile your own version from source if you need to run it.
These are the negatives about opting in for extended support programs. Yes, you receive security updates for something that would otherwise be out of life. But you should not think that your server is then 'just fine the way it is' with ESM. All around the Ubuntu community and other commercial packages, you will see Xenial support being dropped, even if you still have ESM for years to come.
So use ESM only as a means to postpone an upgrade if you really have to, but do not let it stick around it for years.

Can I install php8.0 on Ubutnu 16.04


What are the mechanics behind singing a "split note"?

Question: I'm interested in the mechanics behind producing a certain vocal sound. You can hear it clearly in the vocal track for "Smells Like Teen Spirit", on the word "well", as well as "here we are now" in the chorus.

I have also been able to sing this sound, though I don't have much control over it.  Granted, I'm not a singer.
https://vocaroo.com/1m1nZ85pSsGO
I am calling this a split note because I've heard it called that before, but I'm not sure that's the correct terminology (and I can't really find anything on google with this term).
If you look at the spectrum for this sound, extra tones appear between the harmonics of the note, as if they were harmonics for a note an octave down.  They are visible here, especially between the first few harmonics:
Clean Note

Split Note

Melodyne also detects these notes as being an octave lower than they actually sound:

What's actually happening to produce this sound?
Comment: In my opinion this is mixing normal voice with vocal fry register https://en.wikipedia.org/wiki/Vocal_fry_register Various teachers may use various other names. It seems to produce a note an octave below the normally singed note, and some bass singers use it on a regular basis. At this time I cannot however explain the mechanics behind it.
Comment: Check out *Lalah Hathaway* properly singing a two-note chord, singing with Snarky Puppy: https://youtu.be/0SJIgTLe0hc?t=373
Comment: Be aware that the vocals are double tracked and what you hear and what comes from the analyzer are not 100% generated by singing technique.
Comment: @ToddWilcox The analysis is of my own vocals.  Single tracked, no effects.
Comment: @Morris (Again,) The analysis is of my own vocals. Single tracked, no effects.  Also, perhaps you should vet your references more.  I agree that parts are double tracked, since I can hear it, but that link cited a reddit comment for the date the band formed.  That's not a sign of a reputable article.
Comment: @user1079505 Although when bass singers do it to hit extreme low notes, they aim to make the interference pattern between the vocal fry and the normal voice much cleaner, giving it a wildly different effect than this example.
Comment: I'd also agree that you're hearing the subtle effects of double-tracking.  According to this reference, it seems the producer (Butch Vig) did indeed double-track Kurt's vocals: https://sholamusicl3.wordpress.com/2016/12/12/nirvana-smells-like-teen-spirit/
Comment: @Edward Sorry, I was responding to your question and opening statement, not your analysis, which is based on a false premise about the voice in the Nirvana track.
Comment: I linked the Nirvana track because I think it's a clear example of the sound of a "split note".  The question isn't about that specific example, I just don't know of a better example to put.
Comment: There are conditions where an object can resonate at half its fundamental frequency. Also refered to as undertones. Maybe this is related. See also https://youtu.be/o4jgPdGrZYI
Comment: @KrisVanBael I've seen that video before, but actually the comment section of that video is a lead.  Found [this interesting video](https://www.youtube.com/watch?v=DbKJ2E7YCNg) which is related.  But like most videos on voice, the physiology is not exactly covered because singers sing more by feel.
Comment: My guess is that it's sympathetic vibration of the vestibular folds, aka false cords.  https://teachmeanatomy.info/neck/viscera/larynx/ligaments-folds/
Answer: There are a few ways to answer this, but the spoiler is that it's all about overtones.
For the example from Smells Like Teen Spirit:
"Here we are now" sounds like a chorus effect to me on top of multitracking, which was (and still is) a common way to give vocals a thicker sound.
A chorus typically delays the input sound by an oscillating amount of time (via LFO), then feeds the delayed output sound back at the same time as the input sound. What I think you are hearing there is that the pitch increases slightly when the delay time is decreased and drops slightly as the delay time is increased. This slightly different pitch played on top of the fundamental gives a slightly "thicker" quality to the sound. We are hearing small differences in the fundamental tone AND small differences in the overtones at the same time, which makes the "split" sound more prominent.
However, I don't think all of the "split sound" is due to chorus effects. There are some vocal aspects to that too, like in your demo. So how do you sing so as to intentionally produce that split sound? The answer is overtones.
Without a physics lesson, overtones are are harmonics that also include non-integer multiples of the fundamental. For the sake of understanding, compare the sound of a saxophone to the sound of an ocarina. The ocarina is pretty close to a pure tone instrument (ie, very little audible overtone sound), while the saxophone has a lot of overtones. Organ players might have an even more intuitive grasp on what overtones sound like because stops tend to mess around with the balance of overtones in a particular sound. In general, more overtones means a "grittier" and more complex sound (think saxophone vs ocarina).
Fun fact, the primary thing you hear changing when vowel sounds change is the strength of various overtones (we usually call the peaks in amplitude at particular frequencies "formants"). Tuvan throat singing, technically called "Polyphonic Overtone Singing", is a technique where vocalists have learned to emphasize overtones MORE than the fundamental note (mostly by changing vowel shapes), and it sounds awesome. That would technically be a kind of "split note" as they are literally singing multiple distinctly audible notes at the same time.
Though all that context is relevant, the direct answer to your question "How do I sing a split note" boils down to this: add more overtones to your singing.
There are quite a few ways to do this vocally. I'll outline a few of them:
-You know that angry sort of growly "HUMMMPH!" sound that people make when they are frustrated? This sound often comes out with some emphasized overtones (you'll hear multiple notes at once). When I tried it, my little baby girl just did it next to me and showed me that she could do it too. This is a great starting point to determine what your vocal instrument needs to do to produce a "split sound" as you called it (ie, produce and emphasize more overtones).
-Growling adds overtones to your sound and can give that "split tone" sound. There are some good tutorials on growling while singing without hurting yourself by rock stars out there.
-You can play with the balance of overtones by changing vowel sounds, pushing more air without changing throat positions, and by pushing the sound deeper into your chest or further into your nose (which is an intuitive way of talking about changing the shape of your vocal instrument at various points).
-For guys more than gals, one way to learn how this might feel is to find a place where your break to falsetto naturally occurs, then try to sing both sides of the break at the same time. You'll sound like a boy going through puberty, but if you can get them at the same time you'll get a somewhat obnoxious growling harmonic sort of noise. In my experience, some people have a hard time finding this spot, so don't be frustrated if you can't find it right away.
PS -- I'm a male vocalist, so these things might apply a little differently for female vocalists.
Comment: My question is not "How do I sing a split note" but "What are the mechanics behind singing a 'split note'?"  "What's actually happening to produce this sound?"  I know that overtones are being added, I can see them in the spectrum visualization.  But what is the physical mechanism- what is happening with the vocal cords and related structures- that produces these overtones?
Comment: Ah! My answer was far too basic compared to what you were looking for. You might be able to get insight by playing with a throat modeling tool [like this one](https://www.antarestech.com/product/throat/) and maybe a vowel shaping tool [like this one](https://willsavin.com/software/plugins/vowel-filter/) and then analyzing the overtones. My guess is that the split tone noise you are looking for comes from forcing the vibrating parts of the vocal folds into a harmonic standing wave position.


reading json hierarchy in php

Question: I am trying to map a json file to a mysql database with the following json file:
configurationItems":[
  {
     "configurationItemVersion":"1.0",
     "configurationItemCaptureTime":"2014-12-05T10:22:51.751Z",
     "configurationStateId":1,
     "relatedEvents":[  ],
     "awsAccountId":"a value",
     "configurationItemStatus":"ResourceDiscovered",
     "resourceId":"some resource",
     "ARN":"blah blah",
     "awsRegion":"us-east-1",
     "availabilityZone":"us-east-1b",
     "configurationStateMd5Hash":"string",
     "resourceType":"AWS::EC2::Instance",
     "resourceCreationTime":"2014-01-06T10:37:37.000Z",
     "tags":{  },
     "relationships":[  ],
     "configuration":{
        "instanceId":"",
        "imageId":"",
        "state":{  },
        "privateDnsName":"",
        "publicDnsName":"",
        "stateTransitionReason":"
        "keyName":"production-us",
        "amiLaunchIndex":0,
        "productCodes":[  ],
        "instanceType":"m2.xlarge",
        "launchTime":"ts",
        "placement":{  },
        "kernelId":"1",
        "monitoring":{  },
        "subnetId":"",
        "vpcId":"",
        "privateIpAddress":"",
        "stateReason":{  },
        "architecture":",
        "rootDeviceType":"",
        "rootDeviceName":"",
        "blockDeviceMappings":[
           {
              "deviceName":"namr",
              "ebs":{
                 "volumeId":"vol-eb90e1a6",
                 "status":"attached",
                 "attachTime":"2014-01-06T10:37:40.000Z",
                 "deleteOnTermination":true
              }
           }
        ],
        "virtualization

the way in which I have been accessing using php is as follows
$value_wanted=$parent["child1"]["child2"]["value"];

I am having a problem accessing blockDeviceMappings device name as using my theory which has worked up until now it would be
  $deviceName=$configurationItems["configuration"]["blockDeviceMappings"]    ["deviceName"];

I have tried
    $deviceName=$configurationItems["configuration"]["blockDeviceMappings"]   [""]["deviceName"];

but that does not work either its really the empty bracket that I think is throwing me any advice is always appreciated.
Comment: $deviceName=$configurationItems["configuration"]["blockDeviceMappings"]   [0]["deviceName"];
Answer: blockDeviceMappings is an array of objects. If it always has only one item (as shown):
$deviceName=$configurationItems["configuration"]["blockDeviceMappings"][0]["deviceName"];

else you will need to iterate the array:
foreach($configurationItems["configuration"]["blockDeviceMappings"] as $mapping)
    echo $mapping['deviceName'];

EDIT as per your comment, ebs is a sibling of deviceName not a decendent.
The correct way to access volumeId it would be:
$deviceName=$configurationItems["configuration"]["blockDeviceMappings"][0]["ebs"]["volumeId"];

Comment: many thanks for your answer the json is as shown and solution 1 worked however when I try and put volumeId into my ebs table I get an error of illegal string offset ebs using '$volumeId=$configurationItems["configuration"]["blockDeviceMappings"] [0]["deviceName"]["ebs"]["volumeId"];' any ideas ?
Comment: worked it out thanks its always the daft things appreciate the help

reading json hierarchy in php


Probability of intersecting three chords

Question: Three chords are drawn randomly and uniformly in a circle. Here each chord is established using random end point method, i.e. the endpoints of any chord are two points chosen randomly, uniformity and independently on the circumference of the circle. Now  what is the probability that they intersect at a single point?
In the case of two chords,  it is easy to find the probability of intersecting using symmetry of the circle. But It gets tricky when it comes to three or more chords.
Can a generalized formula be obtained for N number of chords?
*edited
Comment: Firstly, "random chord" needs to be defined precisely. There are various possible meanings. But in any case, for any of those meanings, it should be obvious that the probability of a triple intersection is $0$. Intersect the first two. If that succeeds, the third one has to _hit_ that exact point$\,-\,$without aiming (since it's a random chord).
Comment: The probability is zero.
Comment: zero, surely???
Comment: Maybe they wanted to know the probability that the three chords intersect in three points.
Answer: In the following I'm going to compute the probability that any two of the three cords intersect. This event only depends on the order of the six endpoints $P_i$ $(0\leq i\leq5)$ on the circle. Assume that the chords connect $P_i$ with  $P_{i+3}$. The probability that $P_3$ is opposite $P_0$ in the appearing order is ${1\over5}$. Conditioned on this to be the case the probability that $P_4$ is opposite $P_1$ is ${1\over3}$, and if this is true as well $P_2$ and $P_5$ are automatically in opposition. The probability we are after therefore is ${1\over15}$.
Answer: At any rate your problem seems to be finding the set $\hat C\subset\Omega$ corresponding to segments intersecting the positive $y$-axis as well as the negative $x$-axis.
Let $e^{i\phi_1}$ and $e^{i\phi_2}$ be two points on the unit circle. Then $C$ occurs iff $$0<\phi_1<{\pi\over2}\qquad\wedge\qquad \pi<\phi_2<{3\pi\over2}\qquad\wedge\qquad \phi_2-\phi_1<\pi\ ,\tag{1}$$
or $(1)$ with $\phi_1$ and $\phi_2$ interchanged. The conditions $(1)$ together with their counterparts obtained by $\phi_1\leftrightarrow \phi_2$ define two small triangles in $\Omega$ of area ${1\over32}$ each (draw a figure!). It follows that the probability of $C$ comes to $2\cdot{1\over32}={1\over16}$.
Now try to generalize for your attempt.


Manipular registros de uma array php

Question: Possuo uma consulta no banco que me retorna os registros em uma array, gostaria de saber como faço para manipular estes registros, tira-los da array.
Código
$array = MinPDO::consult("intro", NULL, "id > 1", "id-", "3", "%e%");

var_dump($array);

Registros
array(3) { [0]=> array(3) { ["id"]=> int(3) ["param1"]=> string(5) "ele01" ["param2"]=> string(6) "param2" } [1]=> array(3) { ["id"]=> int(2) ["param1"]=> string(5) "ele01" ["param2"]=> string(6) "param2" } [2]=> array(3) { ["id"]=> int(1) ["param1"]=> string(5) "ele01" ["param2"]=> string(6) "param2" } }

Comment: Onde você quer manipular na view ou no próprio código php?
Comment: Para acessar alguma valor vc pode fazer `$array[0]['param1']`
Comment: Na view e no própio código também.
Answer:
Pode usar o foreach para isso segue abaixo um exemplo

foreach($array as $info) {
    echo $info['id']." - ".$info['param2']."
";
}

Tem o for também porem o foreach é melhor

for($i = 0; $i < count($array); $i++) {
    echo $array[$i]['id']." - ".$array[$i]['param2']."
";
}

Manipular registros de uma array php


getting the import spring libraries wrong when creating a new project from a creted archetype

Question: i had created an archetype from an existing project with the command mvn archetype:create-from-project.
everything worked fine.
i installed and deployed it too.
the problem exists when creating a new project from this archetype.
it converts every "framework" word with the artifactid of the created project.
for example if the artifactid is "test", i get this:
<code> import org.springtest.security.core.Authentication;
</code>
the reason is that in the created archetype files i found it written like this:
<code>     import org.spring${artifactId}.security.core.Authentication;
</code>
My questions: is there a way or some files i should configure to stop replacing the "framework" word with the artifcatid ??
thanks in advance.
Answer: i found the answer.
in the created archetype you will find the next lines written at the top of any java class:
<code>   #set( $symbol_pound = '#' )
   #set( $symbol_dollar = '$' )
   #set( $symbol_escape = '\' )
</code>
so just add the following line to them.only once at any java class of the archetype.
<code>   #set($artifactId = "framework")
</code>
note that you can do the same thing with groupid and package.


Delete Duplicate in I$ table in ODI

Question: We have a load plan in ODI. We get a repeating error in some on our scenarios due to duplicate records in the I% table. What we do is manually run the script every time the load plan fails.
DELETE FROM adw12_dw. I$_1558911580_4
      WHERE     (EFFECTIVE_FROM_DT, DATASOURCE_NUM_ID, INTEGRATION_ID) IN
                    (  SELECT EFFECTIVE_FROM_DT,
                              DATASOURCE_NUM_ID,
                              INTEGRATION_ID
                         FROM adw12_dw . I$_1558911580_4
                     GROUP BY EFFECTIVE_FROM_DT,
                              DATASOURCE_NUM_ID,
                              INTEGRATION_ID
                       HAVING COUNT (1) > 1)
            AND ROWID NOT IN
                    (  SELECT MIN (ROWID)
                         FROM adw12_dw . I$_1558911580_4
                     GROUP BY EFFECTIVE_FROM_DT,
                              DATASOURCE_NUM_ID,
                              INTEGRATION_ID
                       HAVING COUNT (1) > 1)

                commit;

Is there a way to automate the deletion of duplicate records in the Integration table?
Comment: It's difficult to tell without seeing the mapping. These duplicates come from the source I guess? What is the mapping logic? What is the IKM used and what is the loading strategy?
Answer: If you have duplicates in the source, best would be to handle that in the logic of the mapping.
What could work is to add an expression component to add a row_rank column using an analytical function to rank the duplicates : row_number() over (partition by EFFECTIVE_FROM_DT, DATASOURCE_NUM_ID, INTEGRATION_ID order by ROWID).
You can then add a filter with the condition row_rank = 1.
If you prefer to do a delete after inserting, you can edit the IKM and add the delete step before loading the target table.
You could also divide the integration in 3 different steps :

a mapping that would load a staging table instead of your final target table, with the duplicate
an ODI procedure that would perform the delete to remove the duplicates in the staging table
a mapping that would load the data from the staging area to the target table
Comment: Thank you so much @JeromeFR , very much appreciated!
Answer: Maybe your duplicate counts over 2 because we must execute the delete query recursively. For example:
CREATE OR REPLACE PROCEDURE delete_dublicates
IS
BEGIN
    DELETE FROM TABLE1 WHERE ID IN
        (
            SELECT max(ID) FROM TABLE1
            GROUP BY USER_ID, TYPE_ID
            HAVING count(*) > 1
        );

    IF (SQL%ROWCOUNT > 0) THEN
        delete_dublicates;
    END IF;

END delete_dublicates;

Delete Duplicate in I$ table in ODI


Websphere 7: Getting 'Internal Server Error' when accessing JSPs. Servlets ok

Question: I have just installed WS 7 on our stage server. The test server was done some months ago. I have deployed the same applications to stage as on test.
One application is causing me problems. I call the login servlet but the result is an 'Internal Server Error' message. From my logs I can see that the servlet processed the log in successfully and redirects to a JSP. That is the last message. I can find no further info in any of the other standard out/err logs.
I have tried creating a simple JSP containing only HTML - same error. If I rename the file to test.html, it displays correctly. The plugin configuration appears to be identical with the one on the test server (where everything works)
Ideas anyone?
Answer: Problem is now solved.
The installation process created a default server. I had ignored this thinking that it doesn't matter. I removed the server and regenerated the plug-in config and my app works fine.


How can I find a norm of a linear transformation $T(x,y) = (ax+cy, bx+dy)$?

Question: Let a linear transformation $T : \mathbb{C}^2 \to \mathbb{C}^2$ s.t
$T(x,y) = (ax+cy, bx+dy)$
where $a,b,c,d \in \mathbb{C}$.
Now, find the norm of T equipped with ($\mathbb{C}^2$ , $l^1(\{1,2\})$ norm),  ($\mathbb{C}^2$ , $l^{\infty}(\{1,2\})$ norm) each.
--
I tried it several ways, using $z=a + bi$ of $z=r_1e^{\theta_1}$ and etc.
However, since a,b,c,d,x,y are all complex, finding maximizing condition with
$|ax+by|, |cx+dy|$ is too hard.
(radius and argument of x and y can change. so it has too many changing variables. also, computing $|ax+by| + |cx+dy|$ or max$(|ax+by|, |cx+dy|)$ requires $$\big|\sqrt{(ax+by)^2}\big|$$
Is there any method to compute the norm?
Answer: It seems the following.
Surprisingly, the answers turned out very similar.
$\ell^1$-norm.
$$\|(x,y)\|=|x|+|y|.$$
$$\|T(x,y)\|= \|(ax+cy,bx+dy)\|=| ax+cy |+|bx+dy|\le$$ $$|ax|+|cy|+|bx|+|dy|=|a||x|+|c||y|+|b||x|+|d||y|=
(|a|+|b|)|x|+(|c|+|d|)|y|\le$$ $$ \max\{|a|+|b|,|c|+|d|\}(|x|+|y|)=\max\{|a|+|b|,|c|+|d|\}\|(x,y)\|.$$
From the other side, if $|a|+|b|\le |c|+|d|$ and $x=0$ then $$\|T(x,y)\|= \|(cy,dy)\|=|cy|+|dy|=|c||y|+|d||y|=(|c|+|d|)|y|=(|c|+|d|)\|(x,y)\|.$$
A case $|a|+|b|>|c|+|d|$ is considered similarly. Thus
$$\|T\|=\max\{|a|+|b|,|c|+|d|\}.$$
$\ell^\infty$-norm.
$$\|(x,y)\|=\max\{|x|,|y|\}.$$
$$\|T(x,y)\|= \|(ax+cy,bx+dy)\|=\max\{| ax+cy |,|bx+dy|\}\le$$ $$\max\{| ax|+|cy |,|bx|+|dy|\}=
\max\{| a||x|+|c||y |,|b||x|+|d||y|\}\le$$ $$\max\{| a|+|c|,|b|+|d|\}\max\{|x|,|y|\}.$$
From the other side, if $|a|+|c|\le |b|+|d|$ and $x=y$ then $$\|T(x,y)\|= \|(a+c)y,(b+d)y)\|=
\max\{|(a+c)y|,|(b+d)y)|\}=$$ $$\max\{|a+c||y|,|b+d||y|\}=|b+d||y|=|b+d|\|(x,y)\|.$$
A case $|a|+|c|>|b|+|d|$ is considered similarly. Thus
$$\|T\|=\max\{|a|+|c|,|b|+|d|\}.$$


How to access my deployed mvc project?

Question: I just deployed an mvc project to our testing server. During development, my project was auto-deployed into the local IIS Express and could be reached in
http://localhost:62599/api/

I uploaded the project files on machine "server03" in IIS7's "deploymenttest" site, subfolder "api", and now I try to call the project from my browser, only receiving 404s or 403s.
Which URL does the project have now?
Comment: The URL must be `http://server03/api/`, where after `server03` you'll want the port if you changed it (e.g. `server03:4567/`), and between hsot and `/api/` you'll want the application directory if you moved the application in one, like `deploymenttest`. Your final URL may look like `http://server03:4567/deploymenttest/`. You can just click 'Browse' from IIS though.
Comment: possible duplicate of [Install MVC website on IIS7](http://stackoverflow.com/questions/10381016/install-mvc-website-on-iis7)
Comment: When I click 'Browse' from IIS, the main page (HTML/JS) in the root dir is opened. The mvc application in the api folder isn't touched in any way.
Comment: But you're asking for your site's URL. You have it. If you have an actual error when accessing that URL + `/api/`, see the question I linked as duplicate for troubleshooting.
Answer: when you deploy an mvc project  into IIS, make sure following

You copied all the Views(with their directory structure) and the bin folder to the location, you have pointed in your IIS website or Virtual Directory. Also do note that, sometimes Visual Studio Publish, doesn't publish all the required dependencies.Besides, you don't need to copy any of your .cs  files to the deployment.
your web.config has following in its system.WebServer
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" />

your IIS module has UrlRouting module.(goto IIS, select your application on the left, then in the IIS section in the right, look for Modules icon and double click, and see if UrlRouting4.0 or something like that exists)
Also make sure, depending on the dot net version of your app, your IIS supports that version. Simple way to find that out, is to go in the IIS manager, go to ApplicationPools, edit any pool and see in the dropdown, what options are available. .NET Framework v4.0.30319 is for DOT NET Version 4.5

additionally, if you want to install ASP.NET support for your IIS, go to Turn Windows Feature On and Off and select everything that is inside the Node "Internet Information Services".
Comment: This partially answers _"How to set up IIS for ASP.NET MVC?"_, while the question at hand is: _"What is the URL for a site deployed in IIS?"_.
Comment: I can't find UrlRouting in the modules list, and I can't find it under "Add module..."
Comment: in that case, you need to register asp.net to your IIS. run this command in Visual Studio command prompt `aspnet_regiis -i`
Comment: And now I have to find out how to add .NET 3.5 or higher to IIS7. :)
Comment: God, no, that's not fair. anyways @Alexander, simply select your application in IIS, right click>>manage website>>Browse.
Comment: @CodeCaster, if you could read the comments, there is no UrlRouting module in his IIS, so even if he would have worked out the url, he would have ended up for this answer, in that case, i think, i should be upvoted, twice
Comment: That was just a guess from your side. You can't copy paste the ASP.NET MVC setup FAQ on every MVC question in the hope one of the steps solves the problem at hand.
Comment: hey, @CodeCaster, bad day? anyways, you are guessing now. I spent two days, figuring out why my MVC 4.0 project works when fired through Visual Studio but not when through IIS. Setting up IIS took me 20minutes, but the fact that some of the dependencies were missing, cause I was publishing my webproject through visual studio, took me 1.5days. I don't care, what pissed you off, but it is not standard MVC setup FAQ
Comment: @CodeCaster if you think this answer does not cover my question, then please tell me the URL where I can access my project. FYI: I did everything as described in http://msdn.microsoft.com/en-us/library/dd410407%28v=vs.90%29.aspx
Comment: @Alexander. right click your application in iis, goto manage and click Browse.
Comment: @Alexander see my two comments on your question.
Comment: @CodeCaster downvote, typically means, misleading answer or wrong answer. Besides I preferred, minimum steps and not all-the-possible steps(one google search) to lead him in right direction. (Won't let the glory of my typing and formatting in numbered list go away...i didn't copy, didn't even see whether is it a possible duplicate :D)

How to access my deployed mvc project?


What assumptions are require for convergence in probability or almost sure convergence here?

Question: Let $H_1$ , $H_2$, . . . be sequence of independent Bernoulli coin tosses, with
probability $p_n$, with $p_n$ → 0, as n → ∞, so that
$H_n$ = 1 with probability $p_n$
$H_n$ = 0 with probability $1-p_n$
Does $H_n$ converge in probability to 0? Does $H_n$ almost surely convergence to 0?
Make specific assumptions for $p_n$ for both, if necessary.
My attempt:
I have found that $H_n$ does converge in probability to 0, and does not almost surely converge to 0. However, what specific assumptions are required for these to hold?
Answer: I don't think you need any assumptions to show convergence in probability beyond those already stated.
Whether you have almost sure convergence would be determined by whether the probabilities satisfy the condition of the Borel-Cantelli lemma. (By the second Borel-Cantelli lemma, this is both a necessary and sufficient condition, because your random variables are independent.)


Ordinals and Countability

Question: I've been watching Prof Su's (Harvey Mudd College) incredible lecture on Ordinals and Transfinite Induction, and I have a few related questions. He starts by drawing and examining three sets of dots, strictly well-ordered by position ($> \implies \text{to the right of}$), where clustered dots represent carrying on adding dots forever:
(a) $\{\cdot \cdot \cdot \ \cdot \}$
(b) $\{ \cdot \cdot \cdot \cdot \cdot \cdot \cdot \cdots$ } ($\mathbb{N}$)
(c) $\{ \cdot \cdot \cdot \cdot \cdot \cdot \cdot \cdots \ \cdot \cdot \cdot \cdot \cdot \cdot \cdot \cdots \ \cdot \cdot \ \cdot \}$ (2 sets of $\mathbb{N}$ + 3 other things to the right)
He then notes that there are finitely many things in (a) and countably many things in both (b) and (c). Therefor (b) and (c) have the same cardinality. My first question is how can we say that (c) is countably infinite? Isn't the definition of a countable set a set that can be put in to bijection with some subset of (or the entirety of) $\mathbb{N}$? I get how that's true for (b), but what bijection could you use for (c) that would map every element of (c) to an element of the $\mathbb{N}$, and preserve distinctness? Wouldn't you run out of places to map things to after the first set of dots?
Next he constructs the ordinal numbers as a way to classify well-ordered sets. An ordinal is defined to be a set that is:
(i) transitive/complete - every member is a subset, and
(ii) strictly well ordered by membership
We start off with $\phi$ (the empty set, which is vacuously well-ordered) and define, the Successor function:
$$ S(\alpha) = \alpha \ \cup \ \{ \alpha \},  $$
which ensures that $S(\alpha)$ will satisfy (i) and (ii) if $\alpha$ does, and helps us to define the "next" few ordinals:
$$ \{ \phi \}, \ \{ \phi, \{\phi \} \}, \ \{ \phi, \{\phi \}, \{ \phi, \{\phi \} \} \}, \ \dots $$
We can also define the Supremum function for a set set of ordinals, A:
$$ \sup(A) = \bigcup\limits_{i} a_{i}, \ a_{i} \in A $$
If A is a collection of ordinals, then $\sup(A)$ is also an ordinal
We can then start assign labels to ordinals:
$$ "0" \to \phi, \ "1" \to \{ \phi \}, \ "2" \to \{ \phi, \{\phi \} \}, $$ etc.
He then introduces a theorem by Von-Neumann:

Thm. Any well-ordered set is order isomorphic to one of the ordinals

e.g. (a) is order isomorphic to "4".
He then goes on to say that $\mathbb{N}$ is order isomorphic to the supremum of the successor of all the finite ordinals, which we call $\omega$:
$$ \omega \equiv \sup( \ S(\alpha): |\alpha|<\infty) $$
This is said to be a limit ordinal and the first infinite ordinal. It is also the first ordinal that is not a successor of any ordinal. From there, we can continue to take the Successor:
$$ S(\omega) = \omega \cup \{ \omega \} \to "\omega + 1" $$
and we're off to the races. We have, in order:
$$ 1, 2, 3, \dots, \omega, \omega + 1, \omega + 1, \dots \omega\cdot 2, \omega\cdot 2 + 1, \omega\cdot 2 + 2, \dots \omega\cdot 3, \dots \omega^2, \omega^2 + 1, \omega^2 + 2, \dots \omega^2 + \omega, \dots \omega^3, \dots \omega^4, \dots, \omega^{\omega}, \dots \omega^{{\omega}^{\omega}}, \dots,   $$
all of which are apparently countable, even as we move through $\epsilon_{0}$, which is defined to be the first ordinal that satisfies: $ \epsilon_{0} = \omega^{\epsilon_0} $. Then we have $\epsilon_{1}$ which also satisfies this (i.e. $\epsilon_{1} = \omega^{\epsilon_{1}}$) but is not the first to do so... and $\epsilon_2, \epsilon_3, $ etc. all of which are apparently countable, until we get to $$ \boxed{\omega_1}, $$ defined to be the supremum of all of the countable ordinals, which is the first uncountable ordinal.
My second set of questions is How can anything after $\omega$ by countable? isn't the set $\omega + 1$ too big to be put in bijection with $\mathbb{N}$? And how can the union of an infinite number of things (the Supremum of all the countable numbers) be said to be uncountable, if we've already had limit ordinals before, that we say are still countable, that are unions of infinite numbers infinite sets. Shouldn't they start to be uncountable at $\omega$?
What am I not understanding here?
Answer: (c) $3,5,7,9,\dots$, $4,6,8,10,\dots$, $0,1,2$.
$\omega + 1 \longleftrightarrow 1,2,3,4,\dots,0$.
That's how all those sets are countable.
Comment: Wow, very nice, thank you. But how can you continue to do this for things like $\omega^{\omega}$ and onward?
Comment: You can use that $\omega\times\omega$ is biyective with $\omega$ (that's one of Cantor's ideas).
Answer: To answer your first question,
Define a function  $f(n)$ such that $f(0)$ maps to the first of the three finalmost elements, $f(1)$ maps to the second, and $f(2)$ to the third. For each positive integer greater than 2, let $f(n)$ map 3 as the first element of the first group, 4 as the first element of the second, 5 as the second element of the first, and so on, alternating between each of the two countable clusters of elements.
Comment: Do you mean $2^m(2n+1)$? Wouldn't $f(0,0)=-1 \not\in \mathbb{N}$
Comment: Wonderful, keep forgetting (or failing to conceptualize) that you'll never run out of things to map from in $\mathbb{N}$
Comment: Keep in mind that for all integer n, $\mathbb{N}^n$ has the same cardinality as $\mathbb{N}$
Comment: What kind of bijection can you construct from $\mathbb{N}$ to $\mathbb{N}^n$
Comment: First, note that a bijection from $\mathbb{N}$ to $\mathbb{N}^2$ is sufficient, as from there you can biject iteratively.

Some people like to simply draw out $\mathbb{N}^2$, and then draw a certain type of winding, crooked curve, but that strikes me as a little informal. Let $f(m,n)=2^m(2n-1)$.
Comment: Yeah, I did. Whoops, nice catch. But in general, $f$ should map appropriately.
Comment: I guess it's $f(m,n)=2^m(2n+1)-1$. It's been a while since I looked at that particular bijection.
Comment: Ah, very well. That makes sense. Thank you!
Answer: The other answers address your first question; let me tackle the second.
Note that if $\alpha$ is countable, so is $\alpha+1$ (Hilbert's hotel). So $\omega_1$ (this is the standard notation for the supremum of the countable ordinals) can't be countable, since otherwise $\omega_1+1$ would also be countable and we would therefore have to have $\omega_1\ge\omega_1+1$, by definition of $\omega_1$. Basically, $\omega_1$ is the first thing you get after you've run out of countable ordinals, so it clearly can't be countable!
As far as intuition goes, I would argue that makes it different from countable limit ordinals - even really big ones like $\epsilon_0=\omega^{\omega^{\omega^{. . .}}}$ - is cofinality. Basically, each countable limit ordinal can be written as a countable limit of smaller countable ordinals. This is not true for $\omega_1$: the countable union of countable sets is countable (technically this uses a very small amount of choice), so if $\alpha_1<\alpha_2<\alpha_3< . . . <\omega_1$, then $\sup\{\alpha_i: i\in\mathbb{N}\}$ is also less than $\omega_1$.
Comment: What is the proof that you ever actually do run our of countable ordinals?
Comment: @D.W. Great question! By definition if $\alpha$ is countable then $\alpha$ can be put into bijection with $\mathbb{N}$. This means that there is a binary relation $R_\alpha$ on $\mathbb{N}$ (not unique of course) such that $\mathbb{N}$, ordered by $R_\alpha$, "looks like" $\alpha$. (Formally: $(\mathbb{N}, R_\alpha)$ has order type $\alpha$.) This proves that the countable ordinals form a set (since the collection of such $R_\alpha$s is a set, by Powerset and Separation). Now, order this set by "is longer than" and (exercise) you get an ordinal; but (exercise) it is uncountable. (cont'd)
Comment: In fact, this ordinal is just $\omega_1$! You may hope for a more "concrete" description of $\omega_1$, but - for various meanings of the word "concrete" - we can prove that can't happen (this is developed in the field *descriptive set theory*). Note that a similar argument shows that *given any set $A$, there is an ordinal which does not inject into $A$*, and (**Burali-Forti**) that the collection of *all* ordinals is therefore not a set, but a proper class.
Comment: When/why would I ever run out of $R_{\alpha}$s? For every next $\alpha$ ($S(\alpha)$), couldn't I just map the next $R_{\alpha}$ to the next element in  $\mathbb{N}$ *ad infinitum*?
Comment: You've just argued that there isn't a "last" countable ordinal, and this is exactly right. However, because of limit ordinals, this doesn't mean we never run out! It's analogous (but slightly more complicated) to the fact that there are non-finite ordinals. At first it might seem like we can't run out of finite ordinals - given any finite $\alpha$, $\alpha+1$ is also finite - but we do in fact run out after $\omega$-many steps. Note, in particular, that the moment we run out is exactly the first non-finite ordinal! Similarly, we run out of countable ordinals at stage first-uncountable-ordinal.
Comment: I guess the larger question is: why does this solve the problem of classifying order types? Couldn't we have done it all along by just classifying types of bijections from $\mathbb{N}$ without ordinals, succesors, or supremums?
Comment: @D.W. I don't really understand your question - what is "the problem of classifying order types" and why is that what we're trying to solve?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/39136/discussion-between-noah-schweber-and-d-w).
Comment: Hey sorry, I'm on mobile. But thank you for the offer.
Answer: To answer your first question as simply as possible, if we look at set c, take the the three elements at the end, and consider them mapped onto 1, 2 and 3 in the set of natural numbers. If we then map the first element of the first set of b within c and map that to 4, the first element of the second set of b within c onto 5, the second element of the first set of b within c onto 6 and so on and so forth, we have a bijection between c and the set of natural numbers.
In answering the first question we can solve the second problem easily, if you have the successor ordinal: ω + 1, we map the +1 onto 1, the next the each element of ω onto the set of the natural number set in turn. Any countable ordinal works this way, even ε0, we map ω onto 1, ω^ω onto 2 An day so on and so forth for each well ordered element within ε0, the fact that it is well ordered means it has a mapping function onto the set of natural numbers.
Hopefully this helps, I tried to explain this in a way that's would make sense to people that aren't very familiar with these concepts. I remember watching a good YouTube series on this topic once, so there are resources out there to help people starting to learn this section of set theory.

Ordinals and Countability


Proving a trivial bound on $L_2$ norm of the error in a sparse approximation of a vector

Question: Trying to understand this supposedly 'trivial' bound from a paper:
If $\theta_N$ denotes the vector $\theta$ with everything except $N$ largest coefficients set to $0$ then we have
$$ || \theta - \theta_N ||_2 \leq C_{2,p} \cdot ||\theta||_p \cdot (N+1)^{1/2 - 1/p} $$
for $N=0,1,2,...$ and constant $C_{2,p}$ depending only on $p \in (0,2)$.
Comment: @rtybase: by the generalized Holder inequality I would expect something like $$\|\theta-\theta_N\|_2\leq \|\theta\|_p\cdot(M-N)^{1/2-1/p}$$ where $M$ is the number of components of $\theta$. Where your $N+1$ comes from?
Comment: The very first thing which comes almost immediately is Hölder's inequality https://en.wikipedia.org/wiki/H%C3%B6lder%27s_inequality
Comment: Just double-checking, is it correct that $p \in (0,2)$? Because $\frac{1}{2} - \frac{1}{p}<0$
Comment: $(M-N)^{\frac{1}{2}-\frac{1}{p}}\leq M^{\frac{1}{2}-\frac{1}{p}}=\frac{M^{\frac{1}{2}-\frac{1}{p}}}{(N+1)^{\frac{1}{2}-\frac{1}{p}}}\cdot (N+1)^{\frac{1}{2}-\frac{1}{p}}\leq M^{\frac{1}{2}-\frac{1}{p}} \cdot (N+1)^{\frac{1}{2}-\frac{1}{p}}$ and $M^{\frac{1}{2}-\frac{1}{p}}$ is just part of $C_{2,p}$. This is a way too trivial ... there must be a catch for 500 bounty
Comment: Here is a related (imo) question http://math.stackexchange.com/questions/218046/relations-between-p-norms
Comment: I am surprised to see no response in here!
Comment: @msm I think the response is here, it's just too trivial, besides ... we need some answers from user67081 too ...
Comment: Correct. As long as we don't care about the constant $C_{p,q}$ it may be trivial. In such case, a weaker inequality will be resulted: $\left \| \boldsymbol{\theta}-\boldsymbol{\theta}_s \right \|_q\le \frac{1}{s^{1/p-1/q}}\left\|\boldsymbol{\theta}\right\|_p$. However, I don't think my proof for the stronger one (with the constant) is trivial.
Answer: The proof is not trivial and I happen to see it a while ago.
What follows is the proof for the general case with the error expressed in terms of the $\ell_q$-quasinorm of the difference vector assuming only $s$ largest elements of the vector $\boldsymbol{\theta}=(\theta_1,\theta_2,\cdots,\theta_M)$ if $\left\|\boldsymbol{\theta}\right\|_p\le1$.
Reorder $\boldsymbol{\theta}$ to get $\boldsymbol{\theta}^*=(\theta^*_1,\theta^*_2,\cdots,\theta^*_M)$ such that $\theta^*_1\ge\theta^*_2\ge\cdots\ge \theta^*_M$. Define $x_j\triangleq (\theta^*_j)^p$. We are going to prove that
$$\left \| \boldsymbol{\theta}-\boldsymbol{\theta}_s \right \|_q\le \frac{c_{p,q}}{s^{1/p-1/q}}\left\|\boldsymbol{\theta}\right\|_p$$
For simplicity assume the $q$-th power
$$\left \| \boldsymbol{\theta}-\boldsymbol{\theta}_s \right \|^q_q\le \frac{c^q_{p,q}}{s^{q/p-1}}\left\|\boldsymbol{\theta}\right\|^q_p$$
The first $s$ terms of the LHS are zero. Dividing both sides to $\left\|\boldsymbol{\theta}\right\|^q_p$ and given $x_1+x_2+\cdots+x_M\le1$, it is equivalent to prove that
 $$x^{q/p}_{s+1}+x^{q/p}_{s+2}+\cdots+x^{q/p}_{M}\le \frac{c^q_{p,q}}{s^{q/p-1}} \hspace{2cm}(1)$$
 with $r=q/p>1$, we are looking for the maximum of the convex function
$$f(x_1,x_2,\cdots,x_M)=x^r_{s+1}+x^r_{s+2}+\cdots+x^r_{M}$$ over a convex polygon $$\mathcal{C}=\{(x_1,\cdots,x_M)\in\mathbb{R}^N:\, x_1\ge \cdots \ge x_M \ge 0, \,x_1+x_2+\cdots+x_M\le1\}$$
The maximum is on one of the vertices of the polygon. So we check different vertices:

If $x_1=\cdots=x_M=0$ then $f=0$.
If $x_1=\cdots=x_k>x_{k+1}=\cdots=x_M=0$, for some $k$ such that
$1<k<s$ then $f=0$.
If $x_1=\cdots=x_k>x_{k+1}=\cdots=x_M=0$, for some $k$ such that
$s+1<k<N$, then $x_1=\cdots=x_k=1/k$ and
$f(x_1,x_2,\cdots,x_M)=\frac{k-s}{k^r}$.

So we need to find the $k$ that maximizes $g(k)=\frac{k-s}{k^r}$.
It would be $k^*=\frac{rs}{r-1}$. Therefore, we get $$f\le g(k^*)=\frac{1}{r}\left(1-\frac{1}{r}\right)^{r-1}\frac{1}{s^{r-1}}=\frac{c^q_{p,q}}{s^{q/p-1}}$$ with $$c_{p,q}=\left[\left(\frac{p}{q}\right)^{p/q}\left(1-\frac{p}{q}\right)^{1-p/q}\right]^{1/p}$$
which yields $(1)$. Note that the question is not stated correctly and completely.


Inspect Console Log in NodeJS Express

Question: I am currently debugging a Nodejs Express application and I was wondering if there was a way to inspect the console log object similar to how you would do when developing web applications in Chrome or Firefox.
I.E:
<code>  var myObj = [{"hello": "world"}];
  console.log(myObj);
</code>
Inspect Object:

Below is an example of a console.log() I am trying to inspect from Express:
Answer: Check out node-inspector to debug your Node.js script in a browser.
Here's a link to a video showing how to use the module.

Inspect Console Log in NodeJS Express


Scilab - Legend ONLY for a specific set of functions

Question: I would like to generate boundaries using xfpoly and save them using xs2pdf. Then I want to display a plot of 2 functions into those boundaries, add a legend to those functions and save the image again.
My code follows...
clear; clc; xdel(winsid());

t = -2:0.01:2;
x_1 = t.^2; x_2 = t.^4;

xfpoly([-3 -2 -2 -3], [0 0 16 16], color('grey'));
ax = gca();
ax.auto_clear = 'off'; ax.data_bounds = [-3, 0; 3, 3];
ax.box = 'on';
ax.axes_visible = ['on','on','off']; ax.tight_limits = ['on','on','off'];
xfpoly([2 3 3 2], [0 0 16 16], color('grey'));
xfpoly([-1 1 1 -1], [1 1 16 16], color('grey'));

xs2pdf(gcf(), 'fig_1');

plot2d(t, [x_1', x_2'], [color('green'), color('red')]);
legend(['t^2'; 't^4']);
leg_ent = gce();
leg_ent.text = ['';'';'';'t^2'; 't^4']

xs2pdf(gcf(), 'fig_2');

Answer: Do you want something like this?
clear;
clc;

t = -2:0.01:2;
x_1 = t.^2; x_2 = t.^4;

scf(0);
clf(0);
//plot the curves first to make legend easier
plot2d(t, [x_1', x_2'], [color('green'), color('red')]);
legend(['t^2'; 't^4']);   //the first two elements are the curves, so no neet to modify
ax = gca();
ax.auto_clear = 'off';
ax.data_bounds = [-3, 0; 3, 3];
ax.box = 'on';

xfpoly([-3 -2 -2 -3], [0 0 3 3], color('grey'));
xfpoly([2 3 3 2], [0 0 3 3], color('grey'));
xfpoly([-1 1 1 -1], [1 1 3 3], color('grey'));

scf(1);
clf(1);
xfpoly([-3 -2 -2 -3], [0 0 3 3], color('grey'));  //ymax sholud be 3, not 16
xfpoly([2 3 3 2], [0 0 3 3], color('grey'));
xfpoly([-1 1 1 -1], [1 1 3 3], color('grey'));
ax = gca();
ax.auto_clear = 'off';
ax.data_bounds = [-3, 0; 3, 3];
ax.box = 'on';

Comment: Yes, I need to create those 2 plots. But (for teaching purposes) in order as it is written in my question - grey boundaries at first, then add 2 curves. The problem is, that I'm creating 5 graphs with boundaries at first and then adding 5 plots of 2 curves in each.
Answer: Atilla's answer brought me to this solution using pause command:
clear; clc; xdel(winsid());

t = -2:0.01:2;
x_1 = t.^2; x_2 = t.^4;

plot2d(t, [x_1', x_2'], [color('green'), color('red')]); plot_1 = gce();
legend(['t^2'; 't^4']); leg_1 = gce();
plot_1.visible = 'off'; leg_1.visible = 'off';

xfpoly([-3 -2 -2 -3], [0 0 16 16], color('grey'));
xfpoly([2 3 3 2], [0 0 16 16], color('grey'));
xfpoly([-1 1 1 -1], [1 1 16 16], color('grey'));
ax = gca();
ax.box = 'on';

xs2pdf(gcf(), 'fig_1');
// pause
plot_1.visible = 'on'; leg_1.visible = 'on';
xs2pdf(gcf(), 'fig_2');

Comment: If my answer helped you, you may upvote it. I'm glad that I could help.


Quadratic congruence $x^2+5x \equiv 12 \pmod{31} $

Question: Does
$$x^2+5x \equiv 12 \pmod{31} $$
have a solution?
Comment: Complete the square and use quadratic reciprocity, recalling that $16\equiv 2^{-1}\mod 31$.
Answer: The equation is equivalent to:
$$ 4x^2 + 20x\equiv 48 \equiv 17\pmod{31}$$
or to:
$$ (2x+5)^2 \equiv  11\pmod{31} $$
hence it has two solutions iff $11$ is a quadratic residue $\!\!\pmod{31}$. So, let us compute the Legendre symbol $\left(\frac{11}{31}\right)$ through quadratic reciprocity:
$$\left(\frac{11}{31}\right) = - \left(\frac{31}{11}\right) = -\left(\frac{9}{11}\right) = -1.$$
No way, $11$ is not a quadratic residue $\!\!\pmod{31}$, hence there are no solutions.
Comment: Or, $11 \equiv -20 \equiv -144$. If $11$ were a square mod $31$, then so would $-1$, but this is false, because $31 \not\equiv 1 \bmod 4$.
Comment: @lhf: that is a nice (and elementary) alternative.


Sum of multiple loaded dice

Question: I have $n$ dice with $m$ sides. The $i^{th}$ dice will show value $0 \leq x_i \leq m-1$ with probability $0 \leq D_i(x_i) \leq 1$. What is the probability that the sum of the dice equals $\alpha$?
Is there some approximation for $P(\alpha)$?
Comment: Since you subscripted "$D$" with the index of the dice, does that mean each die might have a different distribution?
Comment: You can obtain the exact probability function by discrete convolution.
Answer: Good question. Not sure about a precise analytical solution.
However for large m there is a good approximation indeed.
The random variables $X_i$ where $i\in [0, m-1]$ where $X_i$ is the probability distribution of the $i^{th}$ dice are identical (each having the same mean $\mu$ and standard deviation $\sigma$) and independent. We can hence apply the theorem of the central limit which states that
$$S_n = \sum\limits_{i=0}^{m-1}X_i$$ is approximated by $\mathcal{N}(m \mu, m \sigma^2)$  when m is large.

Sum of multiple loaded dice


Como usar factory, do Angular, com firebase?

Question: Boa tarde,
Pessoal, estou tentando criar uma factory com firebase, para trazer os dados do mesmo.
Meu controller:
app.controller('ListagemCtrl', function($scope, $location, $firebaseObject, $timeout, appFactory){

$scope.filmesCadastrados = [];

appFactory.pegaFilmes().on('value', function (snapshot) {
    for(var id in snapshot.val()){
        var filme = snapshot.val()[id];
        $scope.filmesCadastrados.push({
            titulo: filme.titulo,
            diretor: filme.diretor,
            categoria: filme.categoria,
            duracao: filme.duracao
        });
    }
});
});

E essa é minha factory:
app.factory('appFactory', function($scope, $firebaseObject){

var _pegaFilmes = function() {
    return firebase.database().ref('filmes/').on('value', function (snapshot) {
                for(var id in snapshot.val()){
                    var filme = snapshot.val()[id];
                    //console.log(filme);
                    $scope.filmesCadastrados.push({
                        titulo: filme.titulo,
                        diretor: filme.diretor,
                        categoria: filme.categoria,
                        duracao: filme.duracao
                    });

                }
            });
}

return {
    pegaFilmes: _pegaFilmes
};

});

Esse aviso aparece no console:

angular.js:13708 Error: [$injector:unpr] http://errors.angularjs.org/1.5.7/$injector/unpr?p0=copeProvider%20%3C-%20%24scope%20%3C-%20appFactory
Answer: Depois tu da uma olhada na dock
https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire
  app.factory('Filmes', function($firebaseArray){
      var chatRef = firebase.database().ref('/filmes');

     return $firebaseArray(chatRef);
  });

  app.controller('FilmeCtrl', function($scope, Filmes){
    $scope.filmes =  [];

    // Function auto executada
    (function () {
      console.log(Filmes);
      Filmes.$loaded(success, error);

      function success(data) {
        $scope.filmes =  data;
        console.log('MIUUII', data);
      }

      function error(errorMessage) {
        console.log(errorMessage);
      }
    })();
  });

Comment: Vou tentar, valeu.
Comment: Que show cara!!! Funcionou!! Valeu Muito
Comment: Paulo, como faço se eu quiser pegar uma propriedade do dado do Firebase? Tipo, quero pegar um dos elementos do objeto json, exemplo, só o título do filme.
Comment: Não precisa mais, já consegui.


Can get_queryset return 403 or any custom response

Question: I have no idea if This is the good way to do this.
I have an endpoint, it should retrieve a specific instance of system.
Before being worried about permissions my view lookeds like this:

class SystemDetail(generics.RetrieveAPIView):
""" Get a system detail """
queryset = System.objects.all()
serializer_class = SystemSerializer

I want to update this because I want user to be able to see only systems they own.
So I update my view like so:
class SystemDetail(generics.RetrieveAPIView):
def get_queryset(self):
    user_groups = self.request.user.groups.all().values_list('name')

    if 'all_rights' not in user_groups[0]:
        if len(user_groups) == 1: # For now we say that 1 user is only in 1 group
            dealer_name: str = user_groups[0][0].capitalize() # Group name are creating progammatically, it is using the same enum than the dealer name on the system
            return System.objects.filter(dealer__name=dealer_name)
        else:
            raise AttributeError('User in 2 groups, endpoint can not manage it')
    else:
        return System.objects.all()

""" Get a system detail """
serializer_class = SystemSerializer

So basically it works, when I try to access a system that I should not be able to see I got this message:

{"detail":"Not found."}

but What I'd like is to set a custom message with a 403 status saying to the user he is trying to access a system he can not see.
What is the good way to achieve this ?
Thank you.
:)
Answer: You can override DRF's APIException class:
from typing import Union

from rest_framework.exceptions import APIException
from rest_framework.status import HTTP_400_BAD_REQUEST

class CustomAPIException(APIException):
    def __init__(
        self,
        detail: Union[str, None] = None,
        code: int = HTTP_400_BAD_REQUEST,
    ) -> None:
        self.status_code = code
        super().__init__(detail, code)

Then you can raise it in your view:
raise CustomAPIException(
    detail={"errorMessage": "My custom error message."},
    code=HTTP_403_FORBIDDEN,
)


Simple PHP Login - redirecting to a new webpage after successful login

Question: I'm using the script below for logging in. I'm trying to redirect the users who were succesfully logged in to another webpage (visible only for logged in users), but it redirects everyone - regardless if the username and password are correct. What's should be changed in the code?

page with login form - index.php
the page that I want to redirect to - content.php

Table in my database
CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `emailadress` varchar(255) NOT NULL,
  `pass` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
)

PHP
<?php
if (isset($_POST['username']) and isset($_POST['password'])){
$name = $_POST['username'];
$pass = $_POST['password'];

$query = "SELECT * FROM `person` WHERE name='$username' and pass='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
}else{
echo "Login failed.";
}
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hello" . $username . "
";
echo "Logout";}
?>

HTML
<form method="post" action="content.php" name="login">

<?php
    if(isset($msg) & !empty($msg)){
        echo $msg;
    }
 ?>
        Username:

        <input type="text" name="username">

        Password:

        <input type="password" name="password">

        <button type="submit" name="login">Log in</button>
</form>

Comment: Sidenote: It seems like you are storing passwords in plain text, which is strongly advised you do not use, unless you're already using something to the effect of [`crypt()`](http://php.net/crypt) or PHP 5.5's [`password_hash()`](http://www.php.net/manual/en/function.password-hash.php) function (*which I doubt*). Your code is also missing `session_start();` which is required when using sessions. *Plus*, in its present state, your code is open to [`SQL injection`](http://stackoverflow.com/q/60174/)
Comment: You're using `and pass='$password'` yet your variable is called `$pass` where you have `$pass = $_POST['password'];` and `name='$username'` and you have `$name = $_POST['username'];` no match.
Comment: oh, my bad, sorry. no wonder it's not working :) thanks for pointing that out!
Comment: You're welcome, I posted [`an answer`](http://stackoverflow.com/a/22561923/) below for you to look at. Put a quick tick to close the question then. ;-)
Comment: I made another addition to my answer below. You have a trailing comma in `PRIMARY KEY (`\``id`\``),`
Answer: There is so much wrong with it
First. the action of your form is the protected page meaning that everyone will be redirected there in any case. You want to move your php code to login.php So that login.php looks like
<?php
    session_start();
    if(isset($_POST['username']) and isset($_POST['password']))
    {
        $username = $_POST['username'];
        $pass = $_POST['password'];
        $query = "SELECT * FROM `person` WHERE name='$username' and pass='$pass'";
        $result = mysql_query($query) or die(mysql_error());
        $count = mysql_num_rows($result);
        if ($count == 1){
            $_SESSION['username'] = $username;
            header('Location: content.php');
        }
        else
        {
            $msg = "Wrong credentials";
        }
    }

    if(isset($msg) & !empty($msg)){
        echo $msg;
    }
 ?>
<form method="post" name="login">
        Username:

        <input type="text" name="username">

        Password:

        <input type="password" name="password">

        <button type="submit" name="login">Log in</button>
</form>

Note removing the action tag from the form - this way the browser will submit the page to itself, i.e. login.php
Your content.php should check that the user is logged in and get the username from the session
<?php
    session_start();
    if(!isset($_SESSION['username']))
    {
        die("You are not logged in!");
    }
    $username = $_SESSION['username'];
    echo "Hai " . $username;
    echo "Logout";
?>

Remember to call session_start() in your scripts to tell PHP to create/invoke the existing session
Comment: Needless to say, never store password in the database unencrypted
Comment: Great, a nice thorough answer. Btw, if you want to make additions after you've written a post, just edit them in, rather than making addendums in comments. It keeps everything neat and in one place.
Answer: You are using pass='$password' yet your variable is called $pass
where you have $pass = $_POST['password']; and name='$username'
and you have $name = $_POST['username']; there is no match.
Sidenote: It seems like you are storing passwords in plain text, which is strongly advised you do not use, unless you're already using something to the effect of crypt() or PHP 5.5's password_hash() function.
Your code is (possibly) missing session_start(); which is required to be included inside all pages when using sessions. Plus, in its present state, your code is open to SQL injection
Use mysqli_* functions with prepared statements or PDO.
mysql_* functions are deprecated and will be removed from future releases.

Another thing I noticed is that your SQL reads as:
CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `emailadress` varchar(255) NOT NULL,
  `pass` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
                    ^ // <- comma
)

Remove the last comma
CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `emailadress` varchar(255) NOT NULL,
  `pass` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
)

Here are a few redirection methods:
header('Location: http://www.example.com/content.php');

and if headers are giving you a hard time:
echo "You will be redirected in 5 seconds...";
echo "<meta http-equiv=Refresh content=5;url=http://www.yoursite.com/content.php>";

Another method is to add ob_start(); under your opening <?php tag which works at times.
Example:
<?php
ob_start();
session_start();
if (isset($_POST['username']) and isset($_POST['password'])){
$name = $_POST['username'];
$pass = $_POST['password'];
...

header('Location: http://www.example.com/content.php');

...

Comment: if I have `session_start();` in the included `connection.php` file (see the edited question), should I also have it in the php code in `index.php` - as you wrote it in the last example (with `ob_start();`)
? :)
Comment: Just as long as your included file is inside all pages using sessions, yes. As for `ob_start();` that's just an option I mentioned in regards to, if you get an error message stating `headers already sent....` for the redirection. @dirigibleplum
Answer: To redirect do this:
    header('Location: content.php');

Comment: And `exit()` afterwards - PHP will quite happily carry on executing code after a `header`, even if that it not your intention `:-)`.
Answer: Your form action is content.php. Anyone who submits the form goes to that page because of that. You'd have to make index.php or another separate page process the form in order for access to content.php to be restricted.
Answer:
You didn't call session_start(); before using session variables.
the form action="content.php" is where your post is submitted not where it will be redirected.

Put session_start(); before you use the session variables and put the redirect in the if block like this:
if($count == 1){
 session_start();
 $username = $_SESSION['username'];
 header("location: content.php");
}

and in your form action put action as index.php
<form action="index.php" method="post" name="login">

you can leave the form action empty if you are not using HTML5
Answer: add this
header('Location: home.html'); or header('Location: home.php');


Show that $a = \limsup_{n\to\infty} a_n$.

Question: Suppose $a \in \mathbb{R}$ is such that:

given any $ε>0$ there exists $n_0 \in \mathbb{N}$ such that $a_n \le a+\varepsilon$ for all $n \ge n_0$
there is $k\ge n_0$ for which $a−\varepsilon<a_k$.

Then, prove that $a=\limsup_{n\to\infty}a_n$
It looks like a theorem and is obviously true, but I have no idea how to prove it and where to start. Any help would be appreciated.
Comment: Please edit your original post rather than reposting it with almost no modification - see the reason your previous question was put on hold and modify it as needed.
Answer: Hint
Let $y_n=\sup_{k\geq n}a_k$. So you have to show that $$a=\lim_{n\to\infty }y_n.$$
Notice that $(y_n)$ is decreasing.


Qt4 Creator/QMAKE equivalent to "-mcmodel=medium" GCC compiler settings

Question: I'm using Qt Creator to create a GUI for a fairly memory intensive C++ application on Linux. In order for the application to run properly, the -mcmodel=medium compiler flag must be set during compilation, otherwise the application will abruptly crash during execution (tried compiling in Qt without it, and it crashes as expected). How do I set the GCC flags in the .pro file  to deal with this directly or is there a Qt equivalent to this memory model flag setting?
Note: I've tried QMAKE_CXXFLAGS += -mcmodel=medium and it doesn't seem to work...
Correction: QMAKE_CXXFLAGS method appears to work. Error returned was actually a hardware memory bus error.
Answer: <code>QMAKE_CXXFLAGS += -mcmodel=medium
</code>
Comment: Sorry, I forgot to mention I tried QMAKE_CXXFLAGS += -mcmodel=medium and it didn't seem to work.


Music education audio lessons

Question: I am currently learning to play the guitar, and that has sparked an interest in learning more about music in general. I would like to learn about music theory, ear training, history, musical styles and forms, ethnomusicology, and the like.
When learning about music, I find it best to be able to hear what is being discussed. In addition, I commute to work via the subway, so I have about half an hour each way that I could be listening to lectures and examples.
Are there any good resources of podcasts or audio lectures, either free or for purchase, that I could download and listen to on my commute to learn more about music?
Answer: The best ear training courses available are by David Lucas and can be found at www.perfectpitch.com, these are audio lectures but do require some interactivity from you and your instrument to get the most from them (as you'd expect from any music training of this sort).
An excellent book which has a kindle edition is Hearing and Writing Music: Professional Training for Today's Musician, by Ron Gorow, this covers many aspects of music offering practical exercises to help with hearing/perceiving music and the overall development of your ear and you as a musician.
You might want to give this a look as well How to Listen to and Understand Great Music.
Comment: David Lucas Burge provides two courses on his website. The Perfect Pitch one is more strongly marketed, but there is a much more expansive Relative Pitch course I would be interested to know if anyone has tried.
Comment: I must admit to being skeptical about the perfect pitch course. It seems to oversell itself, making rather substantial claims of being able to teach anyone perfect pitch, when as far as I know it's pretty hard to learn. Do you have positive experience with it? Has it actually taught you perfect pitch? The book looks interesting, but this question is about audio lessons, not written. The third link, for the course on great music, looks like just the kind of thing I'm looking for, though $350 for the course without being able to sample it is a bit steep. Have you tried it? Can you give a review?
Comment: I have listened to it and it helps you to find a way to map note names to the tones eventually giving you aural recall (the ability to name sounding notes/chords by ear) - how much it helps is relative to how serious you take it.  As is explained in the lectures, its a myth that you are born with Perfect Pitch, its something that is developed, those that develop earlier are usually those well involved in music from a very early age.   Its totally develop-able during adulthood, the more experienced a musician you are the easier it is.
Comment: @Brian you might want to go the used route: http://www.amazon.com/gp/offer-listing/0942542908/ref=dp_olp_used?ie=UTF8&condition=used
Comment: Found the "How to Listen" course at my local library. Between that and the David Lucas material, I'd say this answer has given me some good starting material.
Comment: @Brian - If you want to buy the course, now is the time, 70% off http://www.thegreatcourses.com/tgc/courses/course_detail.aspx?cid=700
Answer: Gary Ewer's Easy Music Theory
Comment: Have you used this product? How did it work for you?
Comment: Hmm. That appears to be mostly instruction sheets and video, not audio lectures. It's not something that I could stick on an MP3 player and listen to while commuting. Thanks for the link, but I don't think it's quite what I'm looking for.

Music education audio lessons


Natural homomorphism from $A$ and $B$ to $A \otimes B$

Question: Suppose $A$ and $B$ are two $R-$algebras, where $R$ is a commutative ring with $1$. There are natural algebra homomorphisms $\ a \to a \otimes 1 \ $ and
$ \ b \to 1 \otimes b \ $ from $A$ and $B$ to $A \otimes_{R} B$.

Are these homomorphisms injective?

Consider the first homomorphism. If $a_1 \neq a_2$ then we want
$(a_1 - a_2) \otimes 1 \neq 0$. If there is an $R-$bilinear map $f: A \times B \to M$, where $M$ is some $R-$module, such that $f(a_1 - a_2, 1) \neq 0$ then we are done. But how can one find such $f$?
UPDATE: As it was pointed out, it is not true in general. But when is it true?
It seems that if $A$ and $B$ are real or complex vector spaces, both homomorphisms are injective. Furthermore, when $A$ is a $\mathbb{Z}$-tosrion-free ring and $B$ is a field of characteristic $0$, then  $a \to a \otimes 1$ seems to be injective.
Comment: I don't know what you mean by contradictions. I was just pointing that out because you said "It seems that if $A$ or $B$ are real or complex vector spaces, both homomorphisms are injective", which is only true if you're fixing the base ring to be respectively $\mathbb R$ or $\mathbb C$. For example, $\mathbb C[x]/x^2 \otimes_{\mathbb C[x]} \mathbb C[x]/(x-1)^2 = 0$.
Comment: Note that the definition of tensor product requires a choice of base ring. If the base ring is a field, e.g. $\mathbb R$ or $\mathbb C$, then the canonical tensor product maps are injective.
Comment: Tsemo's example uses the base ring $\mathbb Z$.
Comment: @DustanLevenstein I see no contradictions. I consider the product $A \otimes_{R} B$. In my first example $R = \mathbb{R}$ or $\mathbb{C}$ and in the second one $R = \mathbb{Z}$.
Answer: No,$\mathbb{Z}/2\otimes_{\mathbb{Z}}\mathbb{Z}/3=0$, so $\mathbb{Z}/2\rightarrow \mathbb{Z}/2\otimes_{\mathbb{Z}}\mathbb{Z}/3$ is not injective.
Comment: Agreed: this is my automatic example for this matter.
Answer: We can approach the situation abstractly as follows. These maps are tensor products of inclusions of scalar multiples of the identities $R \to A$ and $R \to B$ into $A$ and $B$, which are then tensored by $B$ and $A$ respectively. So, a sufficient condition for the tensored map
$$R \otimes_R B \cong B \mapsto A \otimes_R B$$
to be injective is first that the original map $R \to A$ is injective and second that $B$ is flat as an $R$-module, and similarly the other way.
Both conditions are automatic if $R$ is a field but not in general. If $R \to A$ is not injective then the identity is a torsion element in $A$ as an $R$-module, so a sufficient condition for this to not happen is that $A$ is torsion-free; also, if $B$ is flat then it is torsion-free. These assumptions are sufficient if $R$ is a Dedekind domain, since then every torsion-free module is flat.


Exception : The requested security protocol is not supported c#

Question: Exception : The requested security protocol is not supported  c#.
My application is using .net framework 3.5 and run on server windows 2012 R2. After i started getting exception "The underlying connection was closed: An unexpected error occurred on a send."
I changed my code and defined the protocol security as below-
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | (SecurityProtocolType)768; | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
After changing my code at my local environment started working but still have issue at Live server.
"The requested security protocol is not supported."
I have already defined the possible security protocol but still the same code is not working for Live.
Also, due to limitations of the version we are using, we cannot upgrade the Framework at this time.
Please suggest.
Comment: I see this is old but try updating your Windows OS: https://support.microsoft.com/en-us/help/3154518/support-for-tls-system-default-versions-included-in-the-net-framework
Answer: As per my research and referring the many blog ,I am find the .NET 3.5 or below. TLS 1.2 is not supported (*) and there is no workaround. Upgrade your application to more recent version of the framework.
Refer link : https://blogs.perficient.com/2016/04/28/tsl-1-2-and-net-support/


Finish running a function before proceeding in a loop

Question: I want the function in my FOR loop to finish running before going on to the next code but I just can't get it to work.
It should fade in fade out the text "Result" before popping the alert window 'Lucky you' but I would see the alert window loop first before seeing the text. I don't know what I'm doing wrong.
HTML:

Result

Javascript:
function showNextQuote() {
    $("#quotes").fadeIn(2000).delay(2000).fadeOut(2000);
}

for (i = 1; i < 4; i++){
    showNextQuote(); alert("Lucky you");
};

Comment: That's not how JavaScript works. You need to use callbacks for this, you can't use a loop.
Comment: `delay` in an asynchronous operation, you can't do that. What you can do is pass a callback to `fadeOut` so it executes when it is done.
Comment: I'm sorry elclanrs, can you write out the code so I can better understand?
Comment: See http://api.jquery.com/fadeout/, check the "complete" callback, there are examples.
Answer: Since these operations are asynchronous you can't block processing while they're running.  Instead, you pass them a function to execute when they complete (called a callback).  So chaining them like this would look more like a recursive function than a loop.
(Though this isn't really technically recursion since the asynchronous operations aren't building up a stack.  It's semantically/logically very similar to tail recursion though, at least in function structure.)
Something like this:
function showNextQuote(iteration) {
  // terminating condition
  if (iteration > 4) {
    return;
  }

  // recurse
  $("#quotes").fadeIn(2000).delay(2000).fadeOut(2000, function () {
    alert("Lucky you");
    showNextQuote(iteration + 1);
  });
}

showNextQuote(1);

What this does is define the function, which internally passes a reference to itself as a callback to fadeOut.  Each callback increments the iteration value by 1.  Then after defining the function it's invoked with an initial iteration value of 1.
Comment: Hi, thanks for your input. Unfortunately, the alert only comes after the text fades out 4 times. I was wanting it to alert each time it fades. I guess this is what you mean by asynchronous. Thanks though. I'll just try something else.
Comment: @TommyNg: In that case put the alert in the recurse part instead of the terminating condition part.
Comment: @TommyNg: Just in case, I've updated the code in my answer to reflect that.  Note that a browser's `alert` is a blocking operation, so the next fade-in and fade-out is going to wait until you've dismissed the `alert`.  The updated code in my answer will show the `alert` after the fade-out.  If you want to show it before the fade-in just move it above the call to `fadeIn()`.
Answer: As said in comments, JavaScript can't do this in a loop, since fadeIn, delay and fadeOut are all asynchronous.
Something like this should work:
function showNextQuote(n) {
  if (n > 0) {
    $("#quotes").fadeIn(2000).delay(2000).fadeOut(2000, function() {
      alert("Lucky you");
      showNextQuote(n - 1);
    });
  }
}
showNextQuote(4);

Comment: Hi, thanks for your input. Unfortunately, the alert only comes after the text fades out 4 times. I was wanting it to alert each time it fades. I guess this is what you mean by asynchronous. Thanks though. I'll just try something else.


Find the surface integral of some ellipsoid?

Question: I got Stokes theorem all warmed up for this one!
$$\int_{S}\int(Curl(\vec{F}))d\vec{s}$$ (That means delta cross F or curl of F) Where S is the ellipsoid $x^2 + y^2 + 2z^2 = 16$
And $\vec{F} = sinxy\vec{i} +e^x\vec{j} - yz\vec{k}$
Where do I move from here?
Answer: Hint: Notice that the surface $S$ has no boundary, so that applying Stokes here results in integrating over the empty set.


a way to integrate: $\int (\sqrt{x} +3)/(2+ x^ \frac{1}{3}) dx$

Question: Im looking for a way to integrate:
$$
\int \frac{ \sqrt{x} +3}{2+ x^ \frac{1}{3}} dx
$$
that would make it efficient and not too difficult...
Any suggestions?
Comment: I haven't tried, but what about changing x = y^6? Does it get better?
Comment: Well, if $x=y^6$ then $dx=6y^5\,dy$.
Comment: @BCLC, you would actually wind up integrating ${(u-2)^{7/2}\over u}du$....
Comment: @BCLC, $x=(u-2)^3$ means $dx=3(u-2)^2du$.
Comment: its not a bas suggestion, problem is you still need to replace $dx$ properly which might be a bit problematic in that course.
Comment: Not sure but try letting u = denominator. Not sure how to integrate $\frac{(u-2)^{3/2}}{u} du$ though.
Comment: @BarryCipra why?
Answer: The substitution $x = t^6$ works. The integral becomes
$$ \int \frac{t^3 + 3}{t^2 + 2} \,6t^5\,dt = 6 \int \frac{t^8 + 3t^5}{t^2 + 2} dt = 6\int \left( t^6 - 2t^4 + 3t^3 + 4t^2 - 6t - 8 + \frac{12t+16}{t^2+2} \right) \, dt $$
You can take it from here
Comment: how did you get from position two to three?
Comment: I used long division.
Answer: Let $x=u^6$, $dx=6u^5du$.
\begin{align*}
&\int\frac{\sqrt x+3}{2+\sqrt[3]x}\,dx\\
=&\int\frac{u^3+3}{u^2+2}6u^5\,du\\
=&6\int\frac{u^8+3u^5}{u^2+2}\,du\\
=&6\int\left(u^6-2u^4+3u^3+4u^2-6u-8+\frac{12u+16}{u^2+2}\right)\,du\\
=&6\int\left(u^6-2u^4+3u^3+4u^2-6u-8+6\frac{2u}{u^2+2}+8\frac{1}{\left(\frac{\sqrt2}{2}u\right)^2+1}\right)\,du\\
=&\frac67u^7-\frac{12}{5}u^5+\frac92u^4+8u^3-18u^2-48u+36\ln\left(u^2+2\right)+48\sqrt2\arctan\left(\frac{\sqrt2}{2}u\right)+C\\
=&\frac67x^{7/6}-\frac{12}{5}x^{5/6}+\frac92x^{2/3}+8x^{1/2}-18x^{1/3}-48x^{1/6}+\\
&36\ln\left(x^{1/3}+2\right)+48\sqrt2\arctan\left(\frac{\sqrt2}{2}x^{1/6}\right)+C
\end{align*}
Comment: Shouldn't it rather be $u^8+3u^5$ in place of $u^8+3$ at line 3 of the equations?
Comment: Yes, thanks for pointing it out :)


How to securely authenticate content embeded in another site?

Question: I need to embed password protected content to a second domain with an iframe. The content itself is a view which will be displayed on a third party site via an iframe and the content is prepared with a custom page and template handing the display. The use case is to present the view on the other site without the users needing to login. From my research, Oauth or Services seem like good candidates, but I don't have much experience with both and using a service to show a single view seems like it might be an over complication. Anyway, I haven't found much in the way of good documentation on the subject so I'm hoping for a good introductory overview of how to implement this. So, what is the best way to securely authenticate the drupal content on another site. I don't want to expose user credentials in the src=url in the frame for security purposes, so I know I need to use another authorisation mechanism. I've looked at the Entity Iframe module, which seems to have some of these features but the module mainly works drupal-to-drupal, and I haven't been able to tangle apart how the module handles the consumer/provider communication.
So, from researching this, I believe that I have to configure oauth and pass the token to the URL in the iframe. What I am unclear about is how to configure oauth access to the page and how to generate the token to be supplied to the iframe.
Comment: I think that you can use one of these methods https://www.drupal.org/node/598662
Answer: 1- build the content structure well in your first site and create a view from admin/structure/views/add that return the data needed to the second site which acts like a client consuming your first site content.
2- Download and enable Services module and enable the submodule Rest Server and submodule OAuth Authentication now you can create secured resources to be consumed by any other sites.
4- create an end point from admin/structure/services/add and choose authentication type as your case "OAuth Authentication" will fit as you need to authenticate the client "the second site consumes your data".
3- Download and enable Services views module that will help you expose any view as a resource to be consumed and managed via services and
4- From the view you have created before click the button Add and choose services, now the view will appear as a regular resource in your site under admin/structure/services/list click edit resources to see it named with your view name enable it and choose the required authentication and authorization.
Now any authenticated client client site or App can consume that resource from http://YOUR_SITE_DOMAIN/END_POINT/VIEWS_SERVICES_URL.
The last and the most important part in your requirements is to configure the authentication method and test it will I recommend below helpful tools and articles.
Chrome rest client extension to test the webservice.
Very helpful article about services module
Another helpful article
Answer: I think you should create a service on your first site to export the view's data as JSON via REST, grab it on your second site, and display it. That is a more secure way.
In your REST service you can use OAUTH and request tokens, or a username and password.
Blog/Using REST Export With Views In Drupal 8 could help you.
Comment: Thanks for the answer, first I'm running a D7 site. Does link still apply?
Comment: yes it still applies  , you can create a rest service and export your view data


How to tell an accented from an unaccented auxiliary note?

Question: Please see this answer from the answer book to my harmony workbook exercise.

Why is the auxiliary note on beat 2 an unaccented auxiliary note (aux. for short) while the auxiliary note on beat 4 is called an accented auxiliary note (a.aux for short). Beat 2 and 4 should be equal and neither is a strong beat in 4/4 time.
Comment: Which theory book is it from please?
Comment: My reasoning is withheld at the moment. However, ABRSM has been pretty helpful with my queries over the last few decades. I'd be ringing them and asking why,'straight from the horse's mouth'. Could even be a typo. In fact, why don't you compile a list of the many questions you pose here, and email them with it? Seriously.
Comment: Well I'll be darned, youd think theyd explain that in the book.. it is ABRSM for crying out loud! Anyhow I have never read that where the aux note resolves defines what kind it is... Surely it was about where the dissonance occured not where they resolve.. If the dissonance occurs on a strong beat then it should be accented period. Your reasoning stands but I dont see how one should be accented and the other not.
Comment: Where do you place accents when you play these examples?
Comment: On beats 1,2,3 and 4
Answer: I fairly strongly suspect that the auxiliary note on Beat 2 is called an unaccented auxiliary note while the auxiliary note on Beat 4 is called an accented auxiliary note because the auxiliary note on Beat 2 resolves on a stronger beat than the auxiliary note is on (Beat 3 in this case), while the auxiliary note on Beat 4 resolves on a weaker beat than that auxiliary note is on (Beat 4.5 in this case). It's all relative for both of these cases.
Comment: This is correct. Recommend strengthening the language (i.e., "strongly suspect" can be removed). Accented vs. Unaccented depends on whether the resolution occurs on a stronger or weaker (part of the) beat.
Comment: Aaron, this is the first time I have heard this. Could you please share where you get this idea? In all my books and all the music theory websites, the only definition for an accented auxiliary note (or upper or lower neighbor as it is sometimes called) I could find is that the dissonance occurs on a strong beat when it is accented. Whether it resolves on the following up or down beat should have no bearing in the classification.
Comment: @armani Your own book is telling you otherwise in the example you posted, and Dekkadeci explains it. Although the auxilliary note occurs on beat 4 — a weak beat — the resolution occurs on the "And" of 4 — and even weaker (part of the) beat. Thus the dissonance is rhythmically strong (accented) compares to the resolution.
Comment: The answer book is giving me an answer. The actual exercise book makes no mention of this, nor does any other definition of an accented auxiliary or neighbor note I have ever read. If you have read such a definition, please share the source.
Answer: Yes, I would class both of these as accented.   The only difference (apart from one being a 'lower auxiliary' the other an 'upper auxiliary' is that the second one resolves within the same beat, the first doesn't.
I might call the first one an auxiliary note, the second an unprepared suspension.
We live now in a musical world of unprepared, unresolved sus2 and sus4 chords.  Of melodies that sometimes follow their own logic, independent of an underlying chord structure.  But the broad principles of constructing a melodic line are still there!
Comment: even if one resolves in the same beat, that doesnt mean they can call one accented and the other not right? this must be a mistake.
Answer: I didn't know the term auxiliary note until now.
I prefer this terminology:
https://www.mymusictheory.com/for-students/grade-6/169-a5-melodic-decoration
But playing the role as an advocatus diaboli of  ABSRM I'd say the quarter note D is unaccented as a changing neighbour note, the F eighth note is intuitively more accented as an appoggiatura (suspended fourth resolving in the third.)
Comment: Why do you say the D is unaccented and the F 8th note accented? A reasoning would be most helpful.
Comment: as I said: It's **intuitive**! (may be because of its length and the interval, a major 2nd). D is a change note, F is an appoggiatura. Sing it and you will feel it: so re do **fami**. Well, the interval doesn't seem so important: if it were mi fa mi redo I would accentuate **redo**.
Answer: This depends entirely on the definitions of the text or teacher.
The only disagreement about accent and NCTs that I have seen is whether accent is simply being on the beat, any beat, or on metrically strong beats such as 1 & 3 in 4/4.
Kostka/Payne give an example of an "unaccented, metrical, chromatic, ascending passing tone" from Mozart's Jupiter Symphony...

In Kostka/Payne - and every other source of NCT definitions I have read - the accent is determined by where the non-chord tone occurs, not where it resolves, or in comparison to some other nearby NCT.
Based on this Kostka/Payne example, they clearly treat only beats 1 and 3 as accented in 4/4 meter and not beats 2 and 4. By their categorization both of your textbook examples would be unaccented auxiliaries. Also, Kostka/Payne categorizes meterical level,  so they would call your first example unaccented, metrical and the second unaccented, submetrical.
If your textbook categorizes NCT accent in some other way, then that's just how that book defines NCTs. But, I have never seen that type of accent categorization in any source I have read.
Comment: Is this the green tonal harmony book you are talking about?
Comment: My copy is 2nd edition, black hard cover.
Comment: Oh ok. My wife bought me that book for my birthday (the newer green one) and the exercise book that goes with it. Do you recommend it?
Comment: Just to add one thing.... what complicates matters is where the bass note is. My book where this extract is from also talks about the bass note having an important impact on where the auxiliary notes is  considered accented. For example, if there is a prominent bass notes on the upbeat of beat 2 then couldnt a melody note on that upbeat be classified as accented since the bass note also falls on that beat?
Comment: Kostka was an assigned text for the one college harmony 101 class I took. I recommend it because it's so well known. I think one should start with basic textbook level analysis, but then move on to something more thoughtful. The basic concept here is about implicit metrical accent... but what about other accents? Explicit ones, like a notated accent mark, or subtler ones like the supposed accented beat 2 of a Sarabande in triple time. The example you gave is very metrical confirming 4/4. If the bass were syncopated in some way, the accent could be different.
Answer: Accented vs Unaccented in this context boils down if the grace note is on the strong part of the beat or on the weak part. In simple time signatures the second subdivision of the beat is the weak part. If the auxiliary note is there it is Unaccented. The strong part of the simple time signatures beats is the first subdivision. If the auxiliary note is there it is accented.
For compound time signature the beats are subdivided into threes. The first subdivision is the strong part of the beat and the second and third subdivision are the weak part of the beats.
I see there is some confusion over terminology. The passing tone is accented or Unaccented. The lower auxiliary and upper auxiliary notes is something completely different. It is the type of thing you explain with an example.
Comment: I will be back at my computer on Monday and then I will complete this answer with examples.


ANOVA or other test for summed data

Question: I would appreciate any suggestions of how to analyse the following dataset. It was suggested that I use ANOVA, but I wanted to check with the community.
I have a protein where I have calculated the entropy of each reading frame (blue, red and yellow). In the attached figure, the bars are a sum of the values calculated. It would probably be better to represent the values as means rather than total sums. Anyway, eye-balling it, the yellow section has a higher entropy than the blue and red regions, whereas red and blue look similar. However, I need to add some statistical weight to this and I would only compare reading frames within one genotype. I'm unsure whether to use ANOVA (repeated as it's 3 groups ?), a pairwise.t.test in R, or even Friedman's test, it's been a while. Perhaps this question is similar to How to test hypothesis of no group differences? ?
I didn't find questions and answers that I identified with, so apologies if I missed one.
Answer: A two way ANOVA or a couple of t-tests is probably just fine.  Is the entropy Gaussian distributed?  Probably not exactly, but you're going to get big $p$-values off of this.  For example, I threw it into R and fit a quick linear model:
d <- data.frame(genotype=factor(rep(c('A','B','C','D','E','F','G','H'), times=3)),
            frame=factor(rep(c('f0','f1', 'f2'), each=8)),
            entropy=c(12.1, 20.2, 21.2, 18.0, 18.0, 21.2, 14.8, 19.0, 9.6, 8.0, 7.6, 7.3, 5.3, 10.8, 4.8, 3.6, 5.1, 7.8, 7.8, 7.3, 7.1, 7.8, 6.4, 7.6))

f <- lm(entropy ~ genotype + frame, data=d)

(I renamed frame 3 to f0 just to make R calculate the differences between 3 and 1 and 3 and 2 without futzing with anything.)  Then summary(f) gives
Call:
lm(formula = entropy ~ genotype + frame, data = d)

Residuals:
    Min      1Q  Median      3Q     Max
-4.1292 -0.7990 -0.0438  0.9719  4.3083

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  16.2292     1.3792  11.768 1.20e-08 ***
genotypeB     3.0667     1.7445   1.758   0.1006
genotypeC     3.2667     1.7445   1.873   0.0822 .
genotypeD     1.9333     1.7445   1.108   0.2864
genotypeE     1.2000     1.7445   0.688   0.5028
genotypeF     4.3333     1.7445   2.484   0.0263 *
genotypeG    -0.2667     1.7445  -0.153   0.8807
genotypeH     1.1333     1.7445   0.650   0.5264
framef1     -10.9375     1.0683 -10.238 6.97e-08 ***
framef2     -10.9500     1.0683 -10.250 6.87e-08 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.137 on 14 degrees of freedom
Multiple R-squared: 0.9157, Adjusted R-squared: 0.8615
F-statistic:  16.9 on 9 and 14 DF,  p-value: 4.697e-06

Entropy is the result of additive effects, none of them particularly wild, so those $p$-values of $10^{-8}$ are plenty to go on.

ANOVA or other test for summed data


Prove the relations $\mathcal{R}_{1}$ and $\mathcal{R}_{2}$ are functions and the inverse of each other

Question: The composition $\mathcal{R}_{2}\circ\mathcal{R}_{1}$ of the relations $\mathcal{R}_{1}$ e $\mathcal{R}_{2}$ is defined as follows:
$$\mathcal{R}_{2}\circ\mathcal{R}_{1} := \{(x,z) \mid \exists y\,(x\mathcal{R}_{1}y\wedge y\mathcal{R}_{2}z)\}$$
In particular, if $\mathcal{R}_{1}\subset X\times Y$ and $\mathcal{R}_{2}\subset Y\times Z$, then $\mathcal{R} = \mathcal{R}_{2}\circ\mathcal{R}_{1}\subset X\times Z$ and
$$x\mathcal{R}z := \exists y\,((y\in Y)\wedge(x\mathcal{R}_{1}y)\wedge(y\mathcal{R}_{2}z))$$
Let $\Delta_{X}$ be the diagonal of $X^{2}$ and $\Delta_{Y}$ the diagonal of $Y^{2}$. Show that if the relations $\mathcal{R}_{1}\subset X\times Y$ and $\mathcal{R}_{2}\subset Y\times X$ are such that $(\mathcal{R}_{2}\circ\mathcal{R}_{1} = \Delta_{X})\wedge(\mathcal{R}_{1}\circ\mathcal{R}_{2} = \Delta_{Y})$, then both relations are functional and define mutually inverse mappings of $X$ and $Y$.
MY ATTEMPT
I know that for a relation to be functional such relation has to satisfy
\begin{align*}
(x\mathcal{R}y)\wedge(x\mathcal{R}z) \Longrightarrow y = z
\end{align*}
Since $\mathcal{R}_{2}\circ\mathcal{R}_{1} = \Delta_{X}$, for any pair $(x,x)\in\Delta_{X}$, one has
\begin{align*}
(x\mathcal{R}_{2}\circ\mathcal{R}_{1}x) \Longrightarrow\exists y\,((y\in Y)\wedge(x\mathcal{R}_{1}y)\wedge(y\mathcal{R}_{2}x))
\end{align*}
Analogously, since $\mathcal{R}_{1}\circ\mathcal{R}_{2} = \Delta_{Y}$, for any pair $(y,y)\in\Delta_{Y}$, one has
\begin{align*}
(y\mathcal{R}_{1}\circ\mathcal{R}_{2}y) \Longrightarrow\exists x\,((x\in X)\wedge(y\mathcal{R}_{1}x)\wedge(x\mathcal{R}_{2}y))
\end{align*}
Then I get stuck. Could someone help me out?
Answer: Your work shows that the domain of both relations is full, and if they are functional, then $R_2\circ R_1(x)=x$ and $R_1\circ R_2(y)=y$ for all $x\in X $ and $y\in Y$, so they are inverses to each other.
Thus, only functionality is left to prove.
Let $xR_1y$ and $xR_1z$. Then $\exists x': yR_2x'R_1y$, but as $x(R_2\circ R_1)x'$, we must have $x=x'$ by hypothesis.
Now this implies $yR_2xR_1z$, so $y(R_1\circ R_2)z$ which yields $y=z$ again by the hypothesis.