Which instrument can a person play with 2 malformed fingers on each hand?

Question: Due to a birth defect, I have 2 malformed fingers on both hands (fingers 1,2).

(The picture is from the web just to illustrate the fingers i'm talking about.)
I've seen GuiGui Zheng videos, it is sweet, but I doubt if she can play more complex pieces that require both hands (for example).
And to my specific case, is there any chance of playing a Piano / Guitar professionally, with only 3 fingers on each hand (fingers T,3,4)?
Or my last chance in music is using digital software?
Edit:
Thanks for all the great answers! You have brought up some excellent and interesting instruments.
The next step is to see which instrument I enjoy the most, and just dive in to it!
Comment: If you can hold the sticks, you could play drums? What kinds of instruments are you open to trying?
Comment: I'm a bit late, but want to mention marimba and hammered dulcimer as potentials.
Answer: I don't know what type of music you're considering playing, but consider stepping outside of the piano/guitar realm. Trombone would be perhaps your best choice. A very difficult instrument to learn and master, but it requires only enough fingers to grip the instrument securely. (You could probably get away with a thumb and finger on each hand). The trombone can be used in any type of music; there are great trombonists that specialize in rock music, for example. Classical, jazz, new-age… the possibilities are endless.
Alternatively, if you are dedicated, consider specializing: if you learn to play pedal steel guitar (fewer finger requirements) and perhaps something like accordion, harmonica, etc., you could join a rock band with that skill-set fairly easily. Learn to sing, at least for backups, and you make yourself even more promising. (Again, I don't know what type of music you're looking at).
HOWEVER: Don't sell yourself short with only three fingers! Guitar would be tough, since the thumb can't do a whole lot, but with alternative tunings and a lot of practice, you can accomplish a lot. My father lost use of three of his fingers in a table-saw accident. He eventually regained full use of one of them, but had his middle finger amputated, and has no ability to bend his forefinger. (This is all on his left, fretting hand). He primarily plays bass in his bands now, as it's less frustrating for him, but hearing him on guitar, with the help of alternative tunings, it's difficult to tell he's doing it with fewer fingers.
As for piano, classical piano is out, I'm afraid. Some people may question that answer, but there are just too many incredible players out there, and the classical world is hesitant to accept anything but perfection (or close to it). However, piano in other styles is an option. Anything that doesn't have specific note requirements would be possible, in my opinion. So, jazz, rock… anything with chord symbols. It would be easier to do than guitar since the thumb is a fully used digit on both hands for the piano. I imagine you could do well if you were dedicated. The biggest thing is to learn (mentally) different styles and theory, etc., to compensate for any impossibilities on the instrument itself. Jazz/rock organ would be a good option; because too many notes muddies the sound, many players play simpler chords with embellishments that would be easier to accomplish and sound really good than with a piano where the sounds are easily distinguished.
My best advice is experiment a little bit, and then pick something and throw yourself into it. You can do things you set your mind to, it just might take extra time, effort, or modifications.
Comment: +1: DEFINITELY trombone. You may need some kind of accommodation for the grip, but that shouldn't be seen as an issue--it's such a strange instrument to hold that even players with typical hand structure use all sorts of gizmos for that. At most, a professional tenor trombone player needs to be able to grip the slide with the right hand, support the weight of the instrument with the left hand, and actuate a trigger with some finger on the left hand (usually thumb, but people have been known to customize).
Comment: Trombone is my baby, and it's definitely easily modifiable. I made myself a brace to basically squeeze the left (stationary) hand between the brace and the left hand slide grip, so I can actually play without gripping with my left hand at all. Very comfortable, and takes a lot of stress off. There are multiple inventions like that, and you can easily come up with one yourself too, as I did.

Again though, the biggest thing is finding something you enjoy; your body and brain will adapt to what you have to work with, and if you enjoy it, you'll advance faster than you think!
Comment: I"m not sure how easy accordion would be with just two usable fingers (seeing as it's basically a piano on one end), but harmonica is definitely on there as a versatile option.
Comment: @kqr https://en.wikipedia.org/wiki/Chromatic_button_accordion
Comment: Hey Josh, Great answer :)
Answer: I will only add Django Reinhardt as an example of guitarist with crippled fingers. He has only fingers 1 and 2 in his fretting hand intact. In his right hand, he used plectrum.
His playing is anything but limited. He has developed a distinctive, yet beautiful and technically demanding style - which is copied by numerous jazz guitarists to this days.
So I think with enough dedication on this hard task, guitar could be your instrument, up to the master level ( =Django level :)
Also, you have the option of alternate tuning and slide techniques, as others mentioned.
Good luck in your musical journey.
Comment: For me it would be challenge to teach such student, and i would give it a try. But sure he would be mainly on his own in his musical pursuit. But this is not necessarily bad - it's opportunity to  develop more personal and distinctive style - and that's a great value.
Comment: Yep, and it's seeing Django that convinced Tony Iommi not to give up. However, a guitarist with non-standard hands would have difficulty finding a teacher, and might expect to have to play their own arrangements.
Comment: I'd point out that Jerry Garcia and Phil Keaggy lost part of their picking hands.
Answer: I'm surprised no one has said "Theremin". You don't even touch the instrument. Although, it is a bit unconventional.
If you're not sure what I'm talking about: http://en.wikipedia.org/wiki/Theremin
Comment: I guess noone has meantioned it because it's quite unusual. I have actually played a concert with my orchestra (I play Tuba) where we had soloist playing the Theremin.
Answer: My wife was born with no thumb on her right hand. She successfully played French horn in high school, although she decided not to continue to be a musician after that time. Many of the brass instruments would be suitable.
Playing a violin-family instrument or erhu would depend on whether or not you could properly grip and manipulate the bow. If you can find a sympathetic teacher, they might evaluate your abilities in that area.
If you want to play guitar, use an electric guitar, because the neck is smaller and the strings are lighter in gauge and require less force to manipulate. Take an example from Django Rinehardt,  Tony Iommi and Phil Keaggy, all of whom had lost parts of fingers to injuries. And look at the later music of Les Paul when he became severely arthritic.
You can also play lap steel, pedal steel, and dobro-style guitars. Pedal steel, while an expensive and esoteric instrument, would be quite useful because you can use your feet in conjunction with your hands to form many chords that you could never play on a lap steel or dobro.
Study songwriting and singing! You can compose music and convince other musicians to play your compositions.
Furthermore, you are fortunate to live in a time when you can do so much with recording and editing music affordably on computers. You can build up music one track at a time playing only a few notes at a time, through programming. You have "accommodations" for you disability that were not available to musicians in previous generations.
Comment: You say that most brass instruments would be suitable, but considering he only have 2 fingers + thumb on each hand, it would be difficult to play a valve instrument where you need 3 fingers on the right hand for the valves. The thumb would be difficult to use here. Trombone is the best bet in the brass category.
Comment: Trombone is best, but 3-valve instrument is doable I think. Especially light valves, such as the trumpet. People with such disabilities gain much better control over the fingers they have left than people without.
Answer: If you're interested in guitar, try playing the guitar with a slide. You only need one finger for the slide. Try to have an alternative tunning for the guitar so you can have a chord played with the slide that consits all on one fret.
Toni Iommi had his fingers severed and was still able to play the guitar with tips made for his fingers.
Answer: Just tried it out on my guitar and I can grip a plectrum, strum and finger pick using those two fingers on my right hand.  Finger picking feels a little weird but it is achievable and is probably cos I'm not used to it.
The fret board is where the problems lie.
I can fret a power chord, its not comfortable at the moment but practice should improve the dexterity on that.  Making that opens up the rhythm lines of a lot of punk, rock and metal songs.  Unfortunately a lot of bar chords are probably out as are some others dependant on the numbers of fingers you require (if you've got the dexterity and size of hand for it you can bring the thumb round to fret the low E string).
Some riffs I can play some I cant, as above this is dependant on the finger positioning it requires of you.
I don't have a slide to hand but I cant imagine there being any problem using one.
Its certainly possible to play guitar, in the few minutes I've been trying for I've got Nirvana's Come as you are and RATM's Bombtrack most of the way there and a few more challenging riffs from other songs working.  My little finger is rarely used so there's not a lot of strength and dexterity in it, with time spent practising and exercising it this should improve.
I think you could develop your own style from what's available to you on guitar, with alternate tunings, capo's and slides you've certainly got a lot of scope to play with.
Comment: For what it's worth, you'll seldom see great rock guitar players using more than 3 fingers. Granted they all use their index and middle fingers, but being without them would certainly suggest increased strength in the remaining fingers. It's probably not so much which fingers or how many, but what you do with them. Check out Eric Clapton's playing on video and watch how few fingers he actually uses two on his right hand (pick) and two or three on his left.
Answer: I have malformed fingers, and I consider myself a fairly advanced guitarist.  I have malformation in my 1, 3, and 4 fingers and my 4 is missing a bone.  My recommendation is that if you really want to do something, you find a way to do it.  It may not be the same way as others, but thats okay.  Make your own "technique".  My sister has a similar malformation and this was the advice I gave her when she was training to be a hair stylist and was having difficulty with mastering the scissor techniques they were trying to teach her.  She is now considered a top-end hair stylist for rich folks.
Here is a link to a picture of my left (fretting) hand.
My left hand
Here is a link to me playing guitar (this was about 6 years ago):
My band (YouTube link)
Answer: I don't think your disability can prevent you for learning to play any instrument you desire. Maybe some will be harder to pick up, but it shouldn't stop you.
I recommend the Erhu, it is a violin but you don't need to apply much pressure the the strings. You would have to adjust your fingering, you'd move your hand up and down more than traditional players but it is completely possible for you. (I do recommend that you get tutored when you first start off and after you can study on your own after a few lessons.) It's a bit exotic so it might be difficult to come by depending on your geographical location.
Answer: Some alternative instruments come to mind, such as the (Appalachian) dulcimer or the autoharp.
Answer: You can play the piano and guitar with some limitations, and brass instruments with no limitations.
Answer: If you want something cutting-edge, some serious musicians are using devices such as iPads and iPods for both studio recordings and live performances. Have a look at MorphWiz, for example, developed and used by Juilliard-trained pianist Jordan Rudess.
Answer: An alternate solution for playing the guitar:
Play left-handed, where you fret with your right hand and strum with your left.
See Kurt Cobain (https://i.stack.imgur.com/lWoXG.jpg) and Jimmy Hendrix (https://i.stack.imgur.com/eq42e.jpg).
If you are unable to hold the pick, there are special picks you can get such as the Zero Gravity Orbit Guitar Pick, which wraps around your thumb and might make it easier to hold with your T and 3 fingers.
Comment: The problem is on both hands. Why left handed play is different?
Comment: Oh, I thought the problem was only on the left hand.  If it's on both hands, it wouldn't make a difference -- the same issues you will face either way.  Might I suggest instead becoming a vocalist?    You can also try the harmonica or if you want to stick with a stringed instrument, maybe something like the Santoor would work:[Santoor, Wikipedia](http://en.wikipedia.org/wiki/Santoor).
Answer: Bill Clements is a one handed-bass player

Granted his left hand is normal, but he has developed some unique styles due to his missing right hand and his prosthesis.
Francis Rocco Prestia only frets with one or two fingers (most of the time).

You probably have higher than average dexterity in your other fingers so it may be possible to develop your own style on a specific instrument. For example you could "Rocco" style with the left hand and "Ben Clements" style with the right hand.
Bass maybe a good choice. I've played outside gigs wearing mittens (because it was way too cold) and still was able to get most of the songs done just fine.
Answer: Chromatic button accordion could be an option for keyboard instruments.  Rudolph Würthner, a brillant musician, played it with just three fingers on his right hand after losing two in an accident (he played his accordion upside down, so that would have been the bass side).  On the melody side, having just three fingers will be more of a handicap, but chromatic button accordion fingering mostly relies on three fingers (though the middle three ones).
You'll be handicapped when playing polyphonic stuff with the right hand, but less so than on a piano keyboard.
Answer: I am surprised nobody has suggested touch-style guitar for this person. The Chapman Stick, the Warr Guitar and others are played in a totally different way and yet produce electric-guitar-like sounds.
There are also a wide array of non-traditional controllers for electronic instruments like touchpads and joysticks and contact pads and touchscreens.


A prime number random walk

Question: This question came to my mind thanks to this question which I found really interesting (and beautiful! Like the mathematician Philippe Caldero said in his book Histoires Hédonistes de Groupes et de Géométries (roughly translated) "Let us stop for a moment to contemplate the beauty of mathematics, that is after all the point of figures".).
It is also related to this other question.

The idea is to perform a walk following the following rules:

Initialisation: You start on the point $(0,0)$ which correspond to the integer $n=0$, and you will walk from one point of $\mathbb Z^2$ to another. You start by walking on the right.
Each horizontal step you take increases the integer $n$ by $1$.
When $n$ is equal to a prime number, you take one step up, and you change the direction you were going to (if you were walking from left to right you will walk from right to left, and reciprocally).

To illustrate the rules, a drawing will perhaps be more explicit:
$$\begin{matrix} & 7 & 8 & 9 & 10\\ & 7 & 6 & 5 \\ & 3 & 4 & 5 \\ & 3 & 2 & \\ 0&1&2& & \end{matrix}$$
Or with blue lines:

Well now nothing stops us from going a little further, which we will do until $n=100$, and then until $n=1\,000$.

It seems that the walk is almost always on the right side of the $y$-axis. Though the walk is crossing the axis a few times.
Let us walk until $n=10\,000$.

Then we realise that we have completely changing the side of the axis we were walking on.
Which rises some questions:

Will we cross the $y$-axis infinitely many times?
Will we be walking as much on each side of the plane? In the sense that if we denote by $L_n$ the set of integers less or equals to $n$ on the left side of the plane and $R_n$ the set of integers less or equals to $n$ on the left side of the plane:

$$\lim_{n\to\infty} \frac {L_n}n=\lim_{n\to\infty} \frac {R_n}n=\frac 12.$$

Will we walk out of any fixed vertical band centred on the $y$-axis?

Though any other result, or drawing (I did not succeed in drawing it for $n=10^5$), references about this walk would be of great interest.
Comment: If the question doesn't get a satisfactory answer here before the bounty expires, I'd recommend posting it to mathoverflow (making sure to link each post to the other).
Comment: Last question is easy: yes. There are infinitely many primes.
Comment: @ajotatxe Yes, but this does not imply that we will get as far off the $y$-axis as we want because we are constantly changing direction.
Comment: Perhaps I didn't understand the question. Whenever $n$ is prime, we go up one unit and change direction. Since there are infinitely many primes, we go up infinitely many times.
Comment: @ajotatxe Yes, but going up does not take us away of the $y$-axis. Going left or right does.
Comment: @ajotatxe: that increases the distance to what is conventionally called the $x$-axis
Comment: @MarcvanLeeuwen What I was saying wasn't clear then. I edited to try to be more specific.
Comment: A more concise definition would be $x_{n} = x_{n-1} + (-1)^n g_n$ where $g_n$ is the [Prime gap function](https://en.wikipedia.org/wiki/Prime_gap)
Comment: Your question reminds us this computational experiment we conducted a few years ago.
We called it the Jacobs Ladder and we published some results here https://www.mdpi.com/2297-8747/25/1/5 hope you find it interesting
best
Answer:
Will we walk arbitrarily far off the y-axis?

Yes, because there are arbitrarily long gaps between consecutive primes.

For every gap $n\in\mathbb{N}$, there is a sequence of $n-1$ consecutive numbers, none of which is prime:
$$n!+2,n!+3,\dots,n!+n$$
In other words, there is no finite bound on the gap between two consecutive primes.
Hence there is no limit as to how far off the y-axis your illustration goes...
Comment: Indeed, the path cannot remain in a fixed size vertical band (in particular not in one centred at the $y$-axis. But you cannot tell whether ones goes off without bound to the left or to the right, or to both (which would imply crossing the $y$-axis infinitely often).
Comment: Woah, this is really cool. Great proof.
Comment: @MarcvanLeeuwen You are not negate prove given by barakmanos, aren't you?
Comment: "Indeed" means I agree.
Answer: Some more graphs:
Up to $n=100000 = 10^5$:

Up to $n=1000000 = 10^6$:

Up to $n=10000000 = 10^7$:

Up to $n=100000000 = 10^8$:

And finally, up to $n=1000000000 = 10^9$:
Answer:
Will we cross the $y$-axis infinitely many times?

Firstly, Let's lay out the assumptions related to this.

There are infinitely many primes.
The spacing between primes is Arbitrary.

Given that both of these are true, the answer is Yes for any point along the $x$ axis.
Given infinite time, and an infinite random walk left or right, any walk will eventually pass through any point.
EDIT:
Any walk which exists in a single axis, in this case, the $x$, will pass through any value of $x$ an infinite amount of times, given infinite time.
Assume the target $x=0$, where the walk is currently at $x=1$. The walk, has a $1/2$ chance to either, cross the $x=0$ within the next move.
But we need the chance that $x$ will ever cross $0$ again.
The percent chance for $x=2$ to reach $0$, within two turns, is $1/4$, which means that $x=1$ has, at least, a $1/2+1/4=3/4$ chance to successfully cross the $0$ in 3 turns.
As such, the chances that $x$ will be $0$ in exactly $x$ turns are $1/2^x$
This means that $x\to\inf$, $p\to0$ where $p$ is the chance that $x$ will equal $0$ in exactly $x$ moves.
$x$ cannot be $\inf$, so $p>0$. There is always a chance, and there are infinite tries. Even after failing,there's a 50% chance that your odds increase.
Thus, a Random Walk, given infinite time, will cross $x=0$, infinite times.
This Applies to Prime Gaps.
In this case, the Prime Gaps are just a random walk which changes direction at a Prime.
Below is a diagram showing how the Prime Walk (Blue) and Random Walk (Red) compare for values up to $y=500$.

Even though the Prime walk is strongly biased towards smaller numbers, there is no known maximum distance between prime gaps which means there is a chance, albeit an even smaller than normal, yet a non-zero chance that the next prime is far enough away to $x\le0$.
Of course, this proof is destroyed if Primes are either Proven non-infinite, against current proofs, or predictable.
Comment: I am not convinced, since even if gaps are huge, you could have walked far off the $y$-axis, so you will not necessarily cross it with a huge gap.
Comment: @E.Joseph I hope to have explained my reasoning well enough. Otherwise, I'm sorry, I'm still fairly new at this.
Comment: Nice explanations! I am not convinced this is a rigorous proof, because we don't know that for the prime walk going left or right is equiprobable. Nice illustration though, I love it!

A prime number random walk


Copy of innodb /data dir not working

Question: I successfully installed fresh 5.6.27 mysql through homebrew.
Now I want to restore innodb databases from previous mysql install. I copied data/ dir from the old one to a new one. It contains ibdata1, ib_logfile1, ib_logfile0 and all databases as directories with the tables .frm as well as .ibd files.
my.cnf are same in both installs.
However the new 5.6.27 is not loading databases after the restart.
Any tips?
Comment: possible duplicate of [How can I move a database from one server to another?](http://dba.stackexchange.com/questions/174/how-can-i-move-a-database-from-one-server-to-another)
Comment: anything relevant in the [error log](https://dev.mysql.com/doc/refman/5.1/en/error-log.html)?
Answer: Ok, I found that this brew install did set up data dir at /usr/local/var/mysql.
ps auxww|grep [m]ysqld helped to reveal that.
So I just copied there, restarted and voila, dbs are there.

Copy of innodb /data dir not working


command to edit /tcb/files/auth/s/someuser

Question: is there a command in HP Unix used to change for example min age for password in this file without actually editing the file?
/tcb/files/auth/s/someuser
it has to do with trusted or non-trusted system...
Answer: When using tcb use the following command:
<code>/usr/lbin/modprpw -m mintm=5 someuser
</code>
Alternatively you can use sam (equivalent to smitty)


How to show/hide a block at some content types using PHP filter?

Question: I want to show/hide my block at some content types so I'm using PHP filter. My code in block configuration is:
<?php
if(arg(0)=='eshop') { return true; }
if(arg(0)=='node' && is_numeric(arg(1)) {
  return false;
}
return false;
?>

With this code the block is visible at every page even if it returns false, even if arg(0) is 'node' and arg(1) is 170. But if I use only:
<?php
if(arg(0)=='eshop') { return true; }
?>

It will show the block corectly only at /eshop page.
What is this, a GIANT Drupal bug?
Comment: `if(drupal_get_path_alias('node/' . arg(1)) == 'eshop') { return true; }`?
Comment: eshop page works correctly and it is not a node, it is path defined by hook menu! Problem is that block is visible at every single pages, nodes, everything.
Answer: There is another alternative available ... which doesn't require the PHP filter to be enabled (which you should try to avoid whenever possible) ... Just use the Rules block visibility module. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
Need to show a block only for users registered more than a month ago?
Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
What about displaying or hiding a block based on current weather conditions?
All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is only shown for the page with an URL like /eshop).
For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".
Answer: Use PHP Code to filter, the content type and specific pages.
This code shall work on node pages, although you can use any code to filter accordingly.
<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
  $node = node_load(arg(1));
  if ($node->type == 'YOUR_CONTENT_TYPE_HERE') {
    return TRUE;
  }
  elseif (PUT ANOTHER CONDITION HERE (for specific pages)) {
    //return TRUE here also
  }
  else {
   return FALSE;
  }
?>

Answer: Nope it is not a bug, if you are using arg() it will always consider the original path, that means node/[nid]
Your /eshop is an alias of node/[nid] so the Drupal will use original path for arg()
If you want to use /eshop then use if($_GET['q'] == 'eshop') { return true; }
Comment: Actually 'eshop' is a path defined by hook_menu. Still don't understand how that code can return true on every page when it clearly should return false.
Comment: Use this
Comment: It is practically the same as I have.
Answer: Why use PHP filter when you can configure your block using the UI.
Answer: If you want to show your block to particular content type then you can set your Visibility settings by your content type .Please find the screenshot.
Comment: Yes it is true, however I should mention thtat I need display that block not only on pages of specified content type but also on some ohter pages. Your solution will show the block strictly at specified content types.
Comment: Can you please tell me which page and content type access to see your block.


Where do I find the comment IP address?

Question: I am searching for comments ip address in D8 and I can't find where they are located in database. In D7 it was easy to find.
Is there a chance that D8 is not storing the commenters ip address? If it is not, how can I store it?
Answer: IP addresses are stored in the hostname field of the comment entity (which you'd usually find in the comment_field_data table).
This functionality is disabled by default, though (see Stop logging comment IP addresses by default). To enable it, it looks like you need to set the config manually, e.g.
 \Drupal::configFactory()->getEditable('comment.settings')
   ->set('log_ip_addresses', TRUE)
   ->save(TRUE);

After running that, IP addresses will start being logged in the hostname field.
Comment: @isin – Of course you don't add any custom code to a core or contrib module. You don't reinstall comments. You can execute the code from this answers from a custom module's hook_update_N or from the command line via `drush ev "\Drupal::configFactory()->getEditable('comment.settings')->set('log_ip_addresses', TRUE)->save(TRUE);"`.
Comment: Thanks for the quick reply. There are 12k comments in my blog so far. If I add in comment.install I guess that I would have to reinstall comment module and lose all comments? Or I can add it in some other place?
Comment: Thank you Clive for the solution and leymannx for pointing out how to use the code. Started now a new installation and tried by using the drush ev... and it worked.

Where do I find the comment IP address?


What is $(\lnot p \implies q)$ relative to $(p \implies q)$? Does this relation (between one conditional and the other) have a name?

Question: Relative to $(p \implies q)$, the expression $(\lnot p \implies \lnot q)$  is the converse, since the second conditional is equivalent to $(q \implies p)$ (by contraposition).
Does the relation between $(\lnot p \implies q)$ and $(p \implies q)$ have a name? What is the first expression relative to the second?
Answer: Since $(\lnot p \implies q)$ is equivalent to $(p \lor q)$, the relationship between   $(\lnot p \implies q)$ and $(p \implies q)$ is the same as the relationship between $(p \lor q)$ and $(p \implies q)$. But since these are two different connectives there is no need to have a name for the relationship between them.


drupal_goto argument retrival

Question: I am redirecting my users with the following code:
drupal_goto("event/registration/failed",
    array(
      'query' => array('nid'=>$submission->nid, 'sid'=>$submission->sid),
    )
);

On the target page I am executing the following function:
function _event_registration_failed($nid, $sid){
  dsm($_REQUEST);

  drupal_set_message("TESTING NID: {$nid}");
  drupal_set_message("TESTING SID: {$sid}");
}

My the variables in the drupal_set_message calls do not have any data.
But, the $_REQUEST object above has the data I expected.
Is there a correct way to access argument passed with drupal_goto or is it correct to use the $_REQUEST object array?
Answer: Query arguments are available in $_GET. Drupal doesn't handle those query arguments for your menu callback; the only query argument Drupal automatically handles is $_GET['q'], which is the path for the requested page.
By default, $_REQUEST contains the contents of $_GET, $_POST and $_COOKIE. Drupal uses $_GET for the requested page path, and I would rather use $_GET also in this case, just to avoid possible conflicts.
In your case, those query arguments are accessible with $_GET['nid'], and $_GET['sid'].
If you define the menu handler with code similar to the following one, then your menu callback gets those values as arguments.
function event_menu() {
  $items["event/registration/failed/%/%"] = array(
    // …
    'page callback' => '_event_registration_failed',
    'page arguments' => array(3, 4),
  );

  return $items;
}

function _event_registration_failed($nid, $sid) {
  // …
}

You could get the node object, instead of the node ID, if you use the following code.
function event_menu() {
  $items["event/registration/failed/%node/%"] = array(
    // …
    'page callback' => '_event_registration_failed',
    'page arguments' => array(3, 4),
  );

  return $items;
}

function _event_registration_failed($node, $sid) {
  // …
}

drupal_goto argument retrival


How to generate a Randomized Complete Block Design?

Question: I'm studying agriculture and I'm looking for answers concerning one of my problem.
I have to implement a randomized complete block design and I would like to generate it with R.
I've found some answers in the pdf of the package named "agricolae". Nevertheless, I cannot manage to create it.
Does someone have an idea on how to do this please ?
I have 6 treatments and 4 blocks..
Answer: The agricolae package is useful for this task. In your case:
if(!require(agricolae)){install.packages("agricolae")}
library(agricolae)
treatment = letters[1:6]
design.rcbd(trt=treatment, r=4)

Comment: Thanks very much, that's exactly what I was looking for :) .. By the way, do you have any idea of how can I replace the letters I obtain (a, b, c, d, e, f) by either numbers (1 -> 6) or sentences/words such as Mod1, Mod2 -> Mod 6 ?
Comment: Yes, just replace the `treatment =` line.  For numbered treatments: `treatment = 1:6`.  For custom treatments: `treatment = c("Control", "N only", "P only", "N and P only", "NPK", "NPK plus micro")`
Answer: For an experiment it depends on what you want, do you want to analyze the data or setup the treatments into the blocks? I think you want the latter based on your question. To do this you need to allocate all 6 treatments once for each of the 4 blocks. To do this is R:
sample(1:6,size=6,replace=FALSE)

4 times to get the allocations for the 4 blocks. For me this gave:

sample(1:6,size=6,replace=FALSE)

[1] 6 3 4 1 5 2

sample(1:6,size=6,replace=FALSE)

[1] 5 2 4 6 3 1

sample(1:6,size=6,replace=FALSE)

[1] 2 6 3 1 5 4

sample(1:6,size=6,replace=FALSE)

[1] 3 6 2 1 4 5
These are the ways to allocate your treatments. Choose a numbering system for your treatments and you're good to go.


Jquery fixed size

Question: I try to fix background and image size and have a conflict with JQuery.
I practice here: http://jsfiddle.net/CyberTramp/uZXQu/
The problem is background-image & div should have a same size like browser resolution "always be in center", my original image width 1500 px
What I have:
CSS
.right_circle
{
    position: relative;
    width: 50%;
    height: 300px;
    overflow: hidden;
    background-image: url('http://cloud.graphicleftovers.com/9583/261791/blue-and-orange-circle-globe.jpg'); //original size 500 × 500 must = screen resolution
}
.left_circle
{    position: relative;
    background-image: url('http://www.kidopo.com/wp-content/uploads/2011/05/Circle-mazep.gif');
}

HTML

JQuery
$('html').mousemove(function(e) {
    var page = $('html').width();
    if (page / 2 > e.pageX) {
        $('.right_circle').css('width', page - e.pageX);
    } else {
        $('.right_circle').css('width', page - (e.pageX - (page / 2)) - (page / 2));
    }
});

Comment: is this http://jsfiddle.net/uZXQu/5/, what u are looking for???
Comment: i have big image size and try to make them smaller.
no-repeat it no for this situation. for example if screen have resolution 800x600 my image have 1500 user can see only small part of image. I try to fix it deference way and have a problem with jquery
Answer:
The problem is background-image & div should have a same size like
  browser resolution "always be in center"

Add the following CSS:
background-repeat: no-repeat;
background-position:center;
background-attachment:fixed;
background-size: 100% 100%;

Also try to re-organise your styles a little to only specify shared styles ones.
Complete CSS:
.right_circle, .left_circle{
    background-repeat: no-repeat;
    background-position:center;
    background-attachment:fixed;
    background-size: 100% 100%
}

.right_circle{
    width: 50%;
    height: 300px;
    background-image: url('http://cloud.graphicleftovers.com/9583/261791/blue-and-orange-circle-globe.jpg');
}

.left_circle{
    background-image: url('http://www.kidopo.com/wp-content/uploads/2011/05/Circle-mazep.gif');
}

DEMO - background-image & div have a same size as browser and are centred
Comment: I would guess as CyberTramp is using circles it might be better to use `background-size: contain;` rather than `100% 100%` - could be totally off however ;)
Comment: Applying `background-size: contains;` re-sets the size and the circle does not fill the browser window. As far as I could tell that was one of the requirements. I could be wrong though as requirements are not perfectly clear and if that is not the case, `contains` sounds perfectly fine.
Comment: @CyberTramp: Could you let me know if this is what you were looking for and if not, feel free to add what needs to change and I will update the answer.
Comment: @FrançoisWahl I'm not sure if that's a typo but it should be `background-size: contain;` - and in my tests using your code but switching in `contain` instead keeps the aspect ratio of the circles *(rather than stretching them to fit)*. But hey CyberTramp seems happy so alls good :)
Comment: @pebbl: I know. But `stretching to fit` is what OP wanted as far as I could tell. But you are correct if OP wants to keep the aspec-ratio of the circle, then `background-size: contain;` should be used instead.
Comment: @CyperTramp: If you feel this answer has helped solve your issue, feel free to accept the answer by selecting the tick mark to the left of the answer just below the vote buttons. It also indicates to future users who experience similar issue what worked for you.

Jquery fixed size


Two dimensional array of objects in C++

Question: I am migrating a scientific code from Java to C++. Please tell me:
a) What's wrong with the two functions?
b) How can I solve the problem? I can use the int** like a two dimensional array but not the Agent**.
I receive this error: "No operator = matches this operand".
In normal C we could assign NULL to pointers. We could also use a type** like a two dimensional array (i.e. a[i][j]) (two dimensional space for objectSpace and agentSpace is allocated somewhere else).
    int** objectSpace;
    Agent** agentSpace;

    void Space::removeAgentAt(Point p)
    {
        agentSpace[p.x][p.y] = NULL;
    }

    void Space::putAgentTo(Agent agent, Point p)
    {
        agentSpace[p.x][p.y] = agent;
    }

Answer: agentSpace is a pointer, and agentSpace[p.x] is a pointer, but agentSpace[p.x][p.y] is not a pointer.
C++ is not the same as Java; objects are (usually) referred to by value, not by reference.
Comment: Oli, I need to have an array of Agents and modify the array to show where in the space are the agents.

Could you possibly give a bit advise or kindly a solution?
Comment: @wmac do you know the dimensions of the array at compile time, or only at runtime? You are likely better off using a standard library container.
Comment: Unfortunately dimensions are unknown but the space is too large. It may contain 1000*1000 cells. I thought that's too much for containers.
Comment: @wmac if the dimensions are too large for a container of containers (vector of vectors seems to fit your use-case best) then they are too large for a dynamically allocated array.
Answer: In C++, NULL is just an alias for 0. Unless you have coded conversion from integers to Agent objects, you can't assign NULL to an Agent.
One solution is to make a dummy Agent object, like Agent AgentNone; and use that instead of NULL. You might have to implement comparison operators if you want to check if an Agent object is equal to AgentNone.
Answer: Look at it like this, for Agent** agentSpace, the first * gives you access to the first dimension of the array, the second * gives you access to the second dimension.
Agent** is a pointer to pointers - or in your case an array of pointers. When you attempted to do agentSpace[p.x][p.y] = NULL, you were trying to assign NULL in to what the compiler thinks is a full object of type Agent You need another level of indirection:
Agent*** agentSpace =
    {
         { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 },
         { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 },
         { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }
    };

Answer: Guess you need to define an assignment operator for your Agent class?
Answer: To make the code easier to match against the original, provide the array dimensions:
int   objectSpace[100][200];   // but use the actual dimensions
Agent agentSpace[250][300];    // todo:  fix dimensions

Even better would be to use defined constants:
int   objectSpace[OS_X_MAX][OS_Y_MAX];
Agent agentSpace[AS_X_MAX][AS_Y_MAX];

If this is in a header file seen by all modules, then the code you have will work correctly.  If there are any places where one of these arrays is passed as a parameter, then the function prototype and implementation likely will have to be rewritten.
Comment: @wmac then I would suggest the vector of vector approach
Comment: The size of arrays is not known. I am using dynamic array allocation templates in this page: http://www.codeproject.com/Articles/21909/Introduction-to-dynamic-two-dimensional-arrays-in
Comment: I have already used that method to create the arrays. It works with integers (like the example on that page). But objects of the type Agent won't work with a two dimensional dynamic array of Agent.

Two dimensional array of objects in C++


Saber o nth do ítem clicado para selecionar um input no mesmo nth?

Question: Tenho uma tabela onde possuo um checkbox para habilitar a edição de vários ítens ao mesmo tempo, ou seja posso editar vários desde que o input esteja selecionado, mas tenho um problema que se desejar editar apenas um não ter a necessidade de selecionar o checkbox.

function selecionaCompromissos() {
  var ids = document.getElementsByClassName('agrupaPagto');

    gravaArray(ids);
  }

function gravaArray(dados) {
  var array_dados = dados;

  var teste = Array();
  var contador = 0;

  for (var x = 0; x <= array_dados.length; x++) {
    if (typeof array_dados[x] == 'object') {
      if (array_dados[x].checked) {
        teste[x] = array_dados[x].id;
        contador++;
      }
    }
  }
  teste = teste.filter(Boolean);
  console.log(teste);
}

      #
      Nome
      Número
      Vencimento
      Parcela
      Valor
      Boleto

      <input class="agrupaPagto" id="10" value="125" name="txtAgrupa" type="checkbox">
      Art Pneus
      343
      10/10/2017
      2 de 2
      R$ 125,00

      Em aberto  Pagar

      <input class="agrupaPagto" id="11" value="221.00" name="txtAgrupa" type="checkbox">
      Maria Bonita
      532
      18/10/2017
      1 de 4
      R$ 221,00

      Em aberto  Pagar

A aplicação funciona mas tem que estar selecionado, mas a questão fica se o usuário for editar apenas uma linha e selecionar sem a necessidade de marcar o checkbox?
Answer: Você pode pegar o checkbox da linha clicada com:
elemento.closest('tr').getElementsByTagName('input')[0];

Analisando seu código, uma sugestão é passar o link clicado enviando um this como parâmetro na função selecionaCompromissos(), assim:
Pagar

Desta forma, o "elemento" citado lá acima seria esse this recebido na função como i:
function selecionaCompromissos(i) {...

Depois você pode repassar essa informação para a outra função gravaArray() pegando a id do respectivo checkbox e criar a array apenas com 1 id. Ficaria assim:

function selecionaCompromissos(i) {

   var idc = i.closest('tr').getElementsByTagName('input')[0];

   var ids = document.getElementsByClassName('agrupaPagto');

   gravaArray(ids,idc);
}

function gravaArray(dados,idc) {
   var array_dados = dados;

   var teste = Array();

   if(idc != null && !idc.checked){
      teste.push(idc.id);
   }else{
      var contador = 0;
      for (var x = 0; x <= array_dados.length; x++) {
         if (typeof array_dados[x] == 'object') {
            if (array_dados[x].checked) {
               teste[x] = array_dados[x].id;
               contador++;
            }
         }
      }
   }
   teste = teste.filter(Boolean);
   console.log(teste);
}

      #
      Nome
      Número
      Vencimento
      Parcela
      Valor
      Boleto

      <input class="agrupaPagto" id="10" value="125" name="txtAgrupa" type="checkbox">
      Art Pneus
      343
      10/10/2017
      2 de 2
      R$ 125,00

      Em aberto  Pagar

      <input class="agrupaPagto" id="11" value="221.00" name="txtAgrupa" type="checkbox">
      Maria Bonita
      532
      18/10/2017
      1 de 4
      R$ 221,00

      Em aberto  Pagar

Comment: excelente a explanação sobre a resposta, é algo do tipo que ensina e também resolve. Valeu.


Is the Noetherian condition of $R$ really necessary here?

Question: This is from an old Ph.D Qualifying Exam of Algebra.

Let $R$ be a commutative Noetherian ring with unity and $M$ be a nonzero simple $R$-module. Prove that there exists a prime ideal $I\subset R$ such that $R/I \cong M$ as an $R$-module.

My solution: Since $M$ is simple, it is cyclic. i.e. it is generated by a single element, say $m$.
Then $\text{Ann}(M)=\text{Ann}(m)$, where $\text{Ann}$ means the annihilator of a given module(or an element). Now prove that $I=\text{Ann}(m)$.
Define a map $\phi: R\to M$ as $\phi(r)=rm$, $r\in R$, $m$ is a generator of $M$. Clearly $\phi$ is an $R$-module epimorphism and $\ker(\phi)=\text{Ann}(m)$. Therefore, $R/\text{Ann}(m)\cong M$.
Now it remains to show that $\text{Ann}(m)$ is a prime ideal of $R$.
Let $a,b\in R$ and $ab\in \text{Ann}(m)$. Suppose that $b\notin \text{Ann}(m)$. Then $bm\neq 0$, so the submodule $(bm)$ of $M$ is nonzero and thus $(bm)=M$ by simplicity of $M$.
$\therefore \text{Ann}(bm)=\text{Ann}(m)$, and $abm=0$ implies $a\in \text{Ann}(bm)$, so $a\in \text{Ann}(m)$. This completes the proof.

On the solution above, the Noetherian condition of $R$ is not used. Is my solution correct? If so, then the Noetherian condition is indeed unnecessary.
Answer: That seems okay to me. A slight generalization: one can take $I$ maximal.
As you said, given a nonzero $m \in M$ we have a module epimorphism,
$$
l : R \longrightarrow M
\\ r \mapsto rm
$$
and therefore if $I := \ker l$ by the first isomorphism theorem we get that $M \simeq R/I$. Now, this epimorphism induces a bijection from the $R$-submodules of $M$ to the $R$-submodules of $R/I$, which are in correspondence with the $R$-submodules (that is, the ideals) of $R$ that contain $I$. In particular, since $M$ has only two submodules, there are only two submodules that contain $I$: either $R$ or itself. This proves that $I$ is maximal, and in particular, prime.


How do lambdas store references to variables

Question: I feel that this is an easy question but I was unable to find answer. After executing this simple code:
public class MyClass {

    int value;

    static interface MyFunctionalInterface {
        void foo();
    }

    public static void main(String args[]) {
       MyClass xxx = new MyClass();
       MyFunctionalInterface myLambda = () -> System.out.println("Value: " + xxx.value);

       xxx.value = 777;
       myLambda.foo();

       xxx.value = 888;
       bar(myLambda);
    }

    static void bar(MyFunctionalInterface myLambda) {
        myLambda.foo();
    }

}

The result (as expected) is just:
Value: 777
Value: 888

My question is about xxx object. How does the lambda store reference to this object? Is there some anonymous class created which stores "Value: " string and xxx object? This object still exists in bar function, so it has to be stored somehow somewhere.
Edit:
Basing on hint from @Sweeper it can be concluded that lambdas store references to such variables inside themselves.
If (with above code) we print:
System.out.println(Arrays.toString(myLambda.getClass().getDeclaredFields()));

we will get:
[private final MyClass MyClass$$Lambda$1/0x0000000800000c08.arg$1]

However, if code is modified and lambda created without xxx:
MyFunctionalInterface myLambda = () -> System.out.println("Just string");

Then declared fields will be empty and it will print just "[]"
Comment: Also try printing `Arrays.toString(myLambda.getClass().getDeclaredFields())` :-)
Comment: IIRC the language specification doesn't say, so the answer to "how does the lambda store reference to this object" is "however you like as long as it works" :) If you want to ask about a specific implementation of the JVM, please [edit].
Comment: I'm asking from memory leak perspective, since if lambda will store reference then object will not be garbage collected, so it might cause leaks, right? That's why I would like to understand it better.
Comment: Good hint with the print, it gives:
[private final MyClass MyClass$$Lambda$1/0x0000000800000c08.arg$1]
so it must be stored there!
Comment: "I'm asking from memory leak perspective". It's no different from any reference-holding thing. The lambda will prevent `xxx` from being GC-d until itself can be GC-d. In your example, the lambda goes out of scope at the end of `main` and both could be GC-d then.
Answer: First let me just doublecheck that you understand the way java references and objects work or the explanation isn't going to make any sense:

MyClass xxx = new MyClass();

This [A] reserves some space on the heap large enough to store 1 instance of MyClass, [B] constructs a new instance of MyClass into that space, and then [C] assigns the pointer pointing at the location where this object now resides on the heap to xxx. Because 'pointer', from C, kinda implies you can e.g. increment it or print it, as an encore, we shall not call it a 'pointer' and instead we call it a 'reference'. But, it's.. a pointer.

xxx.value = 777;

This doesn't 'change' anything - xxx. is 'take variable xxx, follow the pointer, then go change stuff over on the heap. Which, crucially, means xxx does not change. Only the object xxx is pointing at is being changed here.
Thus, xxx is effectively final throughout this method. It's a constant. Which means the only thing we need to do here is ensure the lambda continues to know about it. Given that a lambda can 'outlive' the context of the method it is created in, this is a bit of an issue: Ordinarily, local variables (and method parameters are a kind of local var) are declared on stack and therefore poof out of existence when a method ends. Clearly then, xxx cannot live there. At least, not the one the lambda uses.
Java solves this problem not in the way most languages do. Most languages realize xxx has to outlive the method and 'hoist it onto the heap'. Java doesn't do this (after all, things that live on heap, or can escape via lambdas to other threads, all of a sudden need to answer hairy questions such as "does that mean local variables can now be marked volatile?"). Instead, java just clones it. Because clones would get real confusing if code also modifies the variable (which of the clones are you modifying?), your code wouldn't even compile unless xxx is final! - the one 'gift' java gives you is that if your variable could have been marked as final without causing issues, i.e. you only write to it once, then you can omit final and java will just assume it. Try it! Take that code and reassign xxx anywhere (in the lambda or outside of it; does not matter), and you'll get an error that you can't use xxx in the lambda at all as it is not 'effectively final' (the java spec's term for "either marked final, or could have been so marked without issue").
So now it's simply: xxx in the context of the method itself remains a stack-allocated variable as normal. And the lambda gets a clone of it, which.. yes, lives on heap. There is an object representing this lambda that contains its captured state. Javac knows that only the variables actually used by the lambda need capturing (which may include this!), and captures only what is needed.
Lambdas which capture zero state are special in that they don't need an object at all to represent their state. Instead, those end up, effectively, as static methods and the lambda exists as a MethodRef object at the class/JVM level.
Regardless of whether your lambda has state or not, you should never use the object identity of one; the JVM spec says your code won't straight up crash but whether that identity has a meaningful uniqueness is not guaranteed. In other words, don't use them as keys in maps, don't lock on them (synchronized). Don't == them.
Comment: "*xxx is effectively final throughout this method. It's a constant*." A constant reference. It's not a constant; it's mutable.
Comment: @Michael The pointer value is constant. The word 'mutable' is more nebulous than your comment makes it out to be (example: For most technical definitions of 'immutable', String __is not__. The point isn't: "Let's debate about immutability some more", the point is: "Define what particular aspect you're actually interested in". This answer already makes that clear before using the term - the POINTER VALUE is constant.
Comment: "*This answer already makes that clear before using the term - the POINTER VALUE is constant*" No, it doesn't. That's precisely why I left that comment. You can't just assert things about the clarity of your writing in the face of someone who's read it telling you otherwise. The most you can say is "I *think* it's clear enough". Fine, but I don't agree.


Reference book for practice problems on Inference

Question: I was wondering if there is any book which has loads of problems on statistical inference.
Desired topics are

Unbiasedness
Consistency
Sufficiency
Completeness
Rao Blackwell Theorem
etc.
Answer: I recommend three books :

Statistical Inference 2nd Edition by Casella and Berger Chapter 6 and Chapter 7 .
Introduction to the Theory of Statistics by Mood Chapter VII
My favorite book Mathematical Statistics for Economics and Business by Mittelhammer Chapter 7 and Chapter 8


500 Internal Server Error when setting up Apache on Ubuntu+Django

Question: I tried with Apache on ubuntu 9.04 and get the same error: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webmaster@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
And my apache/error.log is:
<code>[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] ServerName: 'sapint2'

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] DocumentRoot: '/etc/apache2/htdocs' [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] URI: '/'

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] Location: '/'

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] Directory: None

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] Filename: '/etc/apache2/htdocs'

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] PathInfo: '/'

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] Traceback (most recent call last):

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/lib/python2.7/dist-packages/mod_python/importer.py", line 1537, in HandlerDispatch\n default=default_handler, arg=req, silent=hlist.silent)

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/lib/python2.7/dist-packages/mod_python/importer.py", line 1229, in _process_target\n result = _execute_target(config, req, object, arg)

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/lib/python2.7/dist-packages/mod_python/importer.py", line 1128, in _execute_target\n result = object(arg)

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/modpython.py", line 180, in handler\n return ModPythonHandler()(req)

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/modpython.py", line 142, in call\n self.load_middleware()

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 45, in load_middleware\n mod = import_module(mw_module)

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module\n import(name)

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/middleware.py", line 4, in \n from django.utils.cache import patch_vary_headers

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/utils/cache.py", line 25, in \n from django.core.cache import get_cache

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/cache/init.py", line 187, in \n cache = get_cache(DEFAULT_CACHE_ALIAS)

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/cache/init.py", line 179, in get_cache\n cache = backend_cls(location, params)

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/cache/backends/memcached.py", line 139, in init\n "Memcached cache backend requires either the 'memcache' or 'cmemcache' library"

[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] InvalidCacheBackendError: Memcached cache backend requires either the 'memcache' or 'cmemcache' library [Sat Oct 06 09:51:30 2012] [notice] caught SIGTERM, shutting down [Sat Oct 06 09:51:31 2012] [notice] mod_python: Creating 8 session mutexes based on 150 max processes and 0 max threads.

[Sat Oct 06 09:51:31 2012] [notice] mod_python: using mutex_directory /tmp

[Sat Oct 06 09:51:31 2012] [notice] Apache/2.2.17 (Ubuntu) PHP/5.3.5-1ubuntu7.11 with Suhosin-Patch mod_python/3.3.1 Python/2.7.1+ mod_wsgi/3.3 configured -- resuming normal operations
</code>
I need some help
Thanks
Answer: What Django version you are using? Have you tried acting on the log messages you got and installed one of the suggested memcache libraries? It's right there:
<code>[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File
  "/usr/local/lib/python2.7/dist-packages/django/core/cache/backends/memcached.py",
  line 139, in init\n "Memcached cache backend requires either the
 'memcache' or 'cmemcache' library"
[Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] InvalidCacheBackendError:
  Memcached cache backend requires either the
 'memcache' or 'cmemcache' library
</code>
This is the reason your apache returns a 500 error.
Comment: Hi for the tips. Django version is: 1.2.5 and memchached is installed. I troed with install cmemcache library and udo easy_install sqlalchemy and sudo easy_install -U python-memcached.
Comment: Also: sudo apt-get install unixodbc unixodbc-dev freetds-dev tdsodbc. SQLAlchemy==0.7.9 unixODBC 2.2.14 Version: 0.82-7


Trigonometry Inequality of Sinus Half-Angles Product

Question: Prove that
$ \sin \frac{\alpha}{2}\sin\frac{\beta}{2}\sin\frac{\gamma}{2} \le \frac18 $
if   $\alpha,\beta,\gamma$ are angles in triangle $(\alpha+\beta+\gamma=180^\circ)$
Answer: Using the half-angle formulas then your inequality is equivalent to
$$\sqrt{\frac{(s-b)(s-c)}{bc}}\sqrt{\frac{(s-a)(s-c)}{ac}}\sqrt{\frac{(s-a)(s-b)}{ab}}\le \frac{1}{8}$$
can you finish?
This is equivalent to$$8(s-a)(s-b)(s-c)\le abc$$
and this is $$(-a+b+c)(a-b+c)(a+b-c)\le abc$$
now we use the Ravi Substitution and we have
$$(x+y)(x+z)(z+x)\geq 8xyz$$
now use $$AM-GM$$ and the proof is finished.
I have another proof, note that $$f(x)=\log(\sin(x))$$ is concave, since $$f''(x)=-\frac{1}{\sin^2(x)}$$ and then we get
$$\log\left(\sin\left(\dfrac\alpha2\right)\right)+\log\left(\sin\left(\dfrac\beta2\right)\right)+\log\left(\sin\left(\dfrac\gamma2\right)\right)\le 3\log\left(\sin\left(\dfrac\pi6\right)\right)=\log\left(2^{-3}\right)$$ ready
Comment: Not convex surely? Concave if you want to now get on the Jensen bus.
Answer: By AM-GM and Jensen inequalities in succession,
$$\prod_{cyc} \sin \frac{\alpha}2 \leq\left[ \frac{\sum_{cyc} \sin \frac{\alpha}{2}}{3}\right]^3 \leq  \left[ \frac{ 3 \sin \frac{\alpha+\beta+\gamma}{6}}{3}\right]^3=\frac18$$
Answer: Hint:
Let $2y=2\sin\dfrac\alpha2\sin\dfrac\beta2\sin\dfrac\gamma2=\sin\dfrac\alpha2\left(\cos\dfrac{\beta-\gamma}2-\sin\dfrac\alpha2\right)$
$$\iff\sin^2\dfrac\alpha2-\sin\dfrac\alpha2\cos\dfrac{\beta-\gamma}2+2y=0$$ which is a Quadratic Equation in $\sin\dfrac\alpha2$
As $\sin\dfrac\alpha2$ is real, the discriminant must be $\ge0$
Comment: See also : https://math.stackexchange.com/questions/952893/cos-a-cos-b-cos-c-leq-frac18  and  https://math.stackexchange.com/questions/949530/in-triangle-abc-show-that-1-lt-cos-a-cos-b-cos-c-le-frac-32 and https://math.stackexchange.com/questions/639890/minimum-value-of-cosa-b-cosb-c-cosc-a-is-3-2
Answer: In the standard notation we need to prove that
$$\prod_{cyc}\sqrt{\frac{1-\frac{b^2+c^2-a^2}{2bc}}{2}}\leq\frac{1}{8}$$ or
$$\prod_{cyc}\sqrt{\frac{(a+b-c)(a+c-b)}{bc}}\leq1$$ or
$$\prod_{cyc}(a+b-c)\leq abc$$ or
$$\sum_{cyc}(a^3-a^2b-a^2c+abc)\geq0,$$ which is Schur.
The inequality $$\prod_{cyc}(a+b-c)\leq abc$$ we can prove also by the Ravi's substitution.
Indeed, let $a=y+z$, $b=x+z$ and $c=x+y$.
Thus, $x$, $y$ and $z$ are positives and we need to prove that
$$\prod_{cyc}(x+y)\geq8xyz,$$ which is obvious by AM-GM:
$$x+y\geq2\sqrt{xy}.$$
Also, we can use the following way.
We need to prove that $$\sin\frac{\alpha}{2}\left(\cos\frac{\beta-\gamma}{2}-\sin\frac{\alpha}{2}\right)\leq\frac{1}{4}$$ or
$$4\sin^2\alpha+1\geq4\sin\frac{\alpha}{2}\cos\frac{\beta-\gamma}{2},$$
which is true by AM-GM:
$$4\sin^2\alpha+1\geq4\sin\frac{\alpha}{2}\geq4\sin\frac{\alpha}{2}\cos\frac{\beta-\gamma}{2}.$$
Also, the starting inequality is equivalent to $$R\geq2 r,$$ which is obvious.
Comment: pardon Michael, but $$R\geq 2r$$ is not obvouis, ask Mr. Euler
Comment: I think it's obvious! Draw $\Delta A_1B_1C_1$ such that $A$ is a midpoint of $ B_1C_1$, $B$ is a midpoint of $A_1C_1$ and $C$ is a midpoint of $ A_1B_1$


Proving that if coprime $\alpha_{i}\in R$ divide b, then $\alpha_{1}...\alpha_{n}$ divide b.

Question: Let $R$ be a principal ideal domain and let $\alpha_{1},...,\alpha_{n}\in R$ be such that $(\gcd(\alpha_{i},\alpha_{j}))=(1)$.
Let $b\in R$ such that each $\alpha_{i}|b$.
I want to show that $\alpha_{1}\alpha_{2}...\alpha_{n}|b$.
I have managed this for $\alpha_{1}$ and $\alpha_{2}$, as follows;
$\alpha_{1}|b$ so there exists $s_{1}\in R$ such that $b=\alpha_{1}s_{1}.$
By Bezout's lemma for principal ideal domains, there exists $r,s\in R$ such that $r\alpha_{1}+s\alpha_{2}=\gcd(\alpha_{1},\alpha_{2})=1$
Then $s_{1}=rb+s\alpha_{2}s_{1}$. Clearly $\alpha_{2}|s\alpha_{2}s_{1}$ and we know $\alpha_{2}|b$, so $\alpha_{2}|s_{1}$
So there exists $q\in R$ such that $s_{1}=\alpha_{2}q$
So $b=\alpha_{1}\alpha_{2}q$, and thus $\alpha_{1}\alpha_{2}|b$
I feel like this could be generalized to some kind of inductive argument, but I can't even seem to manage to show that $\alpha_{1}\alpha_{2}\alpha_{3}|b$.
Any help would be much appreciated, thanks!
Answer: Each principal ideal domain is factorical, so you can simply use factorization into prime elements. Then all you need to show is that being coprime means not having any prime factors in common (up to multiplication with units, etc.).


Navigation Bar animation turning white

Question: Okay so initially I thought my problem was to do with a new background I was adding. However I have now discovered that actually it just started happening for no reason that I can remember...
The problem that is occurring is when I animate back to my original view where I am hiding my navigation controller bar from my tableview which is displaying my navigation bar. the navigation bar is replaced by a white block.
I am not sure why this is happening.. This is how I have hidden my bar in the view that its animating too..
<code>- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:NO]; //Hides the navigation bar
//..
}
</code>
Answer: Your view may not be loaded by the time -viewWillAppear is called (come to think of it, it shouldn't be loaded).  Move your implementation into -viewDidLoad.
Edit:  It is because when you hide the navigationBar, your view often doesn't compensate for the height of the bar without the wantsFullScreenProperty being set to YES, and the nav bar set translucent.
Comment: I have now moved both implementations to viewdidload.. however I still have the same problem and its only happening when I animated back to the original View which is the "normal view" code I have listed.
Comment: okay so I have tested without the backgrounds and its doing the same thing..... so now it must be something else...
Comment: I have updated my question to suite whats actually happening.
Comment: The error is happening on the second view. I think I did not explain myself good enough. The first view is hiding the nav bar, the second view is not. when I animate from the second view to the first view the second views navigation bar goes white. If I put the code into viewDidLoad then when I go back to the first view the navigation appears again.
Comment: okay this worked when I put a [self.navigationController setNavigationBarHidden:YES animated:YES]; in side viewdidDissapear in the second view :) thanks for the help.

Navigation Bar animation turning white


Bound of an integral of a bounded function

Question: If a function $f$ is bounded such that $|f|<M$, then can we say:
$$ \left|\int_a^ \infty f(x)\, \mathrm{d}x \right| \le \int_a^ \infty  |f(x)| \,\mathrm{d}x  \le  \int_a^ \infty M\, \mathrm{d}x$$
Is that correct?
Thank you!
Comment: But the last expression is just $\infty$ and the inequity does not provide useful information, I think?
Answer: It is correct.
Since $ -|f| \leq f \leq |f|$:
$$
-\int_a^\infty |f(x)|\,dx\leq \int_a^\infty f(x) \,dx \leq \int_a^\infty |f(x)| \,dx \\
\therefore \left| \int_a^\infty f(x) \,dx \right| \leq \int_a^\infty|f(x)| \,dx
$$
The right one easily follows from the precondition.
$$
|f(x)| < M \Rightarrow |f(x)| \leq M \\
\int_a^\infty |f(x)|\, dx \leq \int_a^\infty M\,dx
$$
Combine these two to get your desired inequality.
Comment: Suppose that we have a function $f=2$ which is surely bounded with a boundary $M\ge 2$,  now we integrate $f$ over the interval $[a,\infty)$, which gives us infinity, i.e., the integral is not bounded. The problem in your proof is that the interval of integration is infinite.


Telnet SmarterMail: 550 This is a submission only port. You must authenticate before sending mail

Question: I have a "newer" server running Windows Server 2019 and I installed Smartermail FREE Edition so I could send mail via PHP/CDONTs from contact forms to my email address.
I tried matching the settings on an older Server with an older Smartermail but I can't get it to work.
When I try "telnet 127.0.0.1 587" in command prompt, then EHLO then mail from: etc... I get the error
550 This is a submission only port. You must authenticate before sending mail
I also get the error SMTP Error: Could not connect to SMTP host. in phpMail, but I suspect I need to get the 550 submission only port error fixed first.
I have tried searching Google and server fault and can't find a solution.
I'm not sure what logs that I need to provide, nor know where to find them.
Your assistance is appreciated.
Answer: SMTP/MSA on port 587 is for the Mail Submission Agent role only. Client authentication is required at all times. If you don't want to authenticate, use the standard SMTP port 25.
Normally, the server will need some other way of trusting you when sending from a local email address, e.g. you'd need to connect from a private IP address, to  an internal-only interface, to a private-only IP address or something similar.
Comment: Thank you for your assistance. I feel like I'm so close but so far. I switched to using port 25 when sending mail and it says that the user isn't found. However, it is found. So now I  have to figure out how to get Smartermail to send and ignore the Smartermail user base when validating users.
Comment: You're not providing sufficient information for anyone to comment that.
Comment: I understand. I'm just not sure what information that I need to provide.
Comment: Thought about including your Smartermail config? Which is where you define trusted endpoints?
Comment: there is just a ton of configuration in Smartermail. I wasn't sure what was relevant.


Laravel log file specific to a package

Question: I'm writing a couple of laravel packages and I'm wondering if it is possible to have the package write to a specific log file but only for messages related to the package?
I tried making a logging.php file in the packages/myorg/mypackage/config (below) but it doesn't seem to do anything.
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;

return [
    'default' => env('LOG_CHANNEL', 'stack'),
    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single'],
            'ignore_exceptions' => false,
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/mypackage.log'),
            'level' => env('LOG_LEVEL', 'debug'),
        ]
    ]
];

I am using "jeroen-g/laravel-packager" to set up the packages. It appears to manually load the mypackage.config in the ServiceProvider bootForConsole
protected function bootForConsole(): void
{
    // Publishing the configuration file.
    $this->publishes([
        mypackage.'/../config/mypackage.php' => config_path('mypackage.php'),
    ], 'mypackage.config');
}

I'm not sure how to add custom logging to that though. I'm still learning Laravel and I'm not quite sure what or how the main applications config/logging.php is read so I'm not quite sure how to inject a custom version for an add-on package.
EDIT:
I found a post that suggested using the following in the ServiceManager boot() method:
$this->app->make('config')->set('logging.channels.mychannel', [
    /* settings */
]);

I used the package config to set a 'logging' => [ 'channels' => [ 'mychannel' => [ /* settings */ ] ] ] and could then do the same thing as above with:
$this->app->make('config')->set('logging.channels.mychannel', config('mypackage.logging.channels.mychannel');

But that still required something in the code.  The next best thing I have found thus far is to change my config/logging.php to config/logging.channels.php and include something like:
return [
    'mychannel' => [
        'driver' => 'single',
        'path' => storage_path('logs/mypackage.log'),
        'level' => env('LOG_LEVEL', 'debug'),
    ]
];

Then in the service provider register() method add:
    $this->mergeConfigFrom(__DIR__ . '/../config/logging.channels.php', 'logging.channels');

I tried doing it from the original 'logging.php' with channels array nested in a 'logging' key, but array_merge doesn't appear to merge the nested elements so my channel never showed up in logging.channels.
I'm not sure if this is ideal, however.  I'd still like to know if there is a 'better' or best practices way of adding custom package logging parameters and whether there is a need to publish it in any way (and how).
Answer: Here is a straightforward way to have your custom package perform some logging into the target application's storage/logging directory.
In the package I define a config/logging.php that mirrors laravels default logging config file, but with only a single channel defined (adjust as necessary for your package requirements):
return [
    'channels' => [
        'my-package' => [
            'driver' => 'daily',
            'path' => storage_path('logs/my-package.log'),
            'level' => 'debug',
            'days' => 7,
        ],
    ],
];

In the service provider for your custom package you need to merge in the package's custom logging channel(s) into the target application config:
public function register()
{
    // Merge any of your default package config (as needed)
    $this->mergeConfigFrom(__DIR__ . '/../config/my-package.php', 'my-package');

    // Next we specifically merge the logging channels provided by this package
    $this->mergeLoggingChannels();

    // ...
}

private function mergeLoggingChannels()
{
    // This is the custom package logging configuration we just created earlier
    $packageLoggingConfig = require __DIR__ . '/../config/logging.php';

    $config = $this->app->make('config');

    // For now we manually merge in only the logging channels. We could also merge other logging config here as well if needed.
    // We do this merging manually since mergeConfigFrom() does not do a deep merge and we want to merge only the channels array
    $config->set('logging.channels', array_merge(
        $packageLoggingConfig['channels'] ?? [],
        $config->get('logging.channels', [])
    ));
}

composer require your package into your target application.
Within the target application run php artisan config:cache and then php artisan tinker
Print the contents of config('logging.channels') and you should now see your package's logging channel in the resulting array
You can log to this channel from the target application or from within the package itself with Log::channel('my-package')->info('Hello world')

Laravel log file specific to a package


How can I calculate the probability of model $g_i$ given a set of $n$ models and AIC values?

Question: Background
I have a data set $Y$:
set.seed(0)
predictor <- c(rep(5,10), rep(10,10), rep(15,10), rep(20,10)) + rnorm(40)
response  <- c(rnorm(10,1), rnorm(10,4), rnorm(10,2), rnorm(10,1))
plot(predictor, response)

and a set of models g$_i$:
fits <- list()
fits[['null']]      <- lm(response ~ 1)
fits[['linear']]    <- lm(response ~ poly(predictor, 1))
fits[['quadratic']] <- lm(response ~ poly(predictor, 2))
fits[['cubic']]     <- lm(response ~ poly(predictor, 3))
fits[['Monod']]     <- nls(response ~ a*predictor/(b+predictor),
                          start = list(a=1, b=1))
fits[['log']]       <- lm(response ~ poly(log(predictor + 1), 1))

Problem
I can find the best fit using
library(plyr)
ldply(fits, AIC)

I am revising a manuscript with results originally presented as raw AIC values, but I find the actual AIC values are fairly uninformative and difficult to interpret
Question
Can I calculate the probability of each model given the set of models e.g. g$_i$ $$\frac{P(Y|\textrm{g}_i)}{\sum_{j=1:n}P(Y|\textrm{g}_j)}$$
An approach that most similar to using AIC wins, because I would like to minimize the amount of revisions to the methods and results that will be required.
Other considerations:

I have considered using ANOVA although this does not appear to have as straightforward of an interpretation as the above, or does it?:
anova(fits[[1]],fits[[2]],fits[[3]],fits[[4]],fits[[5]],fits[[6]])

A Bayesian approach would require more work on both implementing statistics and because it would fundamentally change the interpretation from the likelihood interpretation of $P(Y|g)$ to the Bayesian $P(g|Y)$.
Comment: @David It's legitimate to use AIC for *nested* model comparison (as in null - linear - quadratic - cubic), but not (AFAIK) for completely different models, such as "monod" versus "log".
Comment: I think you have your 'quadratic' and your 'cubic' models mixed up.
Comment: @David If the $g_i$ are the models and $Y$ is the data, your question already is Bayesian, because it requires a prior and Bayes' theorem to compute $\Pr(g_i|Y)$.
Comment: @whuber sorry, I got these backwards since my recent work has been in a Bayesian framework that considers data fixed and models variable. But the underlying point- that I would prefer to retain the original likelihood-based approach, remains.
Comment: @David With the fix it looks like Bayes' Theorem but you have omitted the (requisite) prior probabilities for the models.  Once you specify that prior you can obtain (in the usual way) a posterior distribution for the models based on the data.
Comment: @whuber I think that is exactly my problem. I was just hoping that there was a more direct way to estimate these probabilities from AIC (or another penalized likelihood like BIC if that is more appropriate for this set of models). I think that Aikake weights provide something along these lines, but I am still not sure of the interpretation. I'll post an answer describing this in more detail.
Comment: I'm going to agree with whuber. If you put a non informative discrete uniform prior on the models, then the posterior likelihood of model k given data is proportional to the likelihood of the data under the model k. This seems much  simpler then trying to derive an approximation of posterior model likelihoods from AIC.
Answer: Although AIC may not be suitable in this context, Aikake weights provide the ratio of $$\frac{L(g_i|Y)}{\sum_{j=1:n}{L(g_j|Y)}}$$
Solution
This can be calculated from AIC in this way for each model $i$ (closely following Burnham and Anderson, 2002):
$$\Delta_i = AIC_i - AIC_{min}$$
where $AIC_{min}$ is the best fit model
normalizing these by the sum of the likelihoods gives the Aikake Weight ($W_i$) for each model
$$W_i=\frac{exp(-1/2\Delta_i)}{\sum_{j=1:n}{exp(-1/2\Delta_j)}}$$
which Johnson and Olmland (2004) interpret as

the probability that model i is the best model for the observed data given the candidate set of models.

Burnham and Anderson state that this approach applies for AIC$_c$, QAIC, QAIC$_c$, and TIC.
References

Johnson and Olmland, 2004. Model selection in ecology and evolution. TREE 19(2) dx.doi.org/doi:10.1016/j.tree.2003.10.013
Burnham, K.P. and Anderson, D.R. (2002) Model Selection and Multimodel Inference: A Practical Information-Theoretic Approach, Springer
Comment: AIC can also be used as (approximate) Bayesian model probabilities with non uniform model prior.  By using BIC to approximate the likelihood $P(D|M_i I)\propto\exp\left(-\frac{1}{2}BIC_i\right)$, and then with the prior for the ith model is given by $P(M_i|I)=N^{\frac{d_i}{2}}\exp(-d_i)$, where $d_i$ is the dimension of model $i$.  We get posterior probability of $P(M_{i}|DI)\propto\exp\left(-\frac{1}{2}AIC_i\right)$
Comment: This approach seems implicitly to place a uniform prior on the models you are using.  Whether that's appropriate or not depends on the application.
Comment: @whuber That is pretty much what I am going for; I have plenty of data for informative priors on these models but that would be another paper altogether. Thanks for the feedback.


Bundling, RequireJS, and CDNs - Do they cancel each other out?

Question: I know what you're all thinking, can't he just use all 3? Yes, I could, but my question is this: do they not cancel each other out?
tl;dr

Does bundling make RequireJS obsolete?
Does bundling make CDNs obsolete?
If I have to make a choice between bundling or RequireJS+CDN, how do I determine which to use? Is it best practice to CDN common files, and bundle uncommon? What about SPA files?

The long version
For example, we bundle files for fewer HTTP requests. Whereas RequireJS is used so that files can be loaded dynamically and asynchronously, as they're needed.
So if we bundle all our JS files into 1, is RequireJS even needed?
Also, we use a CDN so the browser can access a cached version, so if the user visits 5 websites, all of which use a popular jQuery CDN - i.e. http://cdn.com/jquery.min.js - the browser actually needs to make no HTTP requests for this file on the last 4 sites, which is much faster than that file getting bundled. If those sites were to instead each access a unique bundled file from the CDN - specific to their needs - the odds of a cache "hit" become much lower. And, since the odds of a "hit" are lower, the file is less likely to be cached for even the people using that site.
So does it really help for a bundled file to even be on a CDN?
Answer:
Whereas RequireJS is used so that files can be loaded dynamically and asynchronously, as they're needed.

Many developers use RequireJS to have a clean way to separate concerns without the need for loading modules dynamically. I have a few applications and libraries developed with RequireJS. One of them is a library that does not use the dynamic loading capabilities at all and would not benefit from using them. In almost all use-case scenarios for this library, it should be loaded as a single bundle, and not as a collection of modules, one-by-one.
This brings me to another thing: the decision is not between bundling or RequireJS. You can use r.js (RequireJS' optimizer) to bundle your RequireJS modules into a single file for production. This could include 3rd party modules if you want. Or you could leave them out to be served from a CDN. An application can be optimized to a single bundle, or a series of bundles. As any other optimization question, what should be done depends on the architecture of the specific application being considered.
The rest of your question is wholly opinion-based. I've seen detailed arguments supported by statistics that you should use a CDN, that you should not use a CDN, and everything in between. It is an optimization question, which, again, depends on the specifics of the application being considered.
Answer:
So if we bundle all our JS files into 1, is RequireJS even needed?

Not all of it. You might be interested in almond.

A replacement AMD loader for RequireJS. It provides a minimal AMD API footprint that includes loader plugin support. Only useful for built/bundled AMD modules, does not do dynamic loading.


overflow:hidden can't hidden skew dom event?

Question: I created a diamond through the sketch of CSS, which is located in the upper left corner of a circle.
I set overflow: hidden for the circle. How can the diamond still trigger cursor: pointer?

Here is the codepen of the project.
html

css
.container {
    position: relative;
    z-index: 1;
    margin-top: 150px;
    margin-left: 300px;
    width: 300px;
    height: 300px;
    border-radius: 50%;
    border: 1px solid red;
    overflow: hidden
}

.skew {
    transform-origin: right bottom;
    transform: skewX(45deg);
    width: 150px;
    height: 150px;
    border: 1px solid blue;
    cursor: pointer;
}

Answer: clip-path can fix this. It seems to happen on Chrome only:

.container {
  position: relative;
  z-index: 1;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  border: 1px solid red;
  overflow: hidden;
  clip-path: circle(50%); /* added */
}

.skew {
  transform-origin: right bottom;
  transform: skewX(45deg);
  width: 150px;
  height: 150px;
  border: 1px solid blue;
  cursor: pointer;
}

Answer: The behavior you are getting is because the cursor is a CSS function that is activated by the browser when the mouse enters the given area params of .skew.
overflow:hidden doesn't affect this functionality.
What is happening is that the DOM renders everything out in a Square, and the border-radius doesn't really care about this.
So what is happening is that you are cutting out this piece of pie, but there is still the distance between the edge of the circle you have drawn and the edge of the div.

What you could do is use:

clip-path: circle(%50) as mentioned by Temani
Draw your inital circle differently using area tags: https://www.w3schools.com/tags/tag_area.asp
Or use an inline  SVG: https://www.codegrepper.com/code-examples/whatever/inline+css+svg+circle


How can I build a "visitor history" using Flag/Rules?

Question: I need to build a history for visitors so they can see which pages they've visited (ideally filtered by type).  To do this, it seems that the correct combo is to use Flag module and then Rules.
I'd anticipate that I'd create a new rule config where I'd ensure the content was of a certain type, ensure a flag existed, then automatically mark the flag each time the content of that type was visited.  I'd also have to update the time if an 'already-flagged' content was visited again (ie. so it appears at the top of a 'history' list).
I've messed around with Rules in Drupal 8 and I didn't get far at all.  I could obviously add a rule for 'node is viewed', and then condition of it being the right type.  But then I got stuck.
I need to be able to do things like see if there's a flag available, see the current value of the flag for that user, automatically set/update the flag, etc.  I couldn't figure out how to do any of this.
Help? :)
Comment: I ended up abandoning rules because it seemed unnecessarily complicated.  Instead I wrote a simple module (see below) to do this.  I'm leaving this open in case someone wants to describe the method for anyone who is trying to do the same thing and must use Rules.
Comment: Rules is 'unnecessarily complicated' just like Views is 'unnecessarily complicated'. If you're a developer then writing an explicit DB query is far easier and more efficient than configuring a custom View. But then in order to modify or customize or enhance the the resulting page you also need a developer. But if you do things in Views then almost anyone can customize and enhance the View. Likewise with Rules - if you're a developer you may be able to hack a quick solution, but that will not be extensible and maintainable by anyone other than a developer.
Answer: Honestly I gave up pretty quickly since it seemed unnecessarily complicated.  I created a very basic module that handles the marking/unmarking via the Flag API.  It has a single hook that looks like this:
<code>function mymodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  //UPON VIEWING 'mytype' NODES
  if($entity->getType() == 'mytype'){

    //CREATE HISTORY FLAGS
    $uid = \Drupal::currentUser()->id(); //current user
    $flag_id = 'history'; //flag type is named history
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);

    if($flag->isFlagged($entity) == '1'){
        //unflag then reflag to update date
        $flag_service->unflag($flag, $entity);
        $flag_service->flag($flag, $entity);
    } else {
        //flag it for the first time
        $flag_service->flag($flag, $entity);
 }
 }
}
</code>
Comment: hook_node_view() does not work that way - it is only called when the node is first rendered, then never called again until the node is re-rendered. So if the cached node is being served (as it almost always is) this hook will not fire. So your solution will not work in general.


Comparing posterior predicted probabilities with "known" to be true probabilities

Question: Following this description I have implemented a Bayesian logistic regression (BLR) model on some data.
Lets say I have this kind of data:
<code>    Sex  Age Success prob
1   Male  18       1  0.2
2   Male  31       0  0.5
3 Female  27       1  0.7
</code>
And I fitted my BLR model without using prob. If we assume that these "prob" probabilities is the true probability for success is there a good, scalable, way to compare my model probabilities with these?
As far as I know, graphical methods where we draw samples from the posterior and look how far away they are from prob only works for one observation at a time. I'm looking for something that scales better, preferably something that can be automated completely or to some extend.
Here are a few ideas I have come up with:

Find the MAP and compare it with prob using simple linear regression

Turn prob into a Bayesian model and compare this model to my BLR model using Bayes factor

I'm not sure how to do this. I'm thinking that would be a single parameter Bayesian logistic model with a non informative (Jeffreys?) prior. Likelihood function would be Bernoulli($y_i; p_i$) where $y_i$ is the success outcome and $p_i$ prob.
Method 1) feels very underwhelming for some reason.
So, I have two questions:

What do you think about method 2, will it work as intended? Or will there be too much information loss?

Is there any other way to do this? Keywords to search for?

Thanks in advance.
Comment: If the probabilities are some sort of gold standard, then why not make a calibration plot?
Answer: I don't exactly have an answer for you.  I have done things like you are trying to do as a demonstration of the properties of statistics, but not for any type of validation. It makes me wonder what you are doing and why.
Let me begin with an observation as well.  You are proposing using an uninformative prior distribution for this project.  The first difficulty that may be created is that your posterior may not sum to unity.  It may not end up being a probability distribution.  That is only assured with proper priors.  Improper priors are not guaranteed to result in proper probabilities.  The second is that I am not sure what you are going to gain by doing that.
Null hypothesis methods provide a guarantee to the performance of their estimators and do not include prior information.  Bayesian methods have no performance guarantees.
If you were willing to use the MAP estimator, why not the MLE?  At least with the MLE, you will get guarantees on your inference, and you do not have to worry about the model exploding due to a failure to integrate to unity.
With that said, if your posterior does integrate to unity or you use a proper prior, then your estimators cannot be first-order stochastically dominated by another estimator.  That is to say, any other estimator will be as risky or riskier than the Bayesian one.  On average, you will be as close or closer with a Bayesian estimator.
With all of that said, if you are creating a random set of data to check performance, then you should look at two things.  The first one is how do the estimators perform when the sample is reasonably representative.  The second one is how do the estimators perform when the sample statistics are far away from the population parameters?
Unbiased estimators minimize the maximum amount of risk you will be exposed to should you get an unrepresentative sample, while Bayesian estimators minimize your average loss.
There is any number of potential measures against a known parameter.  You could find the distribution of the MAP estimator or the posterior mean around the true value.  You could find the posterior variance around the parameter set.  Each of those scales well.
I don't think either 1 or 2 will do what you want.
I would take the points around the parameters from my MCMC set and then calculate what I needed, depending on my goal.  As long as your set is large enough and converges, it should do what you want.
You should strongly consider using proper a proper prior distribution with real information in it, or consider using a non-Bayesian method.


How do you set a password on a PDF using Python reportlab and buffer from BytesIO

Question: I am trying to programmatically add a password to a generated PDF file that is created using Python's reportlab.  The PDF is generated within a Django web application.  The code to dynamically generate a PDF from Django is well documented on Django's help pages:
import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

def some_view(request):
    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

    # Create the PDF object, using the buffer as its "file."
    p = canvas.Canvas(buffer)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

    # Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()

    # FileResponse sets the Content-Disposition header so that browsers
    # present the option to save the file.
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

But as soon as I attempt to add a password to the PDF file, the resulting PDF file is blank.
# This results in a blank PDF document
p = canvas.Canvas(buffer, encrypt='password')

Does anyone know how to use a BytesIO buffer with reportlab and set a password on the file?
Answer: It seems you are looking in the wrong direction.
I have managed to obtain the encrypted PDF using the example given by Django Doc itself. Here I am posting an updated version of the same
import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

def sample_view(request):
    buffer = io.BytesIO()
    p = canvas.Canvas(buffer, encrypt="password", bottomup=False)
    p.drawString(100, 100, "This is test encryption !!!")
    p.showPage()
    p.save()
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')
Notes

I have set bottomup=False which let us write things from top-to-bottom fashion (bottom-to-up is the default behavior)
Tested this solution in Django 3.0
Comment: Thanks so much for your help.  I copied your code directly into my project and am still getting a blank PDF file when I open it with the password.  So something else must be going on, but I can't figure out what it is.  I am using Dango 3.1.1 and reportlab 3.5.55.  If I remove the encrypt="password" from your code, the PDF file correctly shows the test message.  Also, I am running in development on Mac OS X, I even tried deploying your code to my test server which runs Ubuntu and I'm still getting a blank document after it accepts the password.  I'm completely stumped.


Who is this particular English Premiership (Rugby Union) lead announcer?

Question: http://youtu.be/tcoNn0lskgw?t=2m40s
He should be listed somewhere in here - https://en.wikipedia.org/wiki/List_of_British_football_commentators

A Meta entry said this question would be better received if given the reason for the question.
...So I can have a means to avoid watching anything he ever anouces (pretty much anything Aviva Premiership) because of that tedious gritted-teeth affectation thing he does - fabricating drama.  (It sounds like he's announcing from a toilet seat, and occasionally trying to squeeze one out while speaking.)
And just the whole English boarding-school thing in general, when they are forcing it with stilted pronunciations.  David Croft (Sky Formula 1) Ted Kravitz and Simone Lazenby – are the worst.  Ponce hipster central.  Crofty has this nervous tick.  He says "nOWW" too often for no good reason; other than to make himself sound posh. (http://youtu.be/OS7WoUzcWT4?t=4s)
That said: Jack Burnicle and James Whitham are great – and happen to be English and have their own more natural affectations.  Right and proper Yorkshire, I believe.  Or maybe theirs is just called a "Northern" accent - https://www.youtube.com/watch?v=b5Mbh8_FAhc)
/Rant over.
Comment: I am on your side here. I could either close this question as requested by the community, as a source/research request, or you can remove the trivia tag and leave it be.
Comment: Yet, we have this question: https://sports.stackexchange.com/questions/3526/what-is-the-name-of-a-guy-who-comment-highlights-in-nba?rq=1 I see no difference between the two in terms of what's being asked. **Case in point: let's be consistent in how we evaluate questions. [(meta discussion)](http://meta.sports.stackexchange.com/questions/520/media-are-announcer-commentator-identification-questions-on-topic)**
Comment: Viewing the given video, I guess you can focus your research on commentators from sportsnet. Unfortunately I was not able to find more.
Comment: Oh.  Sorry Ed.  To the others then: announcers are part and parcel to professional sport; particularly when they are themselves significant capped rugby players.  (Albeit, not in this particular case – surely.)  Hence the valid _"media"_ tag.
Answer: I believe Miles Harrison is the man.
After watching quite a few matches on YouTube to see if they would list or call each other out by name (never happened once) I found this by cross referencing a long list of announcer names - https://www.youtube.com/watch?v=FWRYM0ZJZRw


Shortest sequence containing at least one of every pair, creating "valid XML"

Question: I've got an alphabet consisting of four symbols: (, ), e, and t.  The inspiration for them are the four basic types of XML elements: a start tag (like <foo>), an end tag (like </foo>), an empty tag (like <foo/>), and non-markup text (like FOO).
We call a string made up of these symbols valid if it meets the following conditions:

The substring tt does not occur.
Every possible unique pair of symbols except for tt occurs at least once.
The string begins with ( and ends with ).
The string contains the same number of ( and ).
The cumulative count of ( is everywhere greater than the cumulative count of ), except at the beginning and the end.

The question is: What is the length of the shortest valid string?
An extensive brute-force search has yielded valid strings of length 17 (the string (t((e())eet)()te) is one example) but none of length 16.  Rules 1 and 2 mean that there cannot be any valid strings with fewer than 16 symbols.  So the question can be rephrased as: Do any valid strings of length 16 exist? If yes, can you give an example?  If no, can you prove it?
If rule 3 is omitted, then strings of length 16 are possible, for example  e()t(te)((et))ee.
Answer: There must be at least 16 since there must be at least at least $15$ pairs.
To do it with $16$, the first and last character must be the same character (why?,) which is not possible (why?)