How to set a whitelist and blacklist in chrome with Android Management API

Question: i tried evrything in this link.
How to set a whitelist in web view with Android Management API
Below is my code on api.
Any help will be appreciate
    {
        "packageName": "com.android.chrome",
        "installType": "FORCE_INSTALLED",
        "managedConfiguration": {
                                 "URLBLacklist": ["*"],
                                 "URLWhitelist": ["youtube.com"]
         },
         "defaultPermissionPolicy": "GRANT"
 }

Answer: your json format should be following
{
      "packageName": "com.android.chrome",
      "installType": "FORCE_INSTALLED",
      "managed_configuration": {
        "URLBlacklist": ["*"],
        "URLWhitelist": ["https://www.youtube.com"]
      },
      "defaultPermissionPolicy": "GRANT"
    }
Comment: Hi appreciate your response
Which code are sahring above is work on your site try it but not work on my site.
your code work on chrome.
i am begginer in this.
did u add anything else
please help me
Comment: what do you mean by your own site?you can allow for any app.just replace your package name instead of chrome and add list of url as your need.
Comment: {
  "screenCaptureDisabled": true,
  "cameraDisabled": true,
  "systemUpdate": {
    "type": "WINDOWED",
    "startMinutes": 120,
    "endMinutes": 240
  },
  "applications": [
    {
      "packageName": "com.android.chrome",
      "installType": "FORCE_INSTALLED",
      "managedConfiguration": {
        "URLBLacklist": [
          "*"
        ],
        "URLWhitelist": [
          "https://www.google.com"
        ]
      },
      "defaultPermissionPolicy": "GRANT"
    }
  ]
}

i tried this policy
i am not able to block all url exept youtube.
Any mistake or missing.
Answer: Managed configuration keys are key-sensitive. URLBLacklist should be written as URLBlacklist
The policy below should work:
            {
                "packageName": "com.android.chrome",
                "installType": "FORCE_INSTALLED",
                "managedConfiguration": {
                    "URLBlacklist": ["*"],
                    "URLWhitelist": ["youtube.com"]
                },
                "defaultPermissionPolicy": "GRANT"
            }


Estimate the area under $f(x) = \frac{1}{2}x^2 - 1$ from $x = 0$ to $4$ using two right hand rectangles.

Question: Help with beginner college calc plz:
I can't upload pictures on my computer (it's a very old desktop) but I'll try and explain what I did. So obviously I started with graphing f(x);
(2, 1)
(-2, 1)
(0, -1)
(3, 4)
(-3, 4)
Then I drew my rectangles. The first one's width was 0 to 1.5, and the 2nd's width was 1.5 to 3 (this is where my problem came in - I will explain). My height for the 1st rectangle was 2 and the 2nd was 4. To reiterate these are right hand rectangles.
Then I did l . w so the 1st rectangle's area would be 3 and the 2nd's 12 adding up to 15.
My question though is how would you draw your two rectangles? The estimate should be from 0 to 4, but my 2nd rectangle's upper right corner only touched 3,4.
Edit: Or did I graph my parabola completely wrong?
Comment: What is f(x) = 1/2x^2 - 1 supposed to be? Use brackets.
Comment: (1/2)x^2 - 1. Does that make it a bit more clear?
Comment: Whether it's $\frac12 x^2-1$ or $\frac1{2x^2}-1$, $f(3)$ doesn't seem to equal $4$...
Comment: Yes that's the problem I'm having. I don't know where I went wrong on my graph.
Comment: You'll need to use the correct value of f(3), and also should calculate f(4) since the graph has to go from x=0 to x=4.
Comment: @JaapScherphuis Scherpius                                                                                But wouldn't my graph still be incorrect? The parabola (at least when I drew it), went from  -3 to +3. I know with RHR the upper right corner has to touch the curve, and if I went to 4 it would go over right (it wouldn't touch the curve anymore)? Oh and thanks for your help!
Answer: Your graph should look like this:

Also note that $f(4)=7$ and $f(3)=\frac{1}{2}\cdot 9-1$.
Comment: Thank you! I knew I must have graphed it wrong.
Comment: You can always check if your graph is correct using apps like geogebra, desmos, photomath etc.
Comment: I will definitely use those next time...


Re-write the output of taxonomy_term_page() without hacking core

Question: In Drupal 7, taxonomy.pages.inc contains the taxonomy_term_page(), which places a
 around the taxonomy heading output.
How can I re-write the output of taxonomy_term_page() in my theme, so I can remove the DIV without hacking core?
I'm quite surprised that there isn't a tpl.php file available for taxonomy_term_page() as this would making theming much easier.
Comment: Give it a read: http://rarepattern.com/nodes/2011/theming-firehose-nb-designers-front-end-developers-new-drupal
Answer: You can do it with preprocess page something like this:
function themename_preprocess_page(&$vars) {
  if  (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    unset($vars['page']['content']['system_main']['term_heading']['#prefix']);
    unset($vars['page']['content']['system_main']['term_heading']['#suffix']);
  }
}

in your theme's template.php
I believe system_main could be called something else, depending on your site setup.
Answer: As it is a menu callback, you can implement hook_menu_alter() in a module to alter the menu callback invoked for that page.
function mymodule_menu_alter(&$items) {
  if (!empty($items['taxonomy/term/%taxonomy_term'])) {
    $items['taxonomy/term/%taxonomy_term']['page callback'] = 'mymodule_term_page';
  }
}

function mymodule_term_page($term) {
  // Build breadcrumb based on the hierarchy of the term.
  $current = (object) array(
    'tid' => $term->tid,
  );
  $breadcrumb = array();

  while ($parents = taxonomy_get_parents($current->tid)) {
    $current = array_shift($parents);
    $breadcrumb[] = l($current->name, 'taxonomy/term/' . $current->tid);
  }
  $breadcrumb[] = l(t('Home'), NULL);
  $breadcrumb = array_reverse($breadcrumb);
  drupal_set_breadcrumb($breadcrumb);
  drupal_add_feed('taxonomy/term/' . $term->tid . '/feed', 'RSS - ' . $term->name);

  $build = array();

  $build['term_heading'] = array(
    'term' => taxonomy_term_view($term, 'full'),
  );

  if ($nids = taxonomy_select_nodes($term->tid, TRUE, variable_get('default_nodes_main', 10))) {
    $nodes = node_load_multiple($nids);
    $build += node_view_multiple($nodes);
    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
  }
  else {
    $build['no_content'] = array(
      '#prefix' => '
',
      '#markup' => t('There is currently no content classified with this term.'),
      '#suffix' => '
',
    );
  }
  return $build;
}

Comment: Thanks! I prefer googletorp's method as it doesn't need a separate module.  But your suggestion is great as it gives more control. Thanks!
Comment: As far as I recall, `hook_menu_alter()` can be implemented in a theme too; in Drupal 7, themes can implement alter hooks.
Answer: Like the previous example, except it may be cleaner and more future proof to modify the returns from taxonomy_term_page in a wrapper rather than copy the original function wholesale:
function mymodule_menu_alter(&$items) {
  if (!empty($items['taxonomy/term/%taxonomy_term'])) {
    $items['taxonomy/term/%taxonomy_term']['page callback'] = '_custom_taxonomy_term_page';
  }
}

function _custom_taxonomy_term_page ( $term ) {

   $build = taxonomy_term_page( $term );

   // Make customizations then return
   unset( $build['term_heading']['#prefix'] );
   unset( $build['term_heading']['#suffix'] );

   return $build;
}

Comment: This is probably the best way to do it.


React : ignore the onClick event when scrolling-y

Question: I'm using the embla-carousel plugin to create a carousel and I want to ignore the onClick event, which links to another page, when I scroll horizontally.
Answer: You might be looking for the Embla opt-in method named embla.clickAllowed(). I don't know if you're using the VanillaJS or ReactJS version of Embla. Anyhow, example usage looks something along these lines:
const onSlideClick = useCallback((index) => {
  if (!embla || !embla.clickAllowed()) return

  // Embla says the pointer interaction was a static click, and not a drag move.
  // Do your magic here...
}, [embla])

  {slides.map((slide, index) => {

 onSlideClick(index)}>
      ...

  })}

How it works under the hood
If the pointer is touch, Embla will:

Prevent a click when the gesture is a drag move.
Prevent clicks when the carousel is clicked during scroll.

If the pointer is mouse, Embla will:

Prevent a click when the gesture is a drag move.
Not prevent clicks when the carousel is clicked during scroll.

The reason behind this design choice is that touch pointers scroll the document. And when the document is natively scrolling on touch devices, it prevents clicks until the user stops the scrolling and clicks again when it's settled.
But mouse pointers are not used to scroll the document, unless you're dragging the scrollbar. And if you're dragging the scroll bar, it will prevent you from accidentally clicking anything on the webpage anyway, because the pointer is within the scroll bar area. So the assumption here is that we can be more certain that a click with a mouse pointer is intentional.
Links

API reference for embla.clickAllowed() here.
A guide on how to implement click events with Embla on the documentation website here.


Heartbleed: are services other than HTTPS affected?

Question: The OpenSSL 'heartbleed' vulnerability (CVE-2014-0160) affects webservers serving HTTPS. Other services also use OpenSSL. Are these services also vulnerable to heartbleed-like data leakage?
I'm thinking in particular of

sshd
secure SMTP, IMAP etc -- dovecot, exim & postfix
VPN servers -- openvpn and friends

all of which, on my systems at least, are linked to the OpenSSL libraries.
Comment: apt-get update is NOT enough. update only shows the latest changes, apt-get UPGRADE will apply then after the update.
Comment: `apt-get update` should be enough for Ubuntu now without downgrading, the patch appeared in the main repository last night.
Comment: I'm sure that's what @JasonC meant, but +1 for making it explicitly clear.
Comment: Fix for Ubuntu: apt-get update && apt-get install openssl libssl1.0.0 && service nginx restart; then, reissue your private keys
Comment: Use this tool to detect the vulnerable hosts: https://github.com/titanous/heartbleeder
Comment: @sjakubowski Well yes, of course; I presume (hope?) one knows how to apply system updates properly (the comment was following Homer6's earlier comment), but +1 for making it clear. :) The point is that the downgrade to 1.0.0 is no longer necessary.
Comment: "secure SMTP, IMAP etc" - yes. And `SPDY` too. Anything that uses OpenSSL and TLS for the socket security. "OpenVPN, OpenSSH, etc" - no, they are different protocols.
Answer: Any service that uses OpenSSL for its TLS implementation is potentially vulnerable; this is a weakness in the underlying cyrptography library, not in how it's presented via a web server or email server package. You should consider all linked services vulnerable to data leakage at least.
As I'm sure you're aware, it's quite possible to chain attacks together. Even in the simplest attacks it's perfectly possible to, for example, use Heartbleed to compromise SSL, read webmail credentials, use webmail credentials to gain access to other systems with a quick "Dear helpdesk, can you give me a new password for $foo, love CEO".
There's more information and links in The Heartbleed Bug, and in another question maintained by a Server Fault regular, Heartbleed: What is it and what are options to mitigate it?.
Comment: @Perseids you're right of course, I was trying to find a easily understandable way of saying that people aren't secure because they're running this version of webserver X or that version of SMTP server Y. I'm making an edit that will hopefully improve things, so thanks for pointing that out.
Comment: "this is a weakness in the underlying system, not in how it's presented via a higher level system such as SSL/TLS" - No, that is wrong. It is a weakness in the implementation of the TLS heartbeat extension. If you don't ever use TLS you are safe. I do agree with your conclusion, though, that you have to be very careful in your analysis in what might be affected because of chained attacks.
Answer: It seems your ssh-keys are safe:

It's worth pointing out that OpenSSH is not affected by the OpenSSL bug. While OpenSSH does use openssl for some key-generation functions, it does not use the TLS protocol (and in particular the TLS heartbeat extension that heartbleed attacks). So there is no need to worry about SSH being compromised, though it is still a good idea to update openssl to 1.0.1g or 1.0.2-beta2 (but you don't have to worry about replacing SSH keypairs). –  dr jimbob 6 hours ago

See:
https://security.stackexchange.com/questions/55076/what-should-one-do-about-the-heartbleed-openssl-exploit
Comment: You can't read ANY 64k of memory with this bug, only 64k near where the incoming packet is stored. Unfortunately a lot of goodies tend to be stored there, such as decrypted HTTP requests with plaintext passwords, private keys, and pictures of kittens.
Comment: Isn't it indirectly affected as stated by @RobM? Someone reads root's password from memory using the Heartbleed vulnerability, gets whatever non-SSH access to the system and then steals the SSH stuff.
Answer: In addition to the answer of @RobM, and since you ask about SMTP specifically: there already is a PoC for exploiting the bug on SMTP: https://gist.github.com/takeshixx/10107280
Comment: Specifically it exploits the TLS connection that is established after the "starttls" command, if I read the code correctly.
Answer: Yes those services can be compromised if they rely on OpenSSL

OpenSSL is used to protect for example email servers (SMTP, POP and
  IMAP protocols), chat servers (XMPP protocol), virtual private
  networks (SSL VPNs), network appliances and wide variety of client
  side software.

For a more detailed write up on the vulnerabilities, affected operating systems etc. you can checkout http://heartbleed.com/
Answer: Anything that links with libssl.so may be affected. You should restart any service that links with OpenSSL after you have upgraded.
# lsof +c 0 | grep -w DEL | awk '1 { print $1 ": " $NF }' | grep libssl | sort -u
bacula-fd: /usr/lib/libssl.so.1.0.0
php-fpm: /usr/lib/libssl.so.1.0.0
php-fpm: /usr/lib/php/modules/openssl.so
python2: /usr/lib/libssl.so.1.0.0
python2: /usr/lib/python2.7/lib-dynload/_ssl.so
python: /usr/lib/libssl.so.1.0.0
ruby-timer-thr: /usr/lib/libssl.so.1.0.0
ruby: /usr/lib/libssl.so.1.0.0

Courtesy of Anatol Pomozov from Arch Linux mailing list.
Comment: Anything that links with libssl and uses TLS. Openssh uses openssl but doesn't use TLS, so it's not affected.
Comment: @StasM That's why I wrote **may be affected**, not **is affected**. Also, OpenSSH **server** does NOT link against OpenSSL at all. Utilities like ssh-keygen do, but they are not used by OpenSSH **server** itself. Which is clearly visible in the lsof output I provided - OpenSSH is not listed there, although it's running on the server.
Answer: Other services are affected by this.
For anyone who uses HMailServer, start reading here - http://www.hmailserver.com/forum/viewtopic.php?f=7&t=26276
Anyone and everyone will need to check with the developers of all software packages to find out if updates are needed.


example song with lyrics and instrumental introduction?

Question: I really need help for how to create a song in lilypond that has both instrumental portions and verse / chorus portions.  Like a real-world practical song.  I want to be able to create something like this for example:

See how there is an introduction with no lyrics under it.  How do I make only certain parts of the music be associated with my "\addLyrics{ }"?
Answer: A simple way is to add blank lyric syllables, for example " ".
This gets hard to read if there are lots of them, so it's nicer to define your own macro - \skip in the example.
\version "2.18.2"
\language "english"

skip=" "

{ \new PianoStaff {
  <<
    \new Staff {
      \key bf \major \time 4/4 \partial 4 \relative c'' {
      a8. g16 | f8 f f4 f g8. a16 | bf2. f8. f16 \bar "||" f4 g8. f16 f8 f bf8. c16 | } }

    \addlyrics {
      \skip \skip | \skip \skip \skip \skip \skip \skip | \skip
      There's a | church in the val -- ley by the | }

    \new Staff {
      \clef "bass" \key bf \major \relative c' {
      r4 | a2 <f ef'> | <bf d>2. r4 | <bf d>2 q } }
  >>
} }

Answer: By default, \skip 1 in your lyrics will skip as much music as where 1 syllable would appear. For a single note, that means it will find the next note. For tied notes and slurred notes, that means the next note after the conclusion of the tie or slur.
To use this multiple times, trying entering \repeat unfold N in your lyrics:
music = \relative c' {
 c4 d e f
 g f e d
}
words = \lyricmode {
 \repeat unfold 4 { \skip 1 }
 song starts on G
}
\score {
 <<
  \new Voice = "melody" \music
  \new Lyrics \lyricsto "melody" \words
 >>
}

Comment: I did a combo of both ideas like this: \repeat unfold 23 { " " }


How to ensure a timestamp is always unique?

Question: I'm using timestamps to temporally order concurrent changes in my program, and require that each timestamp of a change be unique. However, I've discovered that simply calling DateTime.Now is insufficient, as it will often return the same value if called in quick succession.
I have some thoughts, but nothing strikes me as the "best" solution to this. Is there a method I can write that will guarantee each successive call produces a unique DateTime?
Should I perhaps be using a different type for this, maybe a long int? DateTime has the obvious advantage of being easily interpretable as a real time, unlike, say, an incremental counter.
Update: Here's what I ended up coding as a simple compromise solution that still allows me to use DateTime as my temporal key, while ensuring uniqueness each time the method is called:
private static long _lastTime; // records the 64-bit tick value of the last time
private static object _timeLock = new object();

internal static DateTime GetCurrentTime() {
    lock ( _timeLock ) { // prevent concurrent access to ensure uniqueness
        DateTime result = DateTime.UtcNow;
        if ( result.Ticks <= _lastTime )
            result = new DateTime( _lastTime + 1 );
        _lastTime = result.Ticks;
        return result;
    }
}

Because each tick value is only one 10-millionth of a second, this method only introduces noticeable clock skew when called on the order of 10 million times per second (which, by the way, it is efficient enough to execute at), meaning it's perfectly acceptable for my purposes.
Here is some test code:
DateTime start = DateTime.UtcNow;
DateTime prev = Kernel.GetCurrentTime();
Debug.WriteLine( "Start time : " + start.TimeOfDay );
Debug.WriteLine( "Start value: " + prev.TimeOfDay );
for ( int i = 0; i < 10000000; i++ ) {
    var now = Kernel.GetCurrentTime();
    Debug.Assert( now > prev ); // no failures here!
    prev = now;
}
DateTime end = DateTime.UtcNow;
Debug.WriteLine( "End time:    " + end.TimeOfDay );
Debug.WriteLine( "End value:   " + prev.TimeOfDay );
Debug.WriteLine( "Skew:        " + ( prev - end ) );
Debug.WriteLine( "GetCurrentTime test completed in: " + ( end - start ) );

...and the results:
Start time:  15:44:07.3405024
Start value: 15:44:07.3405024
End time:    15:44:07.8355307
End value:   15:44:08.3417124
Skew:        00:00:00.5061817
GetCurrentTime test completed in: 00:00:00.4950283

So in other words, in half a second it generated 10 million unique timestamps, and the final result was only pushed ahead by half a second. In real-world applications the skew would be unnoticeable.
Comment: I am using guids to represent unique identities. What I need here is temporal ordering... i.e. being able to look at two changes and tell which came first. Guids can't do that. Ideally I'd like to use some form of human-interpretable form of date, but I suppose an incrementing number would work in a pinch, perhaps combined with a DateTime for readability.
Comment: Specify DateTimeKind.Utc when you call `new DateTime(_lastTime + 1, DateTimeKind.Utc);`
Comment: Is the application multi-threaded?  Meaning can two different threads ask for an ID at the same time?
Comment: Is there a reason you cannot use Guids?
Answer: One way to get a strictly ascending sequence of timestamps with no duplicates is the following code.
Compared to the other answers here this one has the following benefits:

The values track closely with actual real-time values (except in extreme circumstances with very high request rates when they would get slightly ahead of real-time).
It's lock free and should perform better that the solutions using lock statements.
It guarantees ascending order (simply appending a looping a counter does not).

public class HiResDateTime
{
   private static long lastTimeStamp = DateTime.UtcNow.Ticks;
   public static long UtcNowTicks
   {
       get
       {
           long original, newValue;
           do
           {
               original = lastTimeStamp;
               long now = DateTime.UtcNow.Ticks;
               newValue = Math.Max(now, original + 1);
           } while (Interlocked.CompareExchange
                        (ref lastTimeStamp, newValue, original) != original);

           return newValue;
       }
   }
}

Also note the comment below that original = Interlocked.Read(ref lastTimestamp); should be used since 64-bit read operations are not atomic on 32-bit systems.
Comment: +1. I ran some unit tests against this code. It indeed works, and performs marginally faster than any other solution. The only downside is that it's not intuitive to the average reader.  I'd expend more time explaining how it works to others than I'd prefer vs a simple lock (which is plenty fast).  [Complexity/Performance tradeoff].  But again, I'd vote your solution up higher if I could.
Comment: Keep in mind that the system time can jump around a bit, i.e. when it gets an update from the time server. So, if the clock jumps backwards you will get a value that is different than the last value, but then when the clock catches up you might snag the same value you did before again and your algorithm won't know that.
Comment: brilliant solution
Comment: @MikeMarynowski Yes, but with the static `lastTimeStamp` it should always advance by at least 1 per call. So this would only apply on an app restart and only if the jump was larger than the time to restart the app. On a jump back it will continue to hand out incremental +1 values until the clock catches up (and it's unlikely you can request them fast enough that this wouldn't quickly get back to being close to actual clock time).
Comment: I found it easy to understand, and well written, except for the variable names, which could be English words. Thank you very much!
Comment: @FrankHileman, updated variable names per your suggestion, thanks!
Comment: Ah sorry, you're totally correct...I apparently missed the math.max part when I was reading it over. Upvoted :)
Comment: What happens when this code goes behind the load balancer? In theory this could generate two keys with same tick value.
Comment: @Gurpreet This is *clearly* a single-server solution. If want a multi-server solution, create a single time source, use a database, or use some other technology that can guarantee unique timestamps within a cluster.
Comment: @Gurpreet you can also include the machine name(or anything else unique per process/machine) to the ticks and generate something unique across a cluster.
Comment: It should be `original = Interlocked.Read(ref lastTimestamp);` since 64-bit read operations are not atomic on 32-bit systems.
Answer: Er, the answer to your question is that "you can't," since if two operations occur at the same time (which they will in multi-core processors), they will have the same timestamp, no matter what precision you manage to gather.
That said, it sounds like what you want is some kind of auto-incrementing thread-safe counter. To implement this (presumably as a global service, perhaps in a static class), you would use the Interlocked.Increment method, and if you decided you needed more than int.MaxValue possible versions, also Interlocked.Read.
Answer: DateTime.Now is only updated every 10-15ms.
Not a dupe per se, but this thread has some ideas on reducing duplicates/providing better timing resolution:
How to get timestamp of tick precision in .NET / C#?
That being said: timestamps are horrible keys for information; if things happen that fast you may want an index/counter that keeps the discrete order of items as they occur. There is no ambiguity there.
Answer: I find that the most foolproof way is to combine a timestamp and an atomic counter.  You already know the problem with the poor resolution of a timestamp.  Using an atomic counter by itself also has the simple problem of requiring its state be stored if you are going to stop and start the application (otherwise the counter starts back at 0, causing duplicates).
If you were just going for a unique id, it would be as simple as concatenating the timestamp and counter value with a delimiter between.  But because you want the values to always be in order, that will not suffice.  Basically all you need to do is use the atomic counter value to add addition fixed width precision to your timestamp.  I am a Java developer so I will not be able to provide C# sample code just yet, but the problem is the same in both domains.  So just follow these general steps:

You will need a method to provide you with counter values cycling from 0-99999. 100000 is the maximum number of values possible when concatenating a millisecond precision timestamp with a fixed width value in a 64 bit long. So you are basically assuming that you will never need more than 100000 ids within a single timestamp resolution (15ms or so).  A static method, using the Interlocked class to provide atomic incrementing and resetting to 0 is the ideal way.
Now to generate your id you simply concatenate your timestamp with your counter value padded to 5 characters.  So if your timestamp was 13023991070123 and your counter was at 234 the id would be 1302399107012300234.

This strategy will work as long as you are not needing ids faster than 6666 per ms (assuming 15ms is your most granular resolution) and will always work without having to save any state across restarts of your application.
Comment: This does feel like the best compromise. I was thinking about something like this as a possible solution; thanks for going into detail. I think 100,000 changes per 15 ms is quite an acceptable limit. :)
Comment: You could also represent the value as a string, rather than a 64-bit int, and simply concatenate an arbitrary-length counter onto the end of the string (perhaps with a delimiter like '.'), thus getting around the 6666 per ms "limitation". One could then simply cut this off the end to interpret the initial part as a date again for readability.
Comment: Yes, but then you have to worry about ordering.  `"123456789.12345" < "123456789.234"` if you compare naturally.  Both parts have to be fixed width.  Though you certainly could increase the width of the second part.  I was just counting on the fact that the millis value for time won't increase in digits for a long time.  In the year 2286 people will be furious that you did it.
Comment: Sorry I don't follow. You could just split the string on the '.' character and compare the two sections separately, or alternatively pad the second part with zeroes. What does this have to do with the year 2286?
Comment: Sorry if that was unclear.  Splitting the string and doing 2 comparisons seems irritating because then you can't take advantage of the natural order.  I was just saying you would want to pad the second part with zeroes.  And then the comment about the year 2286 was about the way I suggested doing it.  I required that the number of digits in the timestamp not change, but in 2286 it will.
Comment: Alternately, you can append a Guid and it will do the same thing without having to worry about keeping a counter. It will be a great deal longer though. Maybe you could make an object that has both properties, and use the timestamp to sort.
EDIT: Never Mind realized you want to ensure the ordering. You could still make the ID a separate property though, so you wouldn't need to compare by it unless the timestamps are equal.
Comment: This doesn't appear to guarantee ordering: If you request two values within the same millisecond window and the counter wraps over the end wouldn't they be in the wrong order?
     123456789.99999 > 123456789.00001
Answer: It can't be guaranteed to be unique, but is perhaps using ticks is granular enough?

A single tick represents one hundred
  nanoseconds or one ten-millionth of a
  second. There are 10,000 ticks in a
  millisecond.
Comment: Unfortunately it appears DateTime.Now is only updated every 15 ms roughly, rendering the Ticks property pointless in this scenario.
Comment: There is an API technique involving GetTickCount() to get what you want.
Answer: Not sure what you're trying to do entirely but maybe look into using Queues to handle sequentially process records.


Função FWRITE não está gravando em formato binário em linguagem C

Question: Não estou conseguindo gravar dados em binário em um arquivo utilizando a linguagem C. Mesmo usando 'wb' a saída do arquivo são caracteres.
Como posso proceder?
Eis aqui parte do meu código:

void cadastrar(void)
{
     if((fp=fopen("Jogos.dat", "wb"))==NULL)
     {
        printf("\nO arquivo nao pode ser aberto!\n");
        getch();
        exit(1);
     }
     fseek(fp,0L, SEEK_END);
 do
 {
    printf("\n Digite o Nome do Jogo ('FIM' para sair): ");
    gets(reg[quantidade_cadastro].nome_jogo);

    if ((strcmp(reg[quantidade_cadastro].nome_jogo,"fim")!=0)&&(strcmp(reg[quantidade_cadastro].nome_jogo,"FIM")!=0))
    {
        printf("\n Ano de Lancamento: ");
        scanf("%d",&reg[quantidade_cadastro].ano_lancamento);
        fflush(stdin);

        printf("\n Genero: ");
        gets(reg[quantidade_cadastro].genero);

        printf("\n Plataforma: ");
        gets(reg[quantidade_cadastro].plataforma);

        reg[0].status='1';

        if(fwrite(&reg, sizeof(struct registro), 1, fp) != 1)
        {
            printf("\nErro de Gravacao :/");
            getch();
        }
        else
        {
            quantidade_cadastro++;
            printf("\n Jogo Gravado no Arquivo!\n\n");
        }
    }
 }while((strcmp(reg[quantidade_cadastro].nome_jogo,"fim")!=0)&&(strcmp(reg[quantidade_cadastro].nome_jogo,"FIM")!=0));
 fclose(fp);}

Comment: Qual é a definição de `struct registro`?
Comment: Este é o registro:
`struct registro
{
    char nome_jogo[40];
    int ano_lancamento;
    char genero[20];
    char plataforma[20];
    char status;
   } reg[50];`
Answer: O seu arquivo tem caracteres pelo seguinte motivo.
Como sua struct é composta por 4 campos char e um campo int, o normal é que os dados possam ser lidos.
O método fwrite escreve diretamente os valores de sua struct dentro de arquivo, sem fazer conversão de valores como o printf.
Os valores usados são os da tabela ascii. Supondo que você tenha a seguinte string "ABCD", os valores seriam escritos como: 65,66,67,68. E quando o editor de texto fosse ler esses valores ele exibiria ABCD.
Caso um int seja escrito no arquivo, o tamanho do int em 64bits vale 4, e o valor a ser escrito será 65. O valor escrito no arquivo será 65,0,0,0 ou A para o editor de texto. Caso o valore escrito seja 16961, deverá escrever AB.
Se usar o comando string (presente no bin/ do gcc) será possível ver os nomes dos métodos, as strings e das bibliotecas usadas pelo seu sistema, isso por causa da interpretação da tabela ascii quando se lê o arquivo.
Caso queira um arquivo com valores ilegíveis (sem caracteres A-Za-z-0-9), você deve armazenas valores que fujam o máximo possível dos caracteres literários e numéricos.
Comment: consegui compreender agora. Eu estava pensando que os caracteres seriam substituídos por símbolos assim como é possível notar em alguns arquivos binários já que não tinha conhecimento prévio sobre ASCII. Muito obrigado pela explicação!
Answer: O conteúdo dos objectos de tipo struct registro é basicamente só texto. Não admira que o conteúdo do ficheiro sejam caracteres.
Verifica a parte do ano_lancamento no ficheiro "Jogos.dat".
Como gostarias que o registo seguinte fosse apresentado "em binário"?
strcpy(reg[0].nome_jogo, "jogo um");
reg[0].ano_lancamento = 2014;
strcpy(reg[0].genero, "sorte");
strcpy(reg[0].plataforma, "papel e lápis");

A diferença entre um ficheiro de texto ou binário prende-se basicamente no tratamento de "\n". Um ficheiro binário não faz tratamento desse caracter, um ficheiro de texto pode converter em "\r\n". Para mais detalhes lê as secções 7,21,2 e 7.21.3 do Standard C11 (em inglês).
Comment: Ao gravar o caracter `'A'` num ficheiro (binário) o que lá fica é o valor 65 (em computadores baseados em ASCII). Esse valor quando interpretado como caracter é apresentado com "A". Ou seja: não há diferença entre caracter texto e caracter binário.
Comment: Você quer dizer que só é possível gravar em binário se os objetos forem convertidos para inteiro?
No arquivo(ficheiro) "Jogos.dat" apenas o ano de lançamento foi gravado em binário.

Não entendi muito bem a diferença do seu código para o meu. Poderia explicar?
Comment: Então se não há diferença, qual seria o motivo de o arquivo gravar caracteres?
Comment: A diferença entre um ficheiro de texto ou binário prende-se basicamente no tratamento de "'\n'". Um ficheiro binário não faz tratamento desse caracter, um ficheiro de texto pode converter em `"\r\n"`. Para mais detalhes lê as [secções 7,21,2 e 7.21.3 do Standard C11 (em inglês)](http://port70.net/~nsz/c/c11/n1570.html#7.21.2).
Comment: @pmg: o que está nos seus comentários deveria estar na resposta - essa que é a duvida dele, e o que é importante documentar aqui.  Será que você pode edita-la e passar essas informações pra resposta?


Linear transformation (no real function)

Question: Q: We're showing that this function is a linear transformation. Let $V$ be the set of polynomials in $x$ with real coefficients and suppose $L:V \to \mathbb{R}^2$ is defined by $L(p(x))=(p(1), p(2))$.
Then suppose $L:V \to \mathbb{R}^3$ is defined by $L(p(x))=(p(1), p(2), p(3))$.
So I've started this with $L(p(x))=(p(1), p(2))$ and want to show it holds under addition so would I take a function $q$ and have $((p+q)(1), (p+q)(2))$? Or do I need to do $(p(1)+p'(1), p(2)+p'(2))$? Am I on the right track with one of these?
Comment: What do you mean, exactly, by "it holds under addition"? And why would you consider the derivative $p'$?
Comment: For it to be a linear transformation it holds under addition and multiplication of scalars. And I didn't mean prime just like some other p
Answer: Hint: OK, so you need to show that if $p, q\in V$ and $c\in\mathbb{R}$, then
$$L((p+q)(x)) = L(p(x))+L(q(x)),\quad L((cp)(x)) = cL(p(x)).$$
Now just write down the definitions of what those things mean in terms of the explicit definition for $L$ that you have, and the answer should pop out.
Comment: Just wondering here: what if I suppose p to be some random polynomial, say p=2x^2 + x. Then L(p)=(3,9). Could I show addition with: L(2x^2)+ L(x)? I.e. 2+1?
Comment: You need to show that this holds for *any* $p$ and $q$. In the particular case you gave, $L(2x^2) = (2\cdot 1^2, 2\cdot 2^2) = (2,8)$ and $L(x) = (2\cdot 1, 2\cdot 2) = (2,4)$, while $L(2x^2+x) = (2\cdot 1^2+1,2\cdot 2^2+2)$. And then $L(2x^2)+L(x) = L(2x^2+x)$. But again, you need to show this for arbitrary $p$ and $q$.


Statistical line comparison

Question: I have a dataset like the one in this question, i.e,
interval    mean  Drug    lower   upper
14  0.004   a   0.002   0.205
30  0.022   a   0.001   0.101
60  0.13    a   0.061   0.23
90  0.22    a   0.14    0.34
180 0.25    a   0.17    0.35
365 0.31    a   0.23    0.41
14  0.84    b   0.59    1.19
30  0.85    b   0.66    1.084
60  0.94    b   0.75    1.17
90  0.83    b   0.68    1.01
180 1.28    b   1.09    1.51
365 1.58    b   1.38    1.82
14  1.90    c   0.9     4.27
30  2.91    c   1.47    6.29
60  2.57    c   1.52    4.55
90  2.05    c   1.31    3.27
180 2.422   c   1.596   3.769
365 2.83    c   1.93    4.26
14  0.29    d   0.04    1.18
30  0.09    d   0.01    0.29
60  0.39    d   0.17    0.82
90  0.39    d   0.20    0.7
180 0.37    d   0.22    0.59
365 0.34    d   0.21    0.53

You can see a good graphical representation in the top answer on the linked thread. Let's assume the upper = means + 1 standard-deviation and lower = means - 1 standard-deviation. Means and standard-deviations were computed over a set number of trials (say, $n=20$) at each interval for each Drug.
My question is, how do I get p-values for the overall superiority of say drug C to drug A or drug B to drug D? What is the correct statistical procedure here and how can it be implemented?
Comment: More information is needed here. Is `interval` the number of days since administration of the drug, or something? Are these repeated measurements from the same subjects, or independent samples? The simplest answer will be to use an ANOVA, and maybe repeated measures ANOVA, depending on the design.
Comment: @Eoin We should be able to say that the samples along ```interval``` are independent. (That is, a different group of people are inspected after 14 days to that inspected after 30 days.) Within these 'inspections', each consisted of 20 trials at each 'interval' for each model based on random train/test splits each trial (my actual use case isn't medicinal drugs...) and that's how the means and standard-devs were calculated
Comment: OK. So you have the raw data from which the means were calculated? And finally, the raw values for each trial are values on some linear scale (e.g. some medical test score)? Or is `OR` an odds ratio, or similar? I'm going to assume the former, and start writing an answer. Please correct me if it isn't!
Comment: @Eoin yes, the raw values are on a linear scale from 0-100 (e.g., "patients who survive" if that's not too morbid). I don't have the raw data---only the means, standard deviations, and the sample sizes (20)
Answer: Assuming that you have access to the values from each individual trial, the simplest model here is a two-way drug (a, b, c, or d) × interval (14, 30, 60, 90, 180, or 365) ANOVA.
m = lm(score ~ interval * factor(drug), data=your_data)
anova(m)

This will tell you if a) there's a main effect of drug (indicating that some drugs are better than others), b) there's a main effect of interval (some intervals have higher scores than others), and c) there's a drug × interval interaction (the difference between the drugs varies depending on the interval).
If you do find a main effect of drug, you may want
to explore various post hoc test,
for instance, testing if there's a significant difference between drugs a and b. The simplest way to do this is just to repeat the analysis on a subset of the data.
data_aVb = dplyr::filter(data, drug %in% c('a', 'b'))
m_aVb = lm(score ~ factor(interval) * drug, data=data_aVb)
anova(m_aVb)

You'll also want to read about correcting for multiple comparisons, but I won't go into that here.

Update!

Since your data is actually a proportion,
you'll have to nuance this slightly.
Standard ANOVA is a version of linear regression,
and assumes the data is on a linear scale.
What you actually have is a proportion,
indicating that $y$ out of 20 patients survived (or similar). You can deal with this by using logistic regression instead of linear regression, as follows (assuming that survived is the total number who survived (out of 20)):
m = glm(cbind(survived, 20) ~ interval * factor(drug),
        data=your_data, family=binomial)
anova(m)

Again, there plenty of resources on this online.
Comment: thanks. What if the original data is no longer available?
Comment: Is `mean` just a proportion out of 20? If so, you just create a new column, `survived = mean * 20`. That is, if you're fitting logistic regression, you don't need the original data if you have the totals (`n_survived` and `n_total`, in this case). If you're using regular ANOVA, you can also [calculate it using the means and SDs](https://www.tandfonline.com/doi/abs/10.1207/S15328031US0103_04?journalCode=hzzk20), but I don't  know if there's a built-in function in R for this.
Comment: No, ```mean``` is a proportion out of 100, averaged over 20 trials (at each ```interval```, for each ```Drug```). So then ```mean*100``` instead? Would it be statistically valid (given the assumptions ANOVA makes anyway) to use the means and SDs to simulate data from the normal distribution and let R run ANOVA on that?
Comment: Ah, ok. Now I understand. It's not necessary or advisable to simulate data as you suggest, since this just adds noise for no reason. Instead, you can calculate an ANOVA using the means and standard deviations, using the method in the link provided. There's probably an R package for this somewhere as well, although it's not complicated to implement yourself.
Comment: Thanks. I don't seem to be able to get access to that paper. Could you edit your post with some details how it might be done (mathematically)?
Comment: You can get the paper on [sci-hub](https://sci-hub.se/https://www.tandfonline.com/doi/abs/10.1207/S15328031US0103_04?journalCode=hzzk20). This is also discussed on this site [here](https://stats.stackexchange.com/a/57759/42952), [here](https://stats.stackexchange.com/a/126521/42952), [here](https://stats.stackexchange.com/a/329293/42952), and in a few other questions.
Comment: Please don't forget to accept the answer and/or upvote if you found it helpful.
Comment: the first two of those posts recommend simulation (which you explicitly advised against) and the last is a one-way ANOVA. I wouldn't say the question has been answered yet

Statistical line comparison


For which prime numbers $p$ does the congruence $x^2 + x + 1 \equiv 0 \pmod{p}$ have solutions?

Question: For which prime numbers p does the congruence $x^2 + x + 1 \equiv 0 \pmod{p}$ have solutions?
We've recently learnt about quadratic reciprocity in class, however I am not sure how to tackle this problem. I have tried starting with the $b^2-4ac$ (discriminant) but that hasn't really helped.
Comment: $p=3$, $p=7$ for instance.
Comment: Welcome to MathSE.  I am glad you found the help you needed on this question.  There is information about writing mathematics on this site here: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference.  Also, the quantity $b^2 - 4ac$ is called the discriminant.
Answer: Hint: Consider $4(x^2 +x+1) = (2x+1)^2 + 3$. Therefore, if it has a solution modulo $p$, $-3$ must be a quadratic residue. Use quadratic reciprocity.
Comment: So following from that I should find p for which (-3/p)=1?
Comment: Yes. Remember that $(-3|p) = (-1|p)(3|p)$. Then, you either need that both -1 and 3 are quadratic residues or both are quadratic non-residues. $(-1|p) \equiv (-1)^{(p-1)/2} \pmod{p}$, and for 3 use quadratic reciprocity
Comment: Okay, so I get (-3/p)=(-1)^(p-1)(p/3) which is dependent on pmod3 then it works for p=1 and p=2, does this mean it holds for all p equivalent to 1 or 2 mod 3? Also what about p=3?
Comment: For $p=3$ you must handle it separately. You can see that $x=1$ is a solution. And yes, if $a\equiv b\pmod{p}$ then $(a|p)=(b|p)$.
Also, be careful, $2$ is not a quadratic residue modulo $3$.
Comment: So if it holds for p=3, does this imply it holds for all p as we already have it working for p=1 or 2 mod 3?
Comment: It doesn't work for $p\equiv 2\pmod{3}$ because, as you've seen $(-3|p) = (p|3)$ and $2$ is not a quadratic residue modulo $3$.
Comment: I thought (-3|p)=(-1)^(p-1) (p|3) so 2 would work?
Comment: You can check that $p=2$ doesn't work by hand, and then, if $p$ is a prime, it must be odd. So $p-1$ is even and then $(-1)^{p-1}=1$. That is, $(-3|p) = (p|3)$.
Comment: Ah I see, and then you have it holds for p as long as p is equivalent to 1 or 3 mod3?
Comment: Yep, that's it :)
Comment: Cool, thanks for the help :)
Answer: Simpler than reciprocity: $\,x^2+x+1 \equiv 0 \,\overset{\large {\cdot\, (x-1)}}\Rightarrow\,x^3\equiv 1,\ $ so by basic results on cyclic groups $\ldots$


Possibility to manipulate TLS1.2 communication within a Jetty environment

Question: I have a strange question and spent more than a week to find a solution.
Does anybody know a possibility how I can adapt the sources from my embedded Jetty server in a way that I can manipulate the whole communication? I'm especially interested in manipulating the responses used for the TLS v1.2 handshake and the communication with this protocol at any time. I need this for writing a simulation of a system - this system shall be tested in many ways including the described use case.
I already created an example which uses a created certificate to start a secured webservice. It is also possible for the web browser to connect to the web service by using HTTPS - so far so good.
I set a breakpoint within my HttpServlet class and I reach this breakpoint. The test answer is generated and the answer is sent back (The method write() within the class Iso88591Http is used) where I can find the TLS v1.2 encryption?
I hope I explained the problem in a good way and someone has an idea.
Comment: You can't even do that in Java, let alone Jetty, unless you write your own SSL provider.
Answer: Sounds like you are missing the SecureRequestCustomizer in your environment.
That will inject the relevant pieces from the established SSLSesssion into the request attributes.
This Customizer is added in the typical way, via the HttpConfiguration.addCustomizer() method.
See full fledged example on the embedded-jetty-cookbook github repository.  The ServerConnectorHttps example has the setup you are looking for.
Comment: Thank you very much! I will try this :)
Am I allowed to adapt and manipulate the "relevant pieces" from the established SSLSession with this? If not do you have a clue what to do?
Comment: You can't change anything with the TLS layer at that point.  The connection is already established, everything you see in the SSLSession is essentially immutable at that point.  What you seem to be asking about would require a custom SSL layer in Java.  If you go down this path, be careful of differences in Linux vs WIndows vs OSX.
Comment: Or are you asking about how to configure the negotiation of ciphers and protocols during the TLS connection?  If so, that's just a configuration, not code.
Comment: Hi, no the question was regarding the manipulation of the SSL data itself. I guess to achieve this goal I have to convince Jetty to use an adapted custom TSL layer as you suggested. I had already a look how to do this and I belive it is a good idea to use CyaSSL Java SSL provider.


Normal Distribution and Sports

Question: One core idea in sports analytics is to be skeptical of hot streaks as being evident of anything more than just something a normal distribution would account for.
What I've never understood, is would a normal distribution, as applied to sports, imply that luck randomly fluctuates, that a player's skill or ability level at any given time randomly fluctuates around some true, underlying mean, or some combination thereof?
Comment: Yes: luck, by definition, randomly fluctuates. A player's skill level, on the other hand, does peak at a certain age and thereafter decline, but on any given performance randomly fluctuates around some mean value.
Answer: This is starting to head into territory that might be better handled at CrossValidated, but it's interesting here nonetheless.
One concept that's important in statistics is that even if a random variable is not normally distributed (could be uniform, binomial, gamma, who knows), a sample of its means will be normally distributed.  Thus, while you cannot assume that a random sample of 50 at-bats from a player will appear normal, you can assume that if you take 50 samples of 50 samples that they will be approximately normally distributed, assuming the basis for the data doesn't change over time.
This, of course, isn't an assumption you can make over a long period of time - 2500 at bats I'm sure a player will change over - but over a shorter period of time you probably can, if the player doesn't get injured and isn't in the very beginning or very end of his career.
This is used by assuming a player's performance that year/etc. is a random sample from the inferential (but imaginary) population of all at-bats he might take, which would define his 'true' ability level.  If a player is batting .280, then the odds of his true ability level being .300 or .260 under a naïve assumption would be identically likely (and, based on the sample size, could be determined.)  Further, you could use other samples of his batting ability (say, he batted .250 last year, and .270 the year before that, and .230 the year before that) to determine what the likely overall skill level is - again assuming, naïvely, that his skill level is constant.  In this example, the .280 sounds like an outlier on the high end - a hot streak, so to speak - since his performance has fluctuated up and down around an average of .260 or so.
However, that's a very naïve assumption, and is certainly well behind where we stand in sports analytics.  The normal distribution assumption is still present in certain elements, but various people have used a much more powerful tool to determine what factors have predictive value as to future performance in other areas than simply a mean of batting averages.
Among other things, with just a simple confidence interval, you can't assume batting average has any effect on other elements of performance (including scoring runs, etc.); instead, sports statisticians have used various forms of regression analysis to determine how the different statistics available correlate with important performance elements (particularly, scoring runs, preventing runs from scoring, and winning games, for baseball as an example).  That gives you more ability to identify whether a player is likely on a hot streak, or whether his performance has truly improved  - separating the Mike Trouts of the world from the Chris Davises.
Answer: You're partially correct, but I think you're not applying the concept of a normal distribution in quite the right way for the context. In the context of hitting streaks, it would be more appropriate to look at the normal distribution as related to hitting streaks. In other words, assuming that hitting streaks follow a normal distribution with some mean indicating the average length of a hitting streak (say, 10 games). If you assume that hitting streaks are normally distributed, then to see a hitting streak of, say, 30 games won't happen very often, but it will happen. And even hitting streaks of 56 games, like Joe Dimaggio's record, will happen, just very, very rarely.
Assuming that hitting streaks follow a normal distribution does not, however, imply that a player's skill necessarily fluctuates. If you view batting average as a measurement of skill, for example, you can draw a parallel between batting average and probability. If a player has a batting average of .300, the parallel is that they have a 30% chance of getting a hit. If an event (at bat) has a 30% chance of success, and the event happens 3-4 times per game, you can calculate the expected "hitting streak" (i.e. minimum 1 success per game). That would be the mean of your distribution. You can also calculate the standard deviation of the streak and that gives you a normal distribution.
So we can still view a player as having a fixed skill level (which may or may not be correct) and it doesn't contradict the idea that long hitting streaks are expected to happen given the probability distribution of hitting streaks. I also think that doesn't necessarily take away from the value of a long hitting streak. A player with an "underlying skill" (i.e. Batting Average) of .300 is still much more likely to have a 20+ game hitting streak than a player with an "underlying skill" of .200.
Comment: So if the "true" .300 hitter (as determined by whatever means) hits .320 for a month, are you sure the difference from the mean is truly randomness (luck), or is his skill level temporarily higher, for any number of possible reasons, physical, psychological, etc?
Comment: With baseball, it's very hard to say whether it's luck or improved skill that causes fluctuations in statistics. You can do some analysis of how the player handles different situations (batting counts, certain pitches, etc.) to see if there are changes, but that's very tough. The point that most sabermetricians are making is that because of the number of batters in the league and the large number of games being played, if you assume hitting streaks are more or less normally distributed, you'd expect the occasional 25+ or higher streak.
Comment: Of course, I'm well aware. I've just never felt like there was a clear explanation for the source of the randomness. Some writers and analysts treat it as if it is luck, but, that doesn't pass the smell test for me. But maybe that's just bias.
Comment: Well, my interpretation of that particular viewpoint is that it's not "luck", it's just that even a .300 hitter will have times when they hit .200 or even .100. You don't expect a .300 hitter to get 3 hits out of every 10 exactly. I guess a probability view is flipping a coin. A coin is 50/50 heads/tails. That doesn't mean you expect the coin to alternate heads and tails. In probability theory, if you flip a coin long enough, you actually expect that any length streak of heads WILL happen eventually, no matter how long the streak is. I guess this is somewhat similar.
Answer:
One core idea in sports analytics is to be skeptical of hot streaks as being evident of anything more than just something a normal distribution would account for.

That isn't true. Successes of three point shots for example, don't follow a normal distribution. They are discrete trials, each with two possible events as outcomes: success, or failure. This is best modelled using a binomial distribution. This approaches the normal distribution if you have enough samples, but for something like a hot streak of 3 pointers, you don't usually have enough samples for the binomial to start looking really like a normal distribution.
Comment: ok, but a series of samples of a binomial distribution (say, sets of 10 3s in a row) will approximate a normal distribution. My point anyway is about randomness and fluctuation in sports. Is the randomness only of luck, or of skill/ability as well? The topic is often treated as only randomness in luck, but I am skeptical that's right.

Normal Distribution and Sports


preprocessing markup

Question: I have a file called template.php and inside the template file I have a preprocessor but I have two problems I don't know if the preprocessor is loading
and if the code in the file is right.
The code inside the file is
function template_preprocess_field(&$vars) {
        kpr($vars);  //Uncomment to output the $vars array.
   }
At this stage all I am trying to do is see if I can get the node to give me some feedback but I get nothing. The nodes I am testing this on does have three fields
Comment: Version numbers and location of template.php is required to answer your question.
Comment: drupal7 and themename->templates->template.php
Answer: Your template file should reside in the sites/all/themes/mytheme/ directory. Not in the templates subdirectory. Furthermore, your preprocess function should be named mytheme_preprocess_field(). Be sure to clear your cache.
You might want to perhaps also look at the Devel Themer module. It should provide information on the preprocess function being used and so on. I'm unsure how well it works with Drupal 7. But it's worth your time if it does.
Answer: Definitely, definitely get the Devel Theme module. It can be a great help in Drupal 7 when digging through the arrays on that page so you won't make any mistakes. It will give a simple list of the field names you can then call.

preprocessing markup


What makes a GLM estimate the means differently from the actual sample means?

Question: Disclaimer: I'll happily admit to not really knowing what I'm doing when it comes to General Mixed Models but hopefully this thread can bring me a little bit closer to some kind of understanding. If, however, this is an "OMG, you're such a n00b" question which should be closed and never spoken of again, I'll totaly understand :)
I'm running a couple of General Linear Model (using SPSS) to try to get a better feeling for the method. My dataset consists of a number of stimuli presentations with a dependent scale variable (ranging from 0 to 1) and a number of independent nominal variables for each presentation (for example the gender of the participant, a drug condition, type of stimuli et cetera).
Now, when I run a General Linear Model, I can generate a lot of pretty graphs showing both significant and non-significant main and interaction effects for all my data. When including just a couple of factors, the estimated means in these graphs are the same as if I do a descriptive analysis and just compute the means. However, when I start to add a lot of factors, the estimated means starts to deviate from the actual means in my sample.
I'm a bit confused here. What is it that makes the GLM estimate the means to be the same as the sample means and when do these estimated means start to deviate from the sample means? Does it have something to do with the number of factors, or is it about the factors themselves (for example, how they divide the data with respect to the other variables).
Comment: When it comes to GLMM noone asking questions is considered pejoratively as "a noob". For what its worth, I think this applies to this site generally.
Comment: @Speldosa, General Linear model of SPSS (GLM) corresponds to "linear model" tag of this site, not "generalized liner model". So I edited your tag
Answer: Let us have some data (shown below), predictand Y and two factors X1 and X2. X1 has 2 groups, and X2 has 3 groups. (In this particular example, the design is incomplete though, because combination X1=2 & X2=3 is absent.)
Let us run GLM command (shown). The settings are default: full factorial model, SS III type of squares, intercept present. The command requests to print out observed means for all groups of factors as well as for their combinations and also to print out the corresponding estimated means. It also saves predicted values for Y (shown below as "pre").
UNIANOVA y BY x1 x2
  /METHOD=SSTYPE(3)
  /INTERCEPT=INCLUDE
  /SAVE=PRED
  /EMMEANS=TABLES(OVERALL)
  /EMMEANS=TABLES(x1)
  /EMMEANS=TABLES(x2)
  /EMMEANS=TABLES(x1*x2)
  /PRINT=DESCRIPTIVE
  /CRITERIA=ALPHA(.05)
  /DESIGN=x1 x2 x1*x2.

     y     x1  x2      pre
  .725581   1   1   .725581
 -.147728   1   2   .046662
  .496867   1   2   .046662
 -.985803   1   2   .046662
 -.139656   1   2   .046662
 -.381405   1   2   .046662
 1.437696   1   2   .046662
  .039809   1   3  -.748909
-1.537626   1   3  -.748909
 -.402714   2   1   .159152
 1.900394   2   1   .159152
  .883087   2   1   .159152
-1.744157   2   1   .159152
 1.009084   2   2   .288968
 1.169746   2   2   .288968
  .579917   2   2   .288968
-1.022533   2   2   .288968
 -.587685   2   2   .288968
  .814123   2   2   .288968
  .003084   2   2   .288968
-1.068938   2   2   .288968
 -.175502   2   2   .288968
 1.290405   2   2   .288968
 1.166946   2   2   .288968
 -.645831   2   3  -.645831
 1.061533   3   1  1.061533
 1.143789   3   2   .676997
  .210205   3   2   .676997
 -.643339   3   3  -.360148
 -.076957   3   3  -.360148

Let us compare observed and estimated means printed out (I don't show these tables here). First, we can notice that on the lowest (the cell) level of the design, i.e. on the level of combinations of groups X1 * X2 estimated means equal observed means. This is because we had used saturated, full factorial model including all possible interactions between the factors.  Second, we can see that when it comes to means on the higher, marginal, level, estimated means do not (generally) equal observed means. For example, the observed marginal mean for X1=1 is -0.05470 and the corresponding estimated mean is 0.00778.
Can we show where this difference stems from? Yes. The observed marginal mean corresponds to the simple mean of the predicted values. For X1=1, this is mean(.725581,.046662,.046662,.046662,.046662,.046662,.046662,-.748909,-.748909) = -0.05470 which is the same as the simple mean of the observed values mean(.725581,-.147728,.496867,-.985803,-.139656,-.381405,1.437696,.039809,-1.537626) = -0.05470. On the other hand, the estimated marginal mean is given by averaging the predicted values with the collapsed groups weighted equally. That is, X2=1, X2=2, X2=3 are given equal weight despite their unequal frequencies, and so 0.00778 = mean(.725581,.046662,-.748909). You may conclude yourself that if the design had been balanced - cells contained equal frequencies - estimated and observed means would have been equal to each other.
That was a simple explanation for the simple case (by "simple case" I mean defaults such as Type III SS, intercept, no covariates). You may consult "SPSS Algorithms" help document to read about how estimated, expected means are actually computed in the general case.
Comment: Finally an answer that actually explains what these pesky *estimated marginal means* are (rather than promising and not delivering). I have been searching for this for so long! I will still have to figure out in what situations these *estimated marginal means* could be useful.
Comment: Interesting! So this will mean that if I skip to include an unbalanced factor (for example, an imagined X3 factor), I'll get estimated means that are closer to the actual mean for mean(X1=1, X2=1), mean(X1=1, X2=2) and mean(X=1, X2=3)...In my design, I have a factor, F, that is highly unballanced when it comes to number of cases for each level (meaning the observed means cannot be trusted to correspond to the actual means). According to this argument, I shouldn't include such a factor if I don't want to screw up my other results, right?
Comment: Generally speaking, yes. ANOVA or ANCOVA "worsen" as groups become more unbalanced. This is because main effects get entangled and and they also get entangled with interactions terms. Different SS types (I, II, III) try to untangle them in different but not optimal ways.
Comment: I have posted [this question](https://stats.stackexchange.com/questions/332167/what-are-ls-means-estimated-marginal-means-predicted-marginal-means-useful-fo) about the use of LS means; perhaps you will have some time to take a look at it at some point.
Answer: From my perspective this is completely legitimate question, which is in fact asked by many of my customers.
The mismatch can be attributed to the following:

Missing Data. SPSS by default excludes missing data case-wise. So if you happen to have missing observations in one factor, the cases on which the means are computed for the model (and, say, 2nd factor) are different (smaller in number) compared to those on which descriptive statistics are based.
Marginal means are computed with assumption, that each cell (i.e. combination of factor levels) has equal weight. This is in accordance with the more basic assumptions of ANOVA, and this is how basically ANOVA sees the data. So, if you have e.g. sex on two levels and education on two levels, the marginal mean for males is computed as $\frac{(\text{Mean of males with high education}) + (\text{Mean of males with college education})}{2}$ rather than

$\frac{(\text{Mean of males with high edu}) \cdot (\text{# males with high edu}) + (\text{Mean of males with college edu}) \cdot (\text{# males with college edu})}{\text{Number of males with any edu}}$, which equivalent to simple mean of males with any education.
This second point is equivalent to the answers given by
ttnphns and Kavin Kane, but in (my opinion) easier language.
Comment: I don't think (2) is correct. One need not assume balanced design for the marginal effect estimation in a GLM to be consistent and unbiased for the population averaged marginal effect. In fact, adjustment is required to ensure this works when using stratified sampling.
Comment: True. What I have written is how the SPSS (now: PASW) software is working by default in a simple language. After all, there is this disclaimer before the question.
Comment: @AdamRyczkowski Actually, they have changed the name back again. They now call it "IBM SPSS".
Answer: If you fitted a model with only one factor with the same number of levels as means you want to estimate (well, maybe one less as you have the intercept term), then the estimated means should be exactly the observed means. When you add other covariates (variables in the model) then when you estimate a least squares mean, balance is usually assumed. The means that for categorical covariates, the estimate asses that in the population, the number of individuals would be evenly spread across the levels of a covariates. In SAS, there is an option - OBSERVEDMARGINS or OM - that will give estimates based on the proportions observed in your sample, and these will usually be a lot closer to the sample means.
You have not mentioned that you are doing with the mixed or random effects. I wouldn't expect these to have a huge effect on the estimates of the means though.
I would say one thing though-if you don't understand what the methods you are using- get the help of a statistician. These things are easy to get wrong.
Comment: Thanks for your answer! However, I'm having some trouble understanding some parts of your explanation. The problem is that I get an interaction effect for interaction x*y*z when just including these factors, but that this interaction dissapears when I include the factors a, b, x, y, z. You are talking about certain options in SAS to give other estimates, but what happens to the significance testing in that case? I assume I just can't walk in, change how the estimated means are computed, and force the analysis to get significant.

Also, I'm just using fixed factors (that is, no random factors).


What is the z-value of glm model parameters?

Question: I know what the z-value of a single observation is, that is explained in Wikipedia. But what is the z-value of a parameter in a glm model?
Comment: Maybe [this post](http://stats.stackexchange.com/a/60083/21054) or [this one](http://stats.stackexchange.com/q/56066/21054) can help.
Comment: What exactly is Wikipedia's explanation?
Answer: It is the test-statistic for the Wald-test that the parameter is 0. It is the parameter divided by the standard error. If the null-hypothesis is true (i.e. the parameter is 0 in the population) and we were to draw many samples from our population and compute the z-statistic in each of them, then those z-statistics will follow a standard normal distribution.
Comment: Well - they're asymptotically normal so for small sample sizes it might not quite be normal.


Using Picard Approximation on $y'=2t(1+y),y(0)=0$.

Question:
Use the Picard approximation to find a solution for $y'=2t(1+y),y(0)=0$.

$\varphi_{0}=0$
$\varphi_{1}=0+\int_{0}^{t}f(s,\varphi_{0})ds=t^{2}$
$\varphi_{2}=0+\int_{0}^{t}f(s,\varphi_{1})ds=t^{2} +\frac{1}{2}t^{4}$
$\varphi_{3}=0+\int_{0}^{t}f(s,\varphi_{2})ds=t^{2} +\frac{1}{2}t^{4}+\frac{1}{6}t^{6}$
My claim is that $\varphi_{m}(t)=\sum_{k=1}^{m}\frac{t^{2k}}{k!}$. I am not sure if this is a right claim though. I want to use induction to prove this claim, but I am not sure how to calculate $\varphi_{m+1}(t)$, the inductive step.
Also, I cannot find the limit of this claim to find the solution. Do I use a convergence test and find radius of convergence?
Answer: The claim
$$\varphi_{m}(t)=\sum_{k=1}^{m}\frac{t^{2k}}{k!}$$
is correct. The exact solution is given by the limit
$$\varphi(t)=\lim_{m\to\infty}\varphi_{m}(t)=\sum_{k=1}^{\infty}\frac{(t^{2})^k}{k!}=\sum_{k=0}^{\infty}\frac{(t^{2})^k}{k!}-1=\text{exp}(t^2)-1$$
and the ratio test can be used to show that the series converges (and to find the radius of convergence). For the inductive step assume
$$\varphi_{m}(t)=\sum_{k=1}^{m}\frac{t^{2k}}{k!}$$
holds for all $m\in\mathbb N$. Then, you need to show that
$$\varphi_{m+1}(t)=\sum_{k=1}^{m+1}\frac{t^{2k}}{k!}$$
if I am not mistaken this follows directly from the definition.


Node reference field autocomplete and allow multiple selections in views

Question: I recently pdated my Drupal core to 8.9 and suddenly a functionality stops working.
I have a "Recipe" content type, it has a field of "Category" (field_category) which is Entity Reference: Node.
I tried to create a View and created a filter criteria field_category, and I want it to be Auto complete and Allow multiple selections.
I know its possible on Entity Reference Taxonomy, but currently its not possible on Entity Reference Node.
I found Views Autocomplete Filters (https://www.drupal.org/project/views_autocomplete_filters), but I want it to Allow multiple selections.
Comment: I'm trying to figure out how to do this in Drupal 7 (yes, I've told the site owner they need to upgrade, but here I am). I can't believe that I've been working on Drupal sites over a decade, and never realized that I can't "Allow multiple selections" on entity reference fields in views. It seems like such a basic thing.
Comment: Follow up, this can be done with a contextual filter, use the "Raw value from URL", then you can add the ids as /1234+5678 etc., and to include all results, just use /all. This is fine for me since I am building an API, but it might not work if you need it as an exposed filter, but it gets the job done at least.
Answer: I managed to solve my problem using this module:
https://gist.github.com/StryKaizer/ae1cb9abc4844a9e7ac12317a9d84a78


addClass() a um objeto através de um link externo

Question: Preciso criar uma função click() para 8 links que estão em uma pagina X, cada link vai me levar para um slide especifico em uma pagina Y.
O slide fica ativo quando esta com a Class selected, então minha ideia é a seguinte:
O usuário clica no link 1 na pagina X é levado para pagina Y com o slide 1 ativo.
O usuário clica no link 2 na pagina X é levado para pagina Y com o slide 2 ativo.
E por ai vai ...
Então resumindo, como faço para esse addCLass() funcionar após o carregamento da pagina Y.
Caso não tenha ficado muito claro eu edito.
Obrigado.
Comment: Você quer guardar qual item que receberá a classe nova?
Comment: Eu quero clicar no link 1 e ele adicione uma classe no Slide 1 e por ai vai ... @Laerte
Comment: So que ambos estão em paginas diferentes, link 1 pagina X e slide 1 pagina Y ...  @Laerte
Comment: Ué, passa por parâmetro na URL, a escolha. paginaY?slide=1, paginaY?slide=2
Comment: Se são paginas diferentes tem que ser por url ou com submit.
Answer: A ideia que me ocorre é passares no link uma query string para poderes analizar na página de chegada qual o slide que deve receber a classe. Por exemplo:
Slide 1
Slide 2

e na página dos slides:
var slide = location.search.match(/slide=(\d+)/)[1];
var slides = document.querySelectorAll('.slides');
slides[slide].classList.add('selected');

Isso é o esqueleto. Se precisares de ajuda a implementar diz, posso acrescentar mais detalhes logo quando sair do trabalho.
Comment: @Laerte sim, cookie também daria. Aí é preciso interceptar o redirect para escrever primeiro antes de o browser mudar de página.
Comment: usar sessionStorage é uma solução boa também, não?


Is it possible to prove that ceil(x/y) = ceil(ceil(x)/ceil(y))?

Question: Let $\operatorname{ceil}(x)$ be the smallest integer greater than or equal to $x$. (Also denoted $\lceil x\rceil$.)
Is it true that $\operatorname{ceil}(x/y) = \operatorname{ceil}(\operatorname{ceil}(x)/\operatorname{ceil}(y))$?
It would help me out if this would be provable but I am not that familiar with the ceil and floor functions in mathematics. I am not sure what properties I could apply.
Comment: Hint: Try some small examples.  Become familiar with the ceiling function, it is not that difficult.
Answer: The statement is not true.
Consider $x=0.9$ and $y=0.1$ then $\lceil\frac{x}{y}\rceil=9$ while $\lceil\frac{\lceil x\rceil}{\lceil y\rceil}\rceil=1$
Comment: @LiamMartens If $\lceil \frac x2 \rceil=n$, then $n-1<\frac x2 \leq n$. So, $2n-2<x\leq 2n$. Thus, $2n-2 < \lceil x \rceil \leq 2n$. So, $n-1<\frac{\lceil x \rceil}{2} \leq n$. Therefore, $\left\lceil \frac{\lceil x \rceil}{2} \right\rceil =n$. You can generalize this for other integers than 2.
Comment: Would it be true if y were an element of Z?
Comment: @LiamMartens. Yes. Graph $\lceil\frac{x}{2}\rceil$ and $\lceil\frac{\lceil x\rceil}{2}\rceil$ to get an intuition.
Comment: @RickDecker and how would one prove this?


About $\alpha$-indecomposability.

Question: One defines $\alpha$-indecomposability, for ultrafilters $\mathcal{D}\subset\mathcal{P}(\kappa)$, as: for every $\langle I_\beta:\beta<\alpha\rangle$ with $\bigcup_{\beta<\alpha}I_\alpha=\kappa$, one can find $s\in[\alpha]^{<\alpha}$ with $\bigcup_{\beta\in s} I_\beta\in\mathcal{D}$.
Now, i want to prove: if $\mathcal{D}\subset\mathcal{P}(\kappa)$ is $\mu^{(n)}$-indecomposable, for every $n\geq1$, then:
\begin{equation}
\prod\mu^{(n)}/\mathcal{D}=\bigcup_{\nu<\mu^{(n)}}\prod\nu/\mathcal{D}.
\end{equation}
Here $\mu^{(n)}$ is the $n$th succesor of $\mu$: $\mu^{(0)}=\mu$, $\mu^{(n+1)}=(\mu^{(n)})^+$.
Comment: Where does this problem come from? What did you try? Also, I'm curious about the notation, is $\mu^{(n)}$ standard for the $n$th successor of $\mu$? I'm more familiar with $\mu^{+n}$. I assume you identify the ultraproducts with their transitive collapses, is that right?
Comment: I do not identify the ultraproducts with their collapses. It came from Prikry's work, On descendingly complete ultrafilters, 1973 pp 6,7. And i wanted to use the indecomposability with $\langle\nu:\nu<\mu^{(n)}\rangle$, but so far nothing. One side of the equality seems trivial. And i don't know how standard is that notation, but that's the only one i knew until now.
Comment: Please state your definition of the ultraproduct then. Do you mean just the quotient via the equivalence relation induced by $D$? Then, equality cannot hold but they might be isomorphic (as structures with the $\varepsilon$-relation also induced by $D$).
Did you notice that if you have $f:\kappa\to\mu^{(n)}$ you can apply indecomposability to $(f^{-1}(\alpha)\mid\alpha<\mu^{(n)})$ and use regularity of $\mu^{(n)}$ to get a bounded $g\colon\kappa\to\mu^{(n)}$ which is $D$-a.e. equal to $f$? I'm not completely sure what you're asking but I'd assume that this should be involved in a solution.
Answer: The reversed inclusion is obvious, so I will just give a proof of the inclusion
\begin{equation}
\prod\mu^{(n)}/\mathcal{D}\subseteq\bigcup_{\nu<\mu^{(n)}}\prod\nu/\mathcal{D}.
\end{equation}
Assume that $f : \kappa \to \mu^{(n)}$ is a function. We shall check that it is bounded almost everywhere with respect to $\mathcal{D}$; that is, we have some $\nu<\mu^{(n)}$ such that
$$\{\xi < \kappa : f(\xi)<\nu\}\in\mathcal{D}.$$
Assume that we know $f$ is bounded almost everywhere with an upper bound $\nu$. Then we have a bounded function $g$ such that $[f]=[g]$ and $g(\xi)\le \nu$ for all $\xi$. (How? You can find such $g$ if you are familiar with ultrfilters.) Hence $[f]$ is an element of $\prod \nu/\mathcal{D}$.
Take $X_\alpha = \{\xi<\kappa : f(\xi) < \alpha\}$. Then $\bigcup_{\alpha<\mu^{(n)}} X_\alpha = \kappa$. By $\mu^{(n)}$-indecomposability, there is a $s\subset \mu^{(n)}$ such that $|s|<\mu^{(n)}$ and $\bigcup_{\alpha\in s} X_\alpha \in\mathcal{D}$. We know that $\mu^{(n)}$ is regular for each $n\ge 1$, so $\nu := \sup s < \mu^{(n)}$. Moreover, if $\alpha\in s$ then $X_\alpha \subseteq X_\nu$.
Therefore $X_\nu = \{\xi<\kappa : f(\xi) < \nu\} \in \mathcal{D}$, and so $f$ is bounded almost everywhere.

About $\alpha$-indecomposability.


One character in multiple groups

Question: I have a string like:
s = 'ababbabbba'

I'm trying to match all patterns matching any number of b's between a's. This is what I expect the patterns to be for s above:
['aba', 'abba', 'abbba']

This is what I've tried:
import re
re.findall('ab+a', s)

Which gives:
['aba', 'abbba']

I think that happens because any single a can only be part of a single group. Whereas my requirement would make the middle a's be part of two groups. Reading through the re documentation, I can't find any way to do this.
Comment: https://stackoverflow.com/q/5616822/1324033
Comment: Duplicate of [Python regex find all overlapping matches?](https://stackoverflow.com/questions/5616822/python-regex-find-all-overlapping-matches)
Answer: Based on the comment above, the solution is:
re.findall('(?=(ab+a))', s)

One character in multiple groups


Deleting Influential Points Leading to Non-constant Variance

Question: http://archive.ics.uci.edu/ml/datasets/Wine+Quality
Using this data set, I am regressing chlorides on ten predictors (all except quality). After Box-Cox transforming chlorides, I get the following Q-Q plot and influential diagnostic plots:

As you can see, the points 837 and 838 are very influential, and so I decided to delete them and see what happens. Surprisingly, after deleting them, my model rejected the null hypothesis that the model has constant variance (p-value of almost 0) although it failed to reject the null hypothesis before deleting the points. Thus, should I keep the points?
Answer: If those two points are very influential, it means they are very informative. It seems strange to want to delete informative data! Anyhow, such a decision should not be taken on the basis of secondary criteria like constant variance or not.
The reason it is a good idea to check on influential data points, is to check if they are correct. If they are correct, should definitely be kept. If they are (or could be erroneous), maybe delete them. But never make such decision on the basis of secondary criteria like you mention.


Counting random shots (foosball)

Question: Is there a definition of foosball random shots?
Do people track them somehow for fun as a "debt" as part of championship ladder?
Comment: I had no idea there was foosball lingo.  If there is that is kind of interesting.  And certainly can make me seem like a uber-nerd next time I play at the bar.
Answer: I assume you are asking about "official" foosball rules (ITSF)? Otherwise, there can be definitions just about everything because your local home games can make rules up.
In ITSF, there's no "random" shots, all shots that goes in, will count as a normal point (if it's shot legally). There's no point in tracking them any differently. How would one really define a random shot? It would depend entire on player skill, some player can reliably see a gap and place a 2-bar shot straight in or even bank it in, but another less skilled player might do that "randomly"... How would you determine that?
In high level gameplay, almost no shot "randomly" goes in. Even a quick pickup and attempt on goal from a loose ball is general high percentage because of proper angling and lightning fast aiming.

Counting random shots (foosball)


Advantages and Disadvantages of NHibernate

Question: What are the advantages/disadvantages of using NHibernate ?
What kind of applications should be (& should not be) built using NHibernate ?
Answer: Since other ppl have listed advantages I will just list the disadvantages

Disadvantages

Increased startup time  due to metadata preparation ( not good for desktop like apps)
Huge learning curve without orm background.
Comparatively  Hard to fine tune generated  sql.
Hard to get session management right if used in non-typical environments ( read non webapps )
Not suited for apps without a clean domain object model ( no all apps in world dont need clean domain object models) .
Have to jump through hoops if you have badly designed ( legacy ) db schema.
Comment: I highlight the immense learning-curve as the single biggest reason to not use NHibernate on a project. For all their drawbacks, tools like LINQ to Sql are significantly easier to get to working than NHibernate. That said, I'd much rather use NHibernate on a project than any other ORM thanks to its amazing flexibility.
Comment: @Garry N+1 selects and its cousin over eager fetching are bane of most of nhinbernate projects . Using straight sql would defeat the whole point of a ORM
Comment: Just on point 3, NHibernate lets you run straight SQL or stored procedures and will help translate the results into your model for when you really need to worry about the SQL used.
Comment: @Programming Hero linq and nhibernate are not mutually exclusive. They solve two different problems . I think there is a linq implementation for nhibenate too.
Comment: @Surya - I would say that N+1 selects is a bane for any ORM that is not used properly .
Comment: Same for over eager fetching. Plus , I think 3, 4, 5, 6 will apply to all ORMs right ?
Comment: Linq2Sql is limited to SQL Server and also Microsoft ditched it in favour of EntityFramework which is about same in many aspects as NHibernate.
Comment: @sirrocco yeah you might be right . Some orm projects out there claimed to have "solved" n+1 select *problem* ..so i wont say its acommon problem across any orm.
Comment: Advantages/Disadvantages comparing to what? If to poor DataSet then it is one set of things, if comparing to other O/R-M tools then it is other.
Comment: @Dmitriy OP asked for disadvantages of bringing in nhibernate to a project , what aspect of nhibernate causes it is irrelevant
Comment: I don't understand how point 5 is relevant.  NHibernate allows you to work from a domain driven design down to the database (whereas most other ORMs do not), but it doesn't require domain driven design.
Answer: Advantages:

Flexible and very powerful mapping capabilities.
Caching.
Very polished UnitOfWork implementation.
Future query (article).
Model classes are POCO - which effectively means you can easily implement anemic domain antipatter.
Interceptors - you can do a kind of aspect oriented programming... Like very easily implementing audition, logging, authorization, validation, ect for your domain.
Lucene.NET and NHibernate are well integrated with each other - gives you a very fast and effective implementation of full-text indexing.
It's very mature and popular in enterprise environment.
Big community.

Disadvantages:

Already mentioned learning curve. You can start using NHibernate very fast but it will take you months to master it. I'd highly recomend to read Manning NHibernate book.
Writing XML mapping can be very tedious especially for big databases with hundreds and thousands of tables and views and stored procedures. Yes, there is tools that will help you by generating those mappings but you still will have to do quite a lot of manual work there. Fluent NHibernate seem to simplify this process by getting rid of XML mappings, so is Castle ActiveRecord (AR though is impossible to use for anemic domain as you define mappings in attributes on your model classes).
Performance may be low for certain scenarious. For instance large bulk operations. For those you might have to use IStatelessSession but its awkward experience, least to say...
Comment: For generating XML mappings, at least consider Active Writer: http://using.castleproject.org/display/Contrib/ActiveWriter
Answer: Advantages:

Open source
Based on widely approved patterns
NH is not code-generator :)

Disadvantages:

Half-done LINQ support
Low performance

(see for example performance and LINQ tests on ormbattle.net)
Comment: Those benchmarks are incorrect. See here http://ayende.com/Blog/archive/2009/08/15/benchmarks-are-useless-yes-again.aspx
Comment: Speaking technicaly, NH IS code generator - it reads metadata and generates proxy classes using either LinFu or Castle DynamicProxy.
LINQ support in Linq2Nhibernate seem to be full as far as Criteria API allows to go, so yeah it more limited than HQL but still very powerful and enough for most situations.
Totally disagree about performance.
Comment: Agree with you, it's runtime code generator, but not design time. I personally don't like tools, that generate tons of code in design time. So it's an advantage of NH. As for LINQ, there is no doubt, they are just at the beginning of the road.
Comment: Benchmarks are correct, Oren believes that ORM vendors shouldn't minimize overhead, added by ORM. In addition he wrote about batching  CUD only, what about other operations? I agree that performance is not the main factor, but in some cases it is very important.
Comment: Benchmarks are correct, but NH team does not want to play the game honestly. Their own test vs EF they made was simply a hack: http://ormbattle.net/index.php/blog/105-a-honest-comparison-of-entity-framework-and-nhibernate.html
Answer: Advantages:

Caching
Simplicity in your code
Power
Flexibility
Multi-database support

Disadvantages:

Stops you having to write your own persistence code
May reduce your knowledge of SQL

Applications you should use it for:

Any that use a database

A few more specific reasons to like NHibernate
Comment: I don't understand why 'Stops you having to write your own persistence code' is a disadvantage.
Comment: Some people like having to write more code than is necessary. It was a bit tongue-in-cheek.
Comment: I would add : Any that use a database - `but are not using it just for data manipulation : loading thousands of rows in memory `
Comment: How can it reduce knowledge of SQL?
Not having to write own persistance code seems more like an advantage to me... Why would you want to reinvent the wheel anyways?
Also by far not every application that uses database should be accessed through NHibernate...
Answer: The high level answer is that NHibernate is in a class by itself and there is no near competition.
If you need CRUD against a database from a .NET application, you should be using NHibernate, for at least two reasons:
1) You get Linq support (which requires something like an ORM)
2) NHibernate is very mature
There are no significant disadvantages.  There are other options, but those other options have significant disadvantages.
I wrote some more on this a while ago:
.NET and ORM - Decisions, decisions
Answer: Disadvantages: NHibernate is not a Microsoft product and therefore will face some resistance from coworkers who haven't heard of it. Especially FOSS bigots. Configuring the mapping files and lazy/eager loading behavior can be time-consuming. If your database has a bizarre naming convention, atypical design or very strict performance requirements, more work may be required than expected.
I say this a lot but ActiveRecord is a great layer over NHibernate. It uses attributes to map the data points to class members right in the classes themselves. People are not using this thing enough.


RDP Connection to Civicrm VM on Azure failing

Question: I used the Bitnami image VHD from VM Depo to create an Azure VM running CiviCRM from the ready to go
I added the remote desktop as an end point and when I try to rdp in I get the following error: "This computer can't connect to the remote computer"
These are my settings, any ideas what I need to do to access the VM and get CivicCRM to run ?
Azure VM CiviCRM dashboard: http://cropme.ru/ac4a84a2b5f91640ad843c08da97d80c
Azure VM CiviCRM endpoints: http://cropme.ru/8fc7843477b9652a4029b571690da679
Answer: civiCRM is on Ubuntu Machine! This is a Linux and does not have Remote Desktop enabled by default.
What you have added is an RDP endpoint (standard) for a Windows Server machine. It will not work with Linux images. With any linux images.
If you want to login remotely, your only chance is the SSH via port 22. Once logged-in on the console, you may install some X-Window and enable remoting on it. You will, however most probably need a VNC client for it and not the standard windows Remote Desktop Client.
You also most probably don't need a Remote Desktop at all. CiviCRM is a web-based open source CRM solution. Being web based, means that you have to access it over WEB.
Add a new endpoint - public port 80 and private port 80 for your VM. Then navigate to it with the browser! And you shall see the welcome screen of CiviCRM.
Comment: Generally correct.  RDP and VNC are both possible, but most likely neither is advisable.  You'll also want a file transfer client of some sort.  WinSCP is old, but works fine for me.  Some sort of rsync client might also be useful.  If you're going to try developing locally, I'd recommend not using windows.  Much easier if your local environment is Linux or Mac (Mac being unix-ish under the hood).


Volume and surface area of $3/4$ of a sphere

Question: Take for example a 3-D sphere cut horizontally into quarters:

How would I identify the volume and surface area of top $3$ horizontal cuts?
Would it just be $\frac34\cdot$volume of complete sphere and $\frac34\cdot$ surface are of complete sphere?
Thanks for your time.
Comment: No... of course the volume isn't 3/4 the total volume, nor the area 3/4 the total area, because you're cutting of a *cap*.  Just look at it!
Answer: You could integrate.
$$\int_V dV=\int A(x)\,dx$$
where $A(x)$ is the area of a slice of the sphere. Since this is a circle, $A(x)=\pi r^2$ where $r$ is the radius of this slice.
What is the radius there? We can get it from the Pythagorean theorem: sphere slice
So we are computing
$$\int_V dV=\int A(x)\,dx=\int \pi(\sqrt{R^2-x^2})^2\,dx=\int \pi(R^2-x^2)\,dx=\pi\int R^2-x^2\,dx$$
The bounds of the integral depend on which of the slices you're looking to find the volume of. In the case of the bottom slice in your picture, we want to go from $0$ to $R/2$.
$$
\begin{eqnarray*}
\pi\int_0^{R/2}R^2-x^2\,dx&=&\pi\left(\left.R^2x-\frac{x^3}{3}\right|_0^{R/2}\right)\\
&=&\pi\left(\frac{R^3}{2}-\frac{R^3}{24}\right)
\end{eqnarray*}$$
Modify the bounds and recalculate this to get the area of the first and second slices.
Can you modify this argument to compute the surface area? (Hint: the area of a each slice adds up to be the volume, so for the surface area, you want to use the ____ of each slice...?)
Answer: Area  proportionality/linearity with water height is valid for  Area but not  Volume. Derivatives of functions typically illustrate this.
Imagine a spherical tank (constant $R$ ) being filled from bottom by means of a flexible garden hose. We monitor with respect to water column height representing sections you mentioned. We have for the wetted area
$$ A= 2 \pi R h$$
$$ \dfrac {dA}{dh} = 2 \pi R \tag1 $$
which is a constant, this is linear dependence. ( btw, Archimedes was the first to state this).
However,
$$ V= \dfrac{\pi h^2}{3}(3R-h) $$
$$ \dfrac {dV}{dh} =  \pi h (2R-h) \tag2 $$
FractionalVolume $(=Volume/\frac43 \pi R^3)$is plotted against Fractional Area $(=Area/4 \pi R^2)$

In answer to your question, fractional areas and volumes have to be compared.
Half Volume is filled when half Area is wetted. When quarter Area wetted, less than quarter Volume is filled. But when $\frac34$ Area is wetted more than $\frac34$ Volume is filled.
The rates at which volume increases is neither constant nor proportional to height $h$. The graph above shows the volume growth rate is zero when sphere starts to fill and when full, but maximum when water level is on the equator.
Answer: No, the volume & total surface area of the sliced\cut sphere are not $3/4$ of the volume & surface area of the complete sphere but the curved surface area (excluding the area of the circular face) of the sliced sphere becomes $3/4$ of the surface area of the complete sphere.
In general, the volume $V$ & total surface area (including area of circular face) $A_t$ of frustum of sphere (i.e. sliced\cut by a plane) having a radius $R$ & vertical height $H$ (as shown in figure below) are given by
$$\boxed{\color{blue}{V=\frac{\pi}{3}(3R-H)H^2}}$$
$$\boxed{\color{blue}{A_t=\pi H(4R-H)}}$$
$$\boxed{\color{blue}{\text{Curved surface area, }A_s=2\pi RH}}$$
Where, $0\le H\le 2R$

As per your question, the vertical height of the sliced sphere is $H=\frac{3}{4}(2R)=\frac32R$. Plugging this value in the above-generalized formula, we get the volume & total surface area of the sliced sphere as follows
$$V=\frac{\pi}{3}\left(3R-\frac32R\right)\left(\frac{3R}{2}\right)^2=\frac{9}{8}\pi R^3=\frac{27}{32} (\text{Volume of complete sphere})$$
$$A_t=\pi \cdot \frac32R\left(4R-\frac32R\right)=\frac{15}{4}\pi R^2=\frac{15}{16}(\text{Surface area of complete sphere})$$
While the curved surface area $V_s$ of the sliced sphere
$$A_s=2\pi R\left(\frac32R\right)=3\pi R^2=\frac{3}{4}(\text{Surface area of complete sphere})$$


Is the canvas.getContext('2d').arc() method centered?

Question: I noticed that I don't need to offset circles to center them. Is it autmatically centered? If so, why is it unlike the rect, fillRect, fillText, and strokeText methods?(These all have to be offset to be centered)
Answer: Yes a full arc() (i.e a circle) will be centered to the x and y parameters you pass to it. These two parameters define the origin of the ellipse that will get drawn.
You are right, it is quite different than the rect() (and its fill / stroke equivalents) method, which is actually a shorthand for
lineTo(x, y);
lineTo(x + width, y);
lineTo(x + width, y + height);
lineTo(x, y + height);
lineTo(x, y);

So we could say the origin of the rect method will be its top-left corner, just like it is for drawImage and putImageData methods.
But fillText() origin for one can be controlled by setting textAlign, and textBaseline properties of your context, so this one is quite different.
And for other path methods, they use control points, so the notion of an origin doesn't really apply there.

var x = 250;
var y = 100;
var txt = ['click to redraw the rect', 'using the long-hand version'];

var ctx = canvas.getContext("2d");
ctx.font = '14px sans-serif';
var w = ctx.measureText(txt[1]).width;
// fillText origin can be set
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.fillText(txt[0], x, y - 8);
ctx.fillText(txt[1], x, y + 8);
// rect / strokeRect / fillRect is top-left
ctx.strokeRect(x, y, w, 16);
// arc is x,y
ctx.arc(x, y, w / 2, 0, Math.PI * 2);
ctx.stroke();
// show that rect is just a shorthand
onclick = function() {
  ctx.beginPath();
  ctx.strokeStyle = 'red';
  ctx.lineTo(x, y);
  ctx.lineTo(x + w, y);
  ctx.lineTo(x + w, y + 16);
  ctx.lineTo(x, y + 16);
  ctx.lineTo(x, y);
  ctx.stroke();
}
<canvas id="canvas" width="500" height="200"></canvas>
Answer: No, it's not automatically centred. Check this article from MDN:

Parameters: x The x-axis coordinate of the circle's center

So no, you have to specify it, unless it's on your current path


Matroid Theory with Graph Theory, Need an Introduction Book

Question: I am looking for a undergraduate introduction to matroid theory. We got them introduced today, to prove the Kruskal algorithm.... I can't say it was more elegant then the direct proof of the algorithm. I also do not see any benefits. Could maybe some explain why matroids are "great", my prof was very very fond of matroids.
I am also looking for an introduction book, maybe with exercises and solutions. (Russian, English, and German are okay.)
Answer: Most standard matroid theory texts feature graphic matroids as examples. James Oxley's survey paper ''What is a matroid?'' is a great starting place to learn about matroids, and has exercises. For more beyond that paper, Oxley's text Matroid Theory is the standard modern reference.
If you're interested particularly in optimization, it is a theorem that matroids are exactly the structures for which the greedy algorithm "works" (just as in Kruskal's algorithm).
Answer: Matroids: a geometric introduction by Gordon, McNulty was a good starting point for me.
Comment: @kjetilbhalvorsen The book I recommended is a Matroid theory book created specifically for undergraduate studies. That's the very first thing Joshua asked for.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://math.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://math.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/1035235)
Comment: @kjetilbhalvorsen Well...it kinda does answer the question... **Question.** I am looking for a undergraduate introduction to matroid theory. **Answer.** Matroids: a geometric introduction by Gordon, McNulty was a good starting point for me.