Print image URL with image style

Question: I would like to print an image URL with an image-style.
This doesn't work, since I don't have a ".value"-value for the image: How to find image style URL from within twig template?
Is there anything different on field-templates?
My code in field--field-images.html:
{% for item in items %}

{% endfor %}

This doesn't work (results in no filename since .value isn't available:

This crashes the page:

Thanks!
Comment: Possible duplicate of [Render Teaser Image in search block using Twig](https://drupal.stackexchange.com/questions/214366/render-teaser-image-in-search-block-using-twig)
Comment: Don't do this with template code, configure the proper image style in `Admin > Structure > Content types > (your bundle) > Manage display`
Comment: Just let it render normally and use the display config proper.
Comment: I forgot to say: there's lots of other custom-code in the template file, so I can't use the display configured in the display-settings.
Comment: Have you tried something like this: https://drupal.stackexchange.com/questions/219039/rendering-an-image-field-in-page-html-twig-with-a-custom-image-style Otherwise the only way I can think of is to use a preprocess to add a variable to the template.
Answer: Change the display mode of your field with the image style you want. And it's ok
But If you want do this with a custom module, you can do this:

$imageFile = Media::load($media_mid);
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$imageThumbnailUri = $style->buildUrl($imageFile->get('thumbnail')->entity->getFileUri());

Print image URL with image style


Correlation with very different sample sizes

Question: I am new to statistics (self-taught since I need it for my thesis) and I have a question that I haven't been able to find an answer to yet. For my thesis I want to find out whether there is any relationship between how students and their teachers answer a likert scale questionnaire (several items forming a scale). I want to see whether there are any similarities/if teachers influence their students thinking in certain areas. I have questionnaires from 3 teachers and their 160 students. The questionnaire I used is based on an existing one but it has never been analysed in this way. What calculation or correlational analysis would best answer my research question?
I am very thankful for any tips or answers!
Answer: What I would do:

Group the students according to the teachers and check for
correlations to each answer.
Check if this correlates with the teachers answer.
EDIT:

You could take the average value of the student's answers (or their sample median, or 25% quantile, ...) and compare those to their teacher's answers. Doing so, you get two datasets per class: one for the teacher and one (averaged) for the students. These you can easily correlated.
If you want to take it one step further, you could weight the calculated correlations (from above) by the students variance.

Check if this correlates with the other student's answer -- a certain topic might be sexy, indep. of the teacher.

With your dataset it will be impossible to insure that your conclusions are valid for the teachers population, because you can't assume that the three teachers are representative for the whole population. However, if you have more than 20 questions per sheet, the evaluation whether or not there exists a correlation between the answers of these particular teachers and students might be possible.
EDIT:
In my experience, one should not take all student's and teacher's answers on evaluation sheets too seriously. Questions are interpreted and the answers do strongly depend on the current mood of the person. Therefore, it might be wise to evaluate only those questions which invoked extrem answers (bad and good) in a second "interpretation" of the data.
Comment: Thank you for your answer! I know this will not be valid for the teachers, but it would already be great to find out that there is maybe something there since this an exploratory study.

I grouped the students according to the teachers. I also checked whether are differences between the groups. Some answers from the students correlate with each other because they form a Likert scale together (Cronbach's Alpha is reliable).

I'm not sure if i completely understand what you suggest to do next (I'm sorry I'm really new to statistics). How exactly would I check for correlations to each answer?
Comment: I edited my answer. Hope the calculation is clear.
Answer: In my opinion, the vast differential between the two sets of variables (3, 160) means that you really can't statistically answer comparative questions between the two samples. Full exhaustive correlation cannot be performed, due to the small sample size of the teachers. The second problem you have in re the teacher sample is that a Likert-style question, usually means that there are either seven levels (desirable) or 5 levels (acceptable), each of which should ideally have a discernable midpoint (unlike a 4-point scale). Thus,in all likelihood, not every answer that COULD be given by a teacher in the Likert item WAS in fact encountered. You therefore have no ability to answer whether the responses differed according to the introduction of an external variable. It's like asking 3 people what their favorite number is from one to ten, having results 1, 4, and 4 and declaring 4 everyone's favorite number.


A case of survivorship bias?

Question: With the recent FIFA world cup, I decided to have some fun and determine which months produced world cup football players. Turned out, most footballers in the 2010 world cup were born in the first half of the year.
Someone pointed out, that children born in the first half of the year had a physical advantage over others and hence "survivorship bias" was involved in the equation. Is this an accurate observation? Can someone please explain why he says that?
Also, when trying to understand the concept, I found most examples revolved around the financial sector. Are they any other everyday life examples explaining it?
Comment: See my answer at https://stats.stackexchange.com/questions/353519/can-redundant-irrelevant-features-be-called-a-noise/479674#479674  and its references
Answer: The basic idea behind this is that football clubs have an age cut-off when determining teams.  In the league my children participate in the age restrictions states that children born after July 31st are placed on the younger team.  This means that two children that are effectively the same age can be playing with two different age groups.  The child born July 31st will be playing on the older team and theoretically be the youngest and smallest on the team and in the league.  The child born on August 1st will be the oldest and largest child in the league and will be able to benefit from that.
The survivorship bias comes because competitive leagues will select the best players for their teams.  The best players in childhood are often the older players since they have additional time for their bodies to mature.  This means that otherwise acceptable younger players are not selected simply because of their age.  Since they are not given the same opportunities as the older kids, they don't develop the same skills and eventually drop out of competitive soccer.
If the cut-off for competitive soccer in enough countries is January 1st, that would support the phenomena you see.  A similar phenomena has been observed in several other sports including baseball and ice hockey.
Comment: By "January 1st", I presume you mean the cut-off is an entire year and not 6 months period that applies to your children.
Answer: Malcom Gladewell analyses the problem in the book Outliers by analyzing Hockey Players.

A case of survivorship bias?


Convert a string to an array and reverse it

Question: I'm trying to convert a string into an array and then reverse it using Enumerable#each. In the following, I expect to get ["k","o","o","b"].
def reverse(string)
  array = string.split("")
  reverse_array = []
  i = array.length - 1
  array.each do |letter|
    reverse_array << letter[i]
    i = i - 1
    break if i == -1
  end
  p reverse_array
end

reverse("book") # => [nil, nil, nil, "k"]

Can someone explain why I'm getting nil, and how I would fix the code using Enumerable#each?
Comment: Possible duplicate of [Reverse a string in Ruby](http://stackoverflow.com/questions/3057967/reverse-a-string-in-ruby)
Comment: While getting rid of `[i]`: get rid of lines 4, 7 and 8 too.
Comment: The problem is with the line `reverse_array << letter[i]`. The variable letter holds a single letter, not an array, so just get rid of `[i]`.
Answer: Your string is "book". So, array = string.split("") is ["b", "o", "o", "k"]. Then you iterate with i, starting with non-0, decrementing to 0. Since the element strings all have length 1, letter[i] will return the string itself when i is 0, and nil otherwise. That gives you reverse_array to be [nil, nil, nil, "k"].
A fix would be replacing:
reverse_array << letter[i]

with:
reverse_array << letter


Why can you place in the recursive definition to find the limit?

Question: When required to find limits of recursive sequences, i.e.
$$x_{n+1}=\frac{1}{4-x_n}\qquad x_0=3$$
The steps are usually pretty consistent. First you prove it's monotonous and bounded, and therefore converges, then you place $L$ in the equation and compute the limit itself.
$$L=\frac{1}{4-L}\implies L=1\pm \frac{\sqrt{3}}{2}$$
And then you choose the lower one because it's the real limit.
Now the placement seems to be a recurring motive, but I just can't understand why it's true, especially since you get 2 "limits" where one of them is just magically right.
The only explanation I seem to find is that $x_{n+1}$ and $x_n$  are actually the same sequence, which I sort of intuitively understand, but I'm still uncertain of. Is there any rigorous justification for this placement?
Comment: The function defining the recursion must be continuous, otherwise you can't determine the limit in that way. If $f$ is continuous and $(y_n)$ is defined via a starting value and the recursion $y_{n+1} = f(y_n)$, then from $\lim f(y_n) = f(\lim y_n)$ you obtain that the limit must be a fixed point of $f$.
Comment: You can formly prove that $ a_{n} $ and $ a_{n+1} $ have the same limit. Just use the $\varepsilon - \delta $ definition of the limit and take the $ N $ whice suits the problem.
Comment: What do you mean by placement?
Answer: The reason we can replace $x_n$ and $x_{n+1}$ with the same $L$ is because they have the same limit. To see why this is true we need the definition of the limit of a sequence: we say $x_n \to L$ when for all $\epsilon > 0$ there exists $N \in \mathbb{N}$ such that for all $n\ge N$ we have
$$ |x_n - L| < \epsilon.$$
Since you have proved that $x_n$ converges we can use this definition to show that $x_{n+1}$ also converges, and to the same limit. Let $\epsilon > 0$. Let's say $x_n$ converges to some real number $L$. Then by the definition of the limit we can choose $N\in \mathbb{N}$ such that if $n\ge N$ then $|x_n - L| < \epsilon$. Now given $n\ge N$ we have $n+1 > n \ge N$ so that
$$
|x_{n+1} - L| < \epsilon.
$$
Thus, by the definition of the limit, $x_{n+1} \to L$.
Now that we have established that $x_{n+1}$ and $x_n$ have the same limit $L$ we can compute the limit of the recursion. Taking the limit of both sides,
$$
\lim_{n\to\infty}x_{n+1} = \lim_{n\to\infty} \frac{1}{4-x_n}.
$$
Now using that $x_n \to L$ and $x_{n+1} \to L$,
$$
L = \frac{1}{4-L}.
$$
We can expand and simpify this to get the quadratic
$$
L^2 - 4L + 1 = 0
$$
which, by the quadratic formula, has roots
$$
L = 2 \pm \sqrt{3}.
$$
Now the reason why $L$ is "magically" $2- \sqrt{3}$ is because it's the only root that makes sense: note that $x_n$ is monotone decreasing and bounded below by $2 - \sqrt{3}$ so it converges to $2-\sqrt{3}$ by the monotone convergence theorem.
Comment: @Dr.SonnhardGraubner as the OP has said in their question, $x_n$ is bounded and monotone.
Comment: @Dr.SonnhardGraubner Show by induction that $0 < x_{n+1} < x_n \le 1$ for all $n\in \mathbb{N}$.
Comment: That makes everything clear. Thank you very much!
Comment: and why does the limit exist?
Comment: i can't find a proof for it


renaming all files in a folder deletes all files

Question: I am trying to rename all files in a folder but the current method im using is deleting all the files in that folder. Why is that happening and how can I fix it? Thanks in advance.

fs.readdirSync(path.join(__dirname, '..', 'blah')).forEach(file => {
  fs.rename(path.join(__dirname, '..', 'blah', file), file.replaceAll(' ', '~'), (err) => {
    if (err) throw err;
    console.log('Rename complete!');
  });
});
Answer:
On unix systems (macOS, linux) the ~ symbol has a special meaning in a file path, you can't use it for a file name.
So for example, ~/Music/blah.mp3 means /User/John/Music/blah.mp3. It's kind of like . or ... So you shouldn't use it for the name.

When renaming a file, you need to give the full absolute path to that file in the new name, not just the name of the file.
So renaming path.join(__dirname, 'blah.mp3') into 'foo.mp3' would move the file from /User/John/a/b/blah.mp3 (depending on where "__dirname" is) to /foo.mp3 (at the root of your system).

I think readdirSync returns an array of full paths, so you shouldn't need to prefix file with __dirname/../blah

Is it possible you're trying to rename "files that don't exist" (see point #3) into files that already exists (maybe your filename doesn't contain ' ' or maybe '~' gets ignored because of point #1). And when renaming, the docs do mention:

In the case that newPath already exists, it will be overwritten.

(https://nodejs.org/api/fs.html#fsrenameoldpath-newpath-callback)
Comment: what is a good special character to replace space with that works with all sub systems?
Comment: People usually use `_` to replace spaces.


8 - SQL error "String data, right truncated..." when creating/updating a node programmatically, but OK when inserting via the CLI. Why?

Question: When I attempt to programmatically update an event node, I get the error:

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'field_event_end_date_and_time_value'...

For most date fields. If I insert the record(s) with the same information into MySQL directly via the CLI, it updates/inserts correctly. Anyone have any idea what's going wrong here?
Full error from logs:

Drupal\Core\Entity\EntityStorageException: SQLSTATE[22001]: String
  data, right truncated: 1406 Data too long for column
  'field_event_end_date_and_time_value' at row 1: INSERT INTO
  {node__field_event_end_date_and_time} (entity_id, revision_id, bundle,
  delta, langcode, field_event_end_date_and_time_value) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4, :db_insert_placeholder_5); Array (
  [:db_insert_placeholder_0] => 7159 [:db_insert_placeholder_1] => 7750
  [:db_insert_placeholder_2] => events [:db_insert_placeholder_3] => 0
  [:db_insert_placeholder_4] => en [:db_insert_placeholder_5] =>
  2014-06-18CDT21:30:00 ) in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 770 of
  /var/www/acg/html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

My queries:
UPDATE node__field_event_end_date_and_time SET field_event_end_date_and_time_value = '2014-06-18CDT21:30:00' WHERE delta = 0 AND langcode = 'en' AND entity_i
d = 7159 AND deleted = 0;

and
INSERT INTO node__field_event_end_date_and_time (entity_id, revision_id, bundle, delta, langcode, field_event_end_date_and_time_value) VALUES(7159, 7750, '
events', 0, 'en', '2014-06-18CDT21:30:00');

work correctly through the CLI.
Output of show columns FROM node__field_event_end_date_and_time
+-------------------------------------+------------------+------+-----+---------+-------+
| Field                               | Type             | Null | Key | Default | Extra |
+-------------------------------------+------------------+------+-----+---------+-------+
| bundle                              | varchar(128)     | NO   | MUL |         |       |
| deleted                             | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id                           | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id                         | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode                            | varchar(32)      | NO   | PRI |         |       |
| delta                               | int(10) unsigned | NO   | PRI | NULL    |       |
| field_event_end_date_and_time_value | varchar(20)      | NO   | MUL | NULL    |       |
+-------------------------------------+------------------+------+-----+---------+-------+

Does anyone see it?
Answer: The CLI works because then you're not in strict mode and it just cuts the string off.
Your date format is wrong. It must be in the format defined by DATETIME_DATETIME_STORAGE_FORMAT
 and converted to the correct timezone DATETIME_STORAGE_TIMEZONE.
Comment: Thank you. That makes sense. I've selected this as the correct answer. Thanks for your help.


What is the smallest distance between a line segment and a cylinder?

Question: Given a cylinder at origin represented by its radius and length (no rotation to simplify the problem), what is its minimum distance to a point on a line segment?
So far I managed to create a function that calculates the distance between the cylinder and a point, then used it as optimization function to iterative numerical methods in order to find the minimum distance. Unfortunately such approach is too slow. I'm wondering if there is any way of solving this problem analytically.
Comment: Use Langrange multipler method. http://en.wikipedia.org/wiki/Lagrange_multiplier, it is more general method for optimizing problems.
Comment: A general reference for distance calculations: https://www.geometrictools.com/Source/Distance3D.html#LinearVolumetric
Answer: You can divide the line into three segments. The line is divided by the two planes of the bottom and top disks of the cylinder. See the image below (1) for example.

Each segment will find the minimum distance independently from each other, and only the minimum distance between all three segments will be chosen. To calculate the minimum distance of each segment, do:

First line segment (blue line): calculate the minimum distance between this segment and the bottom disk of the cylinder (I'm still using an iterative numerical method here using the distance between a point and a disk as objective function).
Second line segment (green line): project this line segment and the cylinder to the plane orthogonal to the main axis of the cylinder (as pointed by @Stefano). Find the point on this projected line that is closest to circle created by the cylinder projection.
Third segment (red line): same as the first segment, but now use the top disk.

Problem with this approach: Imagine you have a line that is really small, almost like a single point, direct below the top disk, inside the cylinder that never crosses to the top side. This approach will calculate the minimum distance as per the Second segment before, (distance circle and line), but its wrong because the minimum distance should be from this line segment to the top disk.
Answer: You can project the problem on a plane orthogonal to the cylinder's axis, so that the cylinder becomes a circle and the line becomes a... line. They you are back to the problem of the distance between a circle and a line.
Comment: It can get a bit more complicated when part of the line segment lies "beyond the end" of the cylinder. The nearest point may not be projected to the nearest point of the images of the line and cylinder.


Python Program to determine greater, lesser, equal

Question: I need to write a program that will tell me if the the first of two number is greater, lesser, or equal
def g_l_e (arg_one, arg_two) :
if (arg_one) > (arg_two):
    answer = print('greater')
if (arg_one) < (arg_two):
    answer = print('lesser')
if (arg_one) == (arg_two):
    answer = print('equal')
return (answer)

g_l_e(1, 2)
g_l_e(2, 1)
g_l_e(2, 2)

The answers come back:
lesser
greater
equal
but when I submit it for grading it says:
FAIL - incorrect output for g_l_e(1, 2)
expected ['lesser'] but got [None]
your function should have a 'return' satement
I do not understand why this could be happening. It says [None] for every output.
Comment: You are assigning a print statement to the answer variable. You need to assign the string to the answer variable and then return that.
Answer: print statements return type None. And you are assigning the result variable the return value of the print statements. What you want is the following:
def g_l_e (arg_one, arg_two) :
    if (arg_one) > (arg_two):
        answer = 'greater'
    if (arg_one) < (arg_two):
        answer = 'lesser'
    if (arg_one) == (arg_two):
        answer = 'equal'
    print(answer)
    return (answer)

g_l_e(1, 2)
g_l_e(2, 1)
g_l_e(2, 2)

Answer: If you try this you would realise that your function does not return anything
def g_l_e (arg_one, arg_two) :
  if (arg_one) > (arg_two):
      answer = print('greater')
  if (arg_one) < (arg_two):
      answer = print('lesser')
  if (arg_one) == (arg_two):
      answer = print('equal')
  return (answer)

answer = g_l_e(1, 2)
print(answer)

You have to replace the print() statements with actual strings.


How can I add C++ Source Files and Headers to a C# .Net project?

Question: I want to make use of the HIDAPI library for a home-brewed USB device. Rather than having to compile the VC++ project into its own .dll and reference it in the .Net project I have, I would prefer to just have the code present within the .Net project and be able to reference it directly.
The reason is I want to avoid having a .dll referencing another .dll, and instead just have a single .dll file.
I've done it in reverse, sort of, where I have used a C# class within a C++ program when I was doing some JNI stuff.
Is what I am trying to do here possible? Is there an idiots guide to using C++ in .Net projects somewhere?
Comment: you need to wrap it since .net is managed code and most c++ is unmanaged.
Comment: you could write it in c++/cli or do pinvokes.
Comment: There is facility to merge .NET dlls together: [ILMerge](http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx). But you can't  native and managed together.
Comment: Ahhh. Just found another one it's a dup of: http://stackoverflow.com/questions/1854290/combine-native-dll-and-assembly-into-a-single-dll
Answer:
"Is what I am trying to do here possible?"

No, it isn't possible this way. These sources can't be compiled within the same project type. You need to have a separate project for the c++/cli assembly, and refer to this one being imported by your c# project.
Comment: Also check out http://stackoverflow.com/questions/1933210/c-cli-why-should-i-use-it for more information.
Answer: Wait, there is a yes answer, but obviously it's completely evil:
How do I mix C# and C++ code in a single assembly?
If your C++ code is not compiled with /clr:safe (i.e. it is compiled with /clr or /clr:pure), do the following:
1) compile your C++ code into .obj files
2) compile your C# code into a .netmodule, using /AddModule to reference the C++ .obj files
3) link the C# netmodule directly with the C++ object files using the C++ linker to create a mixed language assembly
Also this: Linking native C++ into C# applications
Yeah, don't do that.
Comment: both dead links


How to configure an alias in nginx

Question: Im switching from apache to nginx and im not sure how i would do the following in nginx.
<VirtualHost *:80>
ServerName example.com
ProxyRequests On

Alias /faq /var/www/http
<Directory /var/www/http/>
    Options Indexes FollowSymLinks
    AllowOverride ALL
    Require all granted
</Directory>

ProxyPassMatch ^/faq !

ProxyPass        / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/

ErrorLog ${APACHE_LOG_DIR}/http.log
CustomLog ${APACHE_LOG_DIR}/http.log combined

i currently have this but i keep getting a 404 error
server {
listen 80;
server_name example.com;
client_max_body_size 30M;

location / {
    proxy_pass  http://localhost:8080/;
    include /etc/nginx/proxy_params;
}

location /faq/ {
    proxy_redirect off;
    alias /var/www/http;
    index index.php;
    if (!-e $request_filename) {
        rewrite ^/(.*)$ /index.php?q=$1 last;
    }

}

location ~ /faq\.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
#   # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
#   # With php5-cgi alone:
#   fastcgi_pass 127.0.0.1:9000;
#   # With php5-fpm:
    fastcgi_pass unix:/var/run/php7.0-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    }

}
Answer: instead of alias /var/www/http; use root /var/www/http;
Also instead of if for redirection to index.php you can use:
try_files $uri $uri/ /index.php?$args;

How to configure an alias in nginx


How to change application theme in Eclipse

Question: I want to change the background of Date Picker from white to black, I think it can be done by changing my app theme to holo dark.
Currently it is:
 And Iwant to change it  to holo black
So, currently my styles.xml in values folder is
<resources>

</resources>

values-v11 styles.xml
<resources>

</resources>

values-v14 styles.xml
<resources>

</resources>

Mainifest.xml
<application
   .....
   android:theme="@style/AppTheme" >
   .......
</application>

I am using appcompat_v7, so what should I modify my styles.xml use Holo Light and Dark Date Picker?
Comment: Are you using HoloEverywhere? If you are not using it, please remove the tag.
Comment: Here you can find a clue to solve your problem: http://stackoverflow.com/q/18839895
Comment: a clue is always frustrating & torment, until & unless it solves ur problem
Comment: what about changing the style of just that screen in the visual layout editor ?
Comment: @jesses.co.tt This is possible if we use custom dialog box but making date picker custom  will be a big pain in ass !
Answer: Setting Theme.AppCompat as a parent to  themes when the app uses appcompat_v7 solved it !
Theme.AppCompat is visually the same as Theme.Holo (dark).
For more information see the Android documentation ActionBar for more information !
Answer: OK so ALL instances of..
    "Theme.AppCompat.Light"

...need to be changed to...
    "Theme.AppCompat"

"Theme.AppCompat" is the appcompatversion of "Theme.Holo" - the dark version
You cannot use "Theme.Holo" because you are using the appcompat library. They are incompatible. Follow this and it will work!
Answer: SOLUTION IS:: android:Theme.Holo

Copy this Code and paste it in your styles.xml in the values folder
styles.xml in values folder is
<resources>

</resources>

values-v11 styles.xml
<resources>

</resources>

values-v14 styles.xml
<resources>

</resources>

Mainifest.xml
<application
   .....
   android:theme="@style/AppTheme" >
   .......
</application>

 - HAVE A LOOK AT --- HOLO_EVERYWHERE - PROJECT - CLICK -HERE
 - HAVE A LOOK AT --- DEVELOPER_SITE - CLICK - HERE
Comment: Thanks, but the app is crashing by `java.lang.RuntimeException: Unable to start activity ComponentInfo{com...}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.`
Comment: @VivekWarde .... You have to check for other folders, that contain styles files as well, that could possibly override your styles. ... did you do that ?
Comment: wht do u mean by other folders?, BTW the styles.xml are in the folders which I have specified & I have modified all the code according specified by u !
Comment: Sorry, Your answer went me totally wrong, see my answer !
Comment: I was not aware you were using `appcompat_v7` .... My answer was for support `v4` ... and i forgot to ask it ... Glad you were able to resolve it ! Cheers !


How to use separate databases for Drupal tables?

Question: So far, what I've read is you can config multisites to use different tables and share any table with other sites in that multisite config.
My question is if it is possible to get this config:

Database A has Site A's users and Site A content
Database B will only have Site B's content
Site B will use users table in database A.
Site B will have its content in database B.

It may not be a multisite question after all but rather, in short...
Is it possible for a Drupal site to use two different databases for some of its tables? How?
Answer: In the settings.php file used for the site, you can specific a different prefix for each database table.
<code>  $databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'databasename',
    'username' => 'username',
    'password' => 'password',
    'host' => 'localhost',
    'prefix' => array(
      'default'   => 'main_',
      'users'     => 'shared_',
      'sessions'  => 'shared_',
      'role'      => 'shared_',
      'authmap'   => 'shared_',
    ),
    'collation' => 'utf8_general_ci',
  );
</code>
You can also refer different databases, or schema, using code similar to the following one.
<code>  $databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'databasename',
    'username' => 'username',
    'password' => 'password',
    'host' => 'localhost',
    'prefix' => array(
      'default'   => 'main.',
      'users'     => 'shared.',
      'sessions'  => 'shared.',
      'role'      => 'shared.',
      'authmap'   => 'shared.',
    ),
    'collation' => 'utf8_general_ci',
  );
</code>
The difference between the last snippet, and the previous one is that the last character used for the prefixes is the dot, not the underscore. That causes the database engine to select a different database/schema, instead of the currently set one.
To be clearer, in the code I shown the database engine is still MySQL running on localhost; what changes is that for the users table, Drupal will use the shared database instead of the databasename one.
As far as I know, this is valid for Drupal 7, or higher. The same trick is not reported in the comments present in the default.settings.php file that comes with Drupal 6.
Reference
The comments shown in the default.settings.php file.
Comment: Yes! Thank you! Should've looked more in the sample. This is, of course, with the assumption that the username used has sufficient privileges on all databases being referenced.
Comment: In your prefix array, you reference main. and shared. How does Drupal know what databases this is talking about? How does it know what server to find them on?
Comment: @BeardedGeek In the code I am showing, the database engine is still MYSQL, and the host is localhost. What changes is that for the users table, Drupal will not look at the _databasename_ database, but at the _shared_ database.
Comment: @radj That is correct: Since username and password are the same for both the databases, the user accounts need to have the minimum necessary permissions that would allow Drupal to work with those credentials.


How to fit a discrete distribution to count data?

Question: I have the following histogram of count data. And I would like to fit a discrete distribution to it. I am not sure how I should go about this.
Should I first superimpose a discrete distribution, say Negative Binomial distribution, on the histogram so that I would obtain the parameters of the discrete distribution and then run a Kolmogorov–Smirnov test to check the p-values?
I am not sure if this method is correct or not.
Is there a general method to tackle a problem like this?
This is a frequency table of the count data. In my problem, I am only focusing on non-zero counts.
  Counts:     1    2    3    4    5    6    7    9   10
 Frequency: 3875 2454  921  192   37   11    1    1    2

UPDATE: I would like to ask: I used the fitdistr function in R to obtain the parameters for fitting the data.
fitdistr(abc[abc != 0], "Poisson")
     lambda
  1.68147852
 (0.01497921)

I then plot the probability mass function of Poisson distribution on top of the histogram.
However, it seems like the Poisson distribution fails to model the count data. Is there anything I can do?
Comment: A general method is to use maximum likelihood to fit a candidate distribution. What you mean by superimposing a distribution to obtain the parameters isn't clear, but if you mean guessing parameter values until you get a good fit that's a lousy method. Kolmogorov-Smirnov isn't useful here. You need decent software that gives you inferential results, so you need to indicate your software of choice so that people using that can try to help you. Your histogram isn't clear, but if there gaps then no distribution is likely to fit well.
Comment: While using a KS *test* in that manner is a lousy method (and in any case the KS test is not for discrete distributions), it would be possible to estimate parameters by minimizing the KS statistic over all possible parameter values; but if you're going that way (optimizing some goodness of fit), minimum chi-square would be the more typical approach. As Nick Cox suggests ML would be the obvious thing to do, almost certainly more efficient, easier to get standard errors out of, and more readily accepted by others. (There are other possibilities, like method of moments, but ML is the main thing.)
Comment: I am using R. When you say estimating MLE, is there any algorithms that you will recommend for the job? And after finding the ML, what should I do next ?
Comment: I'd start here `?MASS::fitdistr`, since it's already in your R distribution (see the final example at the bottom; see rnegbin for more information about that parameterization of the Negative Binomial). .... "*And after finding the ML, what should I do next?*" -- well at that point you have parameter estimates and standard errors. Beyond that, what do you want to achieve? -- I can't guess.
Comment: It occurs to me that you may have been trying to ask 'how do I assess the fit of my model?'. If that's the case, could you update your question to reflect that?
Comment: Response to UPDATE: I've already addressed your problem with omitting zeros. If you fit a Poisson without zeros, the routine still predicts that you will get a fraction of zeros that is mean * exp(-mean), in your case about .313. The function does _not_ adjust for your subsetting on positive counts. You asked a question that makes no sense statistically.
Answer: Methods of fitting discrete distributions
There seem to be three main methods* used to estimate the parameters of discrete distributions.

Maximum Likelihood
This finds the parameter values that give the best chance of supplying your sample (given the other assumptions, like independence, constant parameters, etc)

Method of moments
This finds the parameter values that make the first few population moments match your sample moments. It's often fairly easy to do, and in many cases yields fairly reasonable estimators. It's also sometimes used to supply starting values to ML routines.

Minimum chi-square
This minimizes the chi-square goodness of fit statistic over the discrete distribution, though sometimes with larger data sets, the end-categories might be combined for convenience. It often works fairly well, and it even arguably has some advantages over ML in particular situations, but generally it must be iterated to convergence, in which case most people tend to prefer ML.

The first two methods are also used for continuous distributions; the third is usually not used in that case.
These by no means comprise an exhaustive list, and it would be quite possible to estimate parameters by minimizing the KS-statistic for example – and even (if you adjust for the discreteness), to get a joint consonance region from it, if you were so inclined.
Since you're working in R, ML estimation is quite easy to achieve for the negative binomial. If your sample were in x, it's as simple as  library(MASS);fitdistr (x,"negative binomial"):
> library(MASS)
> x <- rnegbin(100,7,3)
> fitdistr (x,"negative binomial")
     size         mu
  3.6200839   6.3701156
 (0.8033929) (0.4192836)

Those are the parameter estimates and their (asymptotic) standard errors.
In the case of the Poisson distribution, MLE and MoM both estimate the Poisson parameter at the sample mean.
If you'd like to see examples, you should post some actual counts. Note that your histogram has been done with bins chosen so that the 0 and 1 categories are combined and we don't have the raw counts.
As near as I can guess, your data are roughly as follows:
    Count:  0&1   2   3   4   5   6  >6
Frequency:  311 197  74  15   3   1   0

But the big numbers will be uncertain (it depends heavily on how accurately the low-counts are represented by the pixel-counts of their bar-heights) and it could be some multiple of those numbers, like twice those numbers (the raw counts affect the standard errors, so it matters whether they're about those values or twice as big)
The combining of the first two groups makes it a little bit awkward (it's possible to do, but less straightforward if you combine some categories. A lot of information is in those first two groups so it's best not to just let the default histogram lump them).

* Other methods of fitting discrete distributions are possible of course (one might match quantiles or minimise other goodness of fit statistics for example). The ones I mention appear to be the most common.
Answer: In an edit, you gave some data, and added a new question:
"This is a frequency table of the count data. In my problem, I am only focusing on non-zero counts.
   Counts:     1    2    3    4    5    6    7    9   10
Frequency:  3875 2454  921  192   37   11    1    1    2

Can someone give me an example of how you would carry out the chi-squared goodness of fit test here?"
This leads to further comments:

Having zeros but wanting to ignore them can make sense, but generally statistical and subject-matter people would want to see a good reason for why.
If you choose to ignore zeros, you are placing yourself in difficult territory, as you can't just fire up routines for e.g. Poisson or negative binomial if you leave out the zeros. Well, you can, but the answers would be wrong. You need special purpose functions or commands for distributions such as the zero-truncated Poisson or zero-truncated negative binomial. That's challenging stuff and needs dedicated reading to be clear on what you are doing.
Asking how to do a chi-square test suggests to me that you have not really understood what I said very briefly and @Glen_b said in much more detail (and, to my mind, very clearly). Splitting that in two:

There can be no chi-square test without expected frequencies and there can be no expected frequencies without parameter estimates. It may be that you are most familiar with chi-square test routines in which independence of rows and columns in a two-way table is tested. Although that is the chi-square test most met in introductory courses, it is actually very unusual among chi-square tests in general in that the usual software in effect does the parameter estimation for you and thereby gets the expected frequencies. Beyond that, in most more complicated problems, such as yours, you have to get the parameter estimates first.
A chi-square test isn't wrong, but if you estimate parameters by maximum likelihood it's irrelevant as the fitting routine gives you estimates and standard errors and allows tests in their wake. @Glen_b gave an example already in his answer.

A side-issue is that it would be clearer to tweak your histograms to respect the discreteness of the variable and show probabilities, not densities. The apparent gaps are just artefacts of default bin choice not respecting the discreteness of the variable.
UPDATE: The supplementary question about a chi-square test has now been deleted. For the moment I am letting #3 above stand, in case someone else follows the same path of wanting a chi-square test.
Comment: I have to ignore the zeros, because I am trying to model active counts. Counts  = 0 is referred to as inactive counts.
Comment: That's a substantive choice. Note that in many fields there are so-called two part models, in which you model (in your terms) active versus inactive and then how active.
Comment: I tried to tweak the histograms by doing "plot(table(abc), type = "h")". But, I am not sure how can I get it to show probabilities
Comment: I don't use R, but you can get advice on that. You might need to ask separately.


Changing Guitar Tuning

Question: I learned some Guitar songs in default tuning.
Now i discovered that there are many other tuning available in which people play awesome guitar, as it's easy to do tapping ,play percussive style guitar on these.
So my question if i play the same song (learned in default tuning) on other tuning will it work ?
Comment: You will have to learn a new fingering for the same song, but once you do then it should work.
Answer: Sure - but in general, you have to learn a whole bunch of new chord shapes.
If you use Dropped D (where the E string is down a tone to D and everything else stays the same) than you can of course play everything the same on the top 5 strings.
If you get more adventurous and try say DADGAD (check out Pierre Bensusan!) then you really need to learn new chords shapes. Everything has changed.
I highly encourage it though. Alternate tunings are fun.
Comment: Plus, some songs get easier when played in the alternate tunings.  "Cinnamon Girl" (Neil Young), "That's the Way" (Led Zeppelin) and "Fearless" (Pink Floyd) come to mind.
Comment: There are plenty of open and altered tunings that actually require fewer *fingers* to play.  Blues and country especially. "Midnight Special" springs to mind. Even lifting the bass strings up an octave for rhythm, skiffle.  Any decent reference will cover examples.
Comment: yes it depends a lot on the song. In many open tunings things get more modal, more chords where lots of roots and fifths ring out a lot. I love that sound, but that's also why I suggest Bensusan because he shows that you can still play more colourful chords in those modal sounding open tunings. But of course, as always it depends what you want to do.
Answer: Sometimes songs are written with the help of different tunings. Put them into standard, and they may well be impossible to play. And they wouldn't sound so authentic. The use of open strings in some tunings is their benchmark. That and particular voicings which would be tricky in standard tuning.
So, basically, yes, a lot of stuff would work either way, but new fingerings would make the job onerous, and some open string sounds would disappear. Experiment with different tunings - maybe invent your own!
Answer: Two options for you

Proceed with what you're thinking... even though it's not the typical use case for alternate tuning
Learn a song that's written to be played on alternate tuning. Typical use cases for alternate tuning are:

it's easier to play that way
sounds better played that way

Example songs that uses alternate tuning:
Outshined by Soundgarden - Drop D - DADGBE
Even Flow by Pearl Jam - Open D tuning - DADF#AD
Iris by Googoo dolls - BDDDDD
She Talks to Angels by The Black Crows - EBEG#BE

Changing Guitar Tuning


Calculus Integration Based Proof that the Volume of a Parallelepiped spanned by $\{v_1, \ldots, v_n\}$ is $\text{det}(v_1, \ldots, v_n)$?

Question: NOTE: This question is mostly setup to give context for the proof I am working on and how I want the proof to be. The only technical, and quite modest, question I have appears in the paragraph near the bottom of this post.
Let $v_1, \ldots, v_N \in \mathbb{R}^N$. A parallelepiped $P(v_1, \ldots, v_N) \subset \mathbb{R}^N$ is the set
$$
P(v_1, \ldots, v_N) = \left\{\sum_{i=1}^N t_iv_i \mid  0 \le t_i \le 1 \text{ for $i$ from 1 to $N$.}\right\}.
$$
It is well known that the volume of this set is given by
$$
|\text{det}(v_1, \ldots, v_N).|
$$
Let $1_P$ be the indicator function on the parallelepiped set defined above. I would like to define the volume of the parallelepiped as
$$
\text{vol}(P) = \text{vol}(P(v_1, \ldots v_N)) = \int_{\mathbb{R}^N}1_P dV.
$$
Let $\{e_1,\ldots, e_N\}$ be an orthonormal basis for $\mathbb{R}^N$. I would like to define the determinant as
$$
\text{det}(v_1, \ldots, v_N) = \sum_{\sigma \in S_N} \text{sgn}(\sigma) v_{1, \sigma(1)}\ldots v_{N,\sigma(N)}
$$
where $S_N$ is the symmetric group of size $N$ and $v_{i, j} = e_j \cdot v_i$ is the $j^{\text{th}}$ component of $v_i$.
I would like a proof that
$$
\text{vol}(P) = |\text{det}(v_1, \ldots, v_N)|
$$
using the definitions I've provided above for $\text{vol}$ and $\text{det}$.
I expect the proof to use the following facts.
(1) Let $Q = P(e_1, \ldots, e_N)$ denote the unit cube.  I'm comfortable to take it as proven that
$$
\text{vol}(Q) = |\text{det}(e_1, \ldots, e_N)| = 1
$$
(2) I'm also comfortable to take it as proven that for reasonable set $A \subset \mathbb{R}^N$ and linear transformation $T$ that $\text{vol}(TA) = \text{vol}(TQ)\text{vol}(A)$ because this can seemingly be proven from the appropriate manipulation of the partitions used in the definition of the Reimann or Darboux integral.
(3) I'm also comfortable to take it as proven there is an invertible transformation $T$ such that $P(v_1, \ldots, v_n) = T Q$
(4) I'm comfortable to take it as proven that any invertible transformation $T$ can be written as a product of elementary matrices $T = E_1\ldots E_k$.
(5) I'm comfortable to take it as proven that $\text{det}(T_1 \ldots T_k) = \text{det}(T_1)\ldots \text{det}(T_k)$.
I think all that remains to be proven is that $\text{vol}(EQ) = |\text{det}(E)|$ for all the elementary matrices. For the elementary matrices that either scale a single axis or swap two axes I am convinced of this.
All that remains to be proven is that the above statement holds for the elementary matrices that add a multiple of one axis to another. In parallelepiped language I am asking for a proof that shearing a cube along any axis does not change its volume.
Let $E^{\alpha \beta}(c)$ be the matrix with entries $E^{\alpha\beta}_{ij}(c)$ defined by
$$
E^{\alpha \beta}_{ij}(c) = \delta_{ij} + \delta_{i\alpha} \delta_{j\beta} c
$$
Can someone prove (or provide a link to a proof) that
$$
\text{vol}(E^{\alpha \beta}(c) Q) = 1
$$
Furthermore, I would expect this proof to involve an explicit calculus definite integration over coordinates. It is already intuitively clear to me that the "base" of parallelepiped has hyper-area of 1 and the "altitude" of the parallelepiped is 1, therefore the volume is also 1, but I would like to see a more rigorous proof of this fact. I guess the challenge for me here is getting the bounds on the definite integral right and carrying out the integration over the bounds.
Alternatively, if there is a proof which is as rigorous, but more elegant, taking a different approach, this would also suffice.
Comment: Integrating the indicator of a function always yields a non-negative number. So, your $\text{vol}(P)$ is still a non-negative quantity. If you truly want to make it signed, you must define $\text{signed vol}(P):= \text{sign}(\det (v_1,\dots, v_N))\int_{\Bbb{R}^N}\mathbf{1}_P\,dV$.... which is clearly annoying. So, just do the standard thing of putting absolute values on the determinant.
Comment: You're missing absolute value signs for the determinant.
Comment: @peek-a-boo Thanks. I'll let $\text{vol}(P)$ denote the signed volume of $P$ as opposed to the positive volume.
Comment: Ah, fair point that my definition of volume is not signed. Ok I'll change it.
Answer: We can actually make further reductions. Suppose $T:\Bbb{R}^n\to\Bbb{R}^n$ is the linear transformation
\begin{align}
T(x_1,\dots, x_n)&=(x_1+x_2,x_2,\cdots, x_n)
\end{align}
In terms of matrices, we're taking the second row of the identity matrix and adding it to the first row. We only need to restrict attention to this particular one, because we can perform row swaps to ensure we're only looking at rows 1 and 2, and then perform a scalar multiplication to ensure we only deal with $c=1$. Now,
\begin{align}
T(Q)&=\{\xi\in\Bbb{R}^n\,:\, \xi_2\leq \xi_1\leq \xi_2+1\,\quad\text{and}\quad \xi_2,\dots, \xi_n\in [0,1]\}
\end{align}
(i.e just put $\xi_1=x_1+x_2$, and $\xi_j=x_j$ for $j\geq 2$, and manipulate the inequalities $x_i\in [0,1]$ for all $i$ in terms of $\xi$). Now, we have
\begin{align}
\text{vol}(T(Q))&=\int_{T(Q)}1\,dV\\
&=\int_{[0,1]^{n-2}}\int_0^1\int_{\xi_2}^{\xi_2+1}1\,d\xi_1\,d\xi_2\, d(\xi_3,\dots, \xi_n)\tag{by Fubini}\\
&=\int_0^1(\xi_2+1-\xi_2)\,d\xi_2\\
&=1.
\end{align}
Here, it's clear that the integral over the last $n-2$ coordinates is trivially $1$ (this is just the $(n-2)$-dimensional volume of the cube $[0,1]^{n-2}$).
Comment: Thank you for this response and your comments helping making improvements to the OP. This answer takes the same approach as the other and is equally as good and introduces the further reduction, but unfortunately I can only award the answer points to one answer. I'm awarding it to the other one mostly because it came in a few minutes earlier (even though you were engaging with the question first in the comments).
Comment: @Jagerber48 sure, no worries (I'm not concerned about the points anyway). I'm glad this was helpful.
Answer: This is just Cavalieri's principle in action, but I get it that you want to write down the integral. So, $$E^{\alpha\beta}(c)Q = \{x\in\Bbb R^N: 0\le x_i\le 1, i\ne\alpha,\  cx_\beta\le x_\alpha\le cx_\beta + 1\}.$$
By Fubini's Theorem, do the $\alpha\beta$ integral and then the rest over the usual cube in $\Bbb R^{N-2}$. Thus, the volume is
$$\int_0^1\int_{cx_\beta}^{cx_\beta+1}dx_\alpha\,dx_\beta = \int_0^1 x_\alpha\Big|_{cx_\beta}^{cx_\beta+1}\,dx_\beta = \int_0^1 1\,dx_\beta = 1,$$
of course, as required. (Drawing the two-dimensional parallelogram is, of course, helpful, but not necessary.)
Comment: thank you very much for this answer, and especially for keeping your notation consistent with what I've included in the OP. One remaining question that feels a little dense, but some words on it would help me. Based on my definition of $P$ I would say that $E^{\alpha \beta}(c) Q = \{t_1e_1 +\ldots + t_i(e_i+ce_j) + \ldots + t_N e_N | 0 \le t_1, \ldots t_N \le 1\}$. Could you say some words or give a proof as to why this is equal to the set you've given for $E^{\alpha \beta}(c) Q$?
Comment: I guess I feel confident I could prove this myself by proving the two sets are subsets of each other with little difficulty.
Comment: No, that's not right. First of all, you obviously need $\alpha,\beta$ where you have $i,j$. But remember that it's the $\beta^\text{th}$ basis vector that changes, and so you should have $t_\beta(e_\beta+ce_\alpha)$, shouldn't you? As I suggested, you should draw the 2-dimensional parallelogram to see what I wrote. You can do it just algebraically by solving for $x_\alpha$ in terms of $x_\beta$ from your (corrected) formulation.
Comment: Yes, I think you're correction is right, thanks.


Countable partition in atoms

Question: Let $\mu: \Sigma \to [0, \infty)$ a measure over $\Omega$. We say a set $A \in \Sigma$ is an atom if for all $B \in \Sigma$ with $B \subset A$, $\mu(B)=\mu(A)$ or $\mu(B)=0$. We say that $\mu$ is atomic if every set $A \in \Sigma$ with positive measure contains an atom with positive measure.
So, I'm trying to prove that if $\mu$ is atomic, there exists $\{ A_n\}_{n \in \mathbb{N}}$ pairwise disjoint atoms such that its union covers $\Omega$.
I can build a sequence this way:
Let $A \in \Sigma$ be a set with positive measure. It contains an atom $A_1$.Then I pick up $\Omega \setminus A_1$. Again, it contains an atom $A_2$ which is disjoint from $A_1$.
However, I do not know how to continue. I would appreciate any help.
Comment: Choose at each step an atom with the biggest possible measure, which exists by finitness of the measure. This makes your algorithm stop in countably many steps. You can also have a look at [transfinite induction](https://en.wikipedia.org/wiki/Transfinite_induction) (which is not really necessary here but can be useful in similar problems, for example when there isn't a canonical choice at each step)
Comment: @Ramiro If the total measure is not finite it could be that there are atoms with arbitrarily large mass, for instance $\mu=\sum_n n\delta_n$ on the real line.
Comment: @del Yes, you are right. And if the measure is NOT finite, even if the atoms have bounded mass,  the result  may not hold.
Comment: @Del How is it that if my space is compact and the measure is finite and regular I can put $\mu=\sum_n n\delta_n$ for a certain sequence of elements?
Comment: @Whoknows I'm not sure I understand the question...I was replying to a former comment, to say that without the finiteness assumption on the measure there may not be a biggest atom
Comment: @Del As I have just commented below, I have been thinking about why it is possible to pick the biggest atom up, but I do not see it. Any hint?
Comment: @Whoknows Prove that $\mu$ is additive on atoms with different masses (no matter if they intersect or not). Then conclude using the finiteness of $\mu$ that there is a maximum for the masses of the atoms.
Answer: For finite measures:
Proof: If $\mu(\Omega) = 0$ the result is trivial, because $\Omega$ itself is an atom. Assume $\mu(\Omega) > 0$. Since $\mu$ is atomic, take $B_0=\Omega$ and define by induction, for all $n\in \mathbb{N}$, if $\mu(B_n)>0$ then let $A_n \subseteq B_n$ be an atom with the largest possible measure among the atoms contained in $B_n$ (such choice of $A_n $ is always possible because the measure is finite) and let $B_{n+1}=B_n\setminus A_n$.
One of two things may happen:

For some $n_0\in  \mathbb{N}$, $\mu(B_{n_0+1})=0$ and in this case, $B_{n_0+1}$ is an atom, $A_0, \dots, A_{n_0}, B_{n_0+1}$ are disjoint atoms  and we have
$$\Omega = A_0 \cup \dots \cup A_{n_0} \cup B_{n_0+1}$$
which proves the result (for this case).
For all $n\in  \mathbb{N}$, $\mu(B_{n})>0$. In this case we have an infinite sequence $\{A_n\}_{n\in  \mathbb{N}}$ of disjoint atoms of positive measures. Let
$$ A= \bigcup_{n\in  \mathbb{N}} A_n$$.

Claim: $\mu(\Omega \setminus A)=0$
Proof of the claim: if $\mu(\Omega \setminus A)>0$ the there is an atom $E\subseteq \Omega \setminus A$ such that $\mu(E)>0$. By our choice of $A_n$ at each step, we have that, for all $n\in  \mathbb{N}$ $\mu(A_n) \geqslant \mu(E)$. So $$ \mu(A)=\sum_{n\in  \mathbb{N}}\mu(A_n) =\infty$$
Contradiction, since the measure is finite.
So we proved  $\mu(\Omega \setminus A)=0$. So we have that $\Omega \setminus A$ is (trivially) an atom and we have
$$\Omega =  \left ( \bigcup_{n\in  \mathbb{N}} A_n \right ) \cup (\Omega \setminus A)$$
So $\Omega$ is covered by a countable collection of atoms and this proves the result for this case and completes the proof.
Remark: if the measure is not finite, this result may not hold.
Consider $(\mathbb{R}, P(\mathbb{R}), \mu)$ where $\mu$ is the counting measure. Every singleton is an atom of positive measure. Any set with positive measure is not empty, so it contains a singleton, which means, it contains an atom of positive measure. So $\mu$ is atomic.
Note that the only atoms are the singletons (and the empty set), and clearly $\mathbb{R}$ is not a countable union of singletons.
Remark 2: Let us prove that, since $\mu$ is finite, the for any set $A$, if $A$ contain an atom, then there is an atom $E\subseteq A$ such that for any atom $F \subseteq A$, $\mu(F)\leqslant \mu(E)$.
Suppose  $A$ contain an atom. Let us prove the result by contradiction. Suppose that for all an atom $E\subseteq A$, there is an atom $F \subseteq A$, $\mu(F)> \mu(E)$.
Let $E_0\subseteq A$ is an atom. Then there is sequence of atoms $E_n\subseteq A$ such that for all $n\in \mathbb{N}$ $\mu(E_n) < \mu(E_{n+1})$.
Given any $i<j$, since $E_j$ is an atom and $\mu(E_i\cap E_j)\leqslant\mu(E_i) < \mu(E_j)$, we have that  $\mu(E_i\cap E_j)=0$. So we have
$$\mu \left ( \bigcup_{n\in  \mathbb{N}}E_n\right)= \sum_{n\in  \mathbb{N}}\mu(E_n)=+\infty$$
Contradiction, because the measure is finite.
So we proved that there is an atom $E\subseteq A$ such that for any atom $F \subseteq A$, $\mu(F)\leqslant \mu(E)$.
Comment: @Whoknows You are right. For finite measures the result holds. I have updated my answer to show a detailed proof of such case.
Comment: @Whoknows I updated my answer to include Remark 2. I hope this helps.
Comment: But that is not a finite measure. I'm working with finite ones.
Comment: I have been thinking about the fact that I can always choose the atom with the largest meassure among... However, I have not managed to prove it. Any help would be appreciated.
Answer: Hints. First show that the set of atoms is countable. The show it must be (essentially) the whole space.
Comment: But if we take $(\mathbb{R}, \mathcal{P(\mathbb{R})},\mu)$, where $\mu(A)=1$ if $0 \in A$ and $\mu(A)=0$ otherwise, every set $A \subset \mathbb{R}$ is an atom. Therefore, the set of atoms does not have to be countable.
Comment: I think you're right, and my method may not work. I have to read the question more carefully, but don't have time now. I may leave this false start up for a while, delete it later.

Countable partition in atoms


How to get 5 points of an ellipse which is internaly tangent to two congruent intersecting circles.

Question: Let two circles $C$ and $C'$ intersecting at points $A$, $B$. I would like to construct an ellipse passing through $A$ and $B$ using the $5$ points construction of GeoGebra (foci unknown). The problem is that the ellipse must have two points of tangency ($E$ with $C$ and $F$ with $C'$).
Do you know a method that uses inversion ? Is there a way to impose this tangency ?
Many thanks to any hint/help.
Comment: To be clear: should the ellipse have one tangency for each circle, or should the ellipse be have two points of tangency for each circle? Also, a diagram of what an example would look like would help.
Comment: The ellipse won't be unique. Do you want any ellipse satisfying that? Or do you have another condition in mind?
Comment: Semiclassical: one tangency for each circle.
Comment: Jjagmath: any ellipse should fit.
Comment: Semi classical: you're right. I edited my post with a picture
Comment: It's a good diagram, but you may want to modify the text of the problem to match. (Circles $C,C'$, tangent to the ellipse at points $E,F$ respectively.)
Comment: To _approximate_ such an ellipse with Geogebra isn't too bad: Pick two points $E,E'$ on $C$ and a point $F$ on $C'$, then construct an ellipse passing through $ABEE'F$. Now move point $E'$ so it coincides with $E$ to create the first tangency, then move $F$ until it's also a point of tangency. (Note that this depends on the choice of $E$ and hence is not unique.)
Comment: Yes but I'm looking for a way to designate the five points to GeoGebra and then, he draws me the ellipse passing through them.
Comment: One thing to notice: tangents at points $E$ and $F$ should be parallel !
Comment: If the tangents at E and F are parallel, and the circles are congruent, then all you have is a point A and E and the tangent at E, the other information is redundant, it does not add anything.
Comment: I doubt there is a solution using inversion : in the best case, the inverse of an ellipse is a limaçon, not a very simple curve...
Comment: Is anything wrong with my construction? I uploaded it to GeoGebra for you to understand it better: https://www.geogebra.org/m/dss3bjng
Answer: I'm assuming the circles to be congruent, otherwise the problem has no solution, in general. Point $E$ can then be chosen at will, while $F$ is the reflection of $E$ about the midpoint $S$ of $AB$, which is also the center of the ellipse.
Draw the line $t$ tangent to the circle at $E$, then draw through $S$ a line $r$ parallel to $t$ and call $M$, $N$ the (unknown) intersections between $r$ and the ellipse. $EF$ and $MN$ are conjugate diameters.
Draw a point $P$ on $EF$ such that $AP\parallel r$. By the properties of conjugate diameters we have then:
$$
{AP^2\over SM^2}+{SP^2\over SF^2}=1.
$$
From that you can compute $SM$:
$$
SM={AP\over\sqrt{1-SP^2/SF^2}}
$$
and construct point $M$ on line $r$.
Comment: {+1] Once more, very well done. It would be interesting to study the arc on the upper circle where $E$ can be chosen in order the tangency condition can be fulfilled (of course it would be necessary for that to know ratio $d/r$ where $d$ is the distance between the centers and $r$ the common radius).
Comment: @JeanMarie I'm not sure I understand what you mean. Point $E$ can be chosen anywhere on the upper circle.
Comment: Ah is it so ? Whatever the ratio $d/r$ ? How can we be sure of that ?
Comment: @JeanMarie Why do you think the construction could fail for some choice of $E$? The properties of conjugate diameters ensure that the parallel to $MN$ through $E$ is tangent to the ellipse.
Comment: You are right...
Comment: @JeanMarie I uploaded the construction to GeoGebra: https://www.geogebra.org/m/dss3bjng
Comment: Thank you : indeed nothing prevents $E$ to be anywhere on the outer arc $AB$...
Comment: Thank you for those who answered. I was helped for the following partial solution that gives the two points of tangency with circles $C'$ and $C$. But it doesn't work with GeoGebra because it still misses the 5th point. Choose any point F on the circle C'. Then draw the tangent at F to  C'. Draw the diameter (EE') (of the second circle C) that is orthogonal to the tangent at F to C'. Tangents to C at E and E' are parallel with tangent to C' at F. Lines (FE) and (FE') are passing through the homothetic centers of circles C and C'. The ellipse is then tangent to C at E and to C' at F.
Comment: Your analytical solutions are interesting but I was looking for a more synthetic solution using geometric transformations stored in the GeoGebra menu. I don't think there is any !
Comment: @3809525720 My solution is not "analytical": the formula for $SM$ can be easily turned into a geometric construction, if that is what you want. And the other equation was introduced by Apollonius of Perga in 3rd century BC.
Comment: @3809525720 On the other hand, to find the fifth point by using only a geometrical transformation is clearly impossible, as several people pointed out in the comments.
Answer: Assuming the two circles are congruent, and that the tangents at $E$ and $F$ are parallel, then from symmetry, we know that the center of the ellipse is at the midpoint of $A$ and $B$.  Let this point be $M_{AB}$, i.e.
$ M_{AB} = \dfrac{1}{2} (A + B ) = (x_1, y_1) $
In addition to the center $M_{AB}$ we know that point $A$ is on the ellipse.  And we also have point $E$, and finally we know the slope of the tangent at point $E$.  The equation of the ellipse satisfying these conditions can be derived from the equation of an ellipse centered at $M_{AB}$.
$ (r - M_{AB})^T Q (r - M_{AB} ) = 1 $
where $ r = [x, y]^T $ and $Q = \begin{bmatrix} a && b \\ b && c \end{bmatrix}$
Expanding,
$ a x^2 + 2 b x y + c y^2 - 2 a x x_1 - 2 b ( x y_1 + y x_1) -2 c y y_1 + a x_1^2 + 2 b x_1 y_1 + c y_1^2 -1 = 0 $
Which is nice and linear in the $3$ unknowns: $a,b$, and $c$.
Using the coordinates of $A$ and $E$ gives two independent equations in the three unknowns.
Next, differentiate the above equation implicitly with respect to x, this will give
$ 2 a x + 2 b (x y' + y ) + 2 c y y' - 2 a x_1 - 2 b (y_1 + y' x_1) -2 c y' y_1 = 0 $
Substitute point $E$ and the slope at point $E$ into this equation, which provides the third independent equation.
Solve the system of $3$ equations in the $3$ unknowns, and this gives the values of $a,b$ and $c$.
Having obtained $a,b,c$, you now have the equation of the ellipse, which you can feed to Geogebra to obtain a plot.


How do I get rid of the node title on a specific view mode?

Question: I'm using Drupal 7 with Omega subtheme and Display Suite module.
I have a content type and the nodes are displayed as default (Full Content). But I have two or three nodes of this content type which must be displayed in slightly different way (just a few fields hidden, some others perhaps).
So using Display Suite I've created a new view mode for these specific nodes and on the content edit page I've selected new view mode rather than Default.
Now the problem with this new mode is that node's title is rendered twice, once as the page title and second as the node title. This is different from the Default/Full Content mode, which seems to just have a page title and no node title.
How to get a rid of the node title on the new view mode so it's the same as the way Default/Full Content displays are shown (without using Views)?
Maybe there's some way to clone the Full Content view mode and then just edit that clone. So the new view mode also only shows a page title not the node title?
Comment: Answer on this question may help you http://drupal.stackexchange.com/questions/107895/hide-title-for-rendered-entity-views/169664#169664
Answer: Since already using Display Suite you can enable Extras module in orde to hide page title
DS config
admin/structure/ds/extras
Tab "Other"
Check "Page title options"
Node Manage Display
admin/structure/types/manage/article/display/full
Tab "Layout for article full"
select Hide "Page title"
Comment: You'll need to ensure you're using the "Full content" view mode for this to work (you may not be by default).
Comment: a vote up for display suite.
Answer: sounds to me like a theming error. you probably have forgotten to check in the node.tpl.php if the node is being viewed or not.
regularly there is no title set
<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>>
    <a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>

you can check for the $view_mode in the node template file and depending on that, set the titel (or dont set it). dont forget, that on the full view_mode, the page variable is set to true.
Answer: If anybody wants to solve this problem programmatically from template.php or a custom module:
/**
 * Implements template/hook_preprocess_node().
 */
function MYTEMPLATE/MYMODULE_preprocess_node(&$vars) {

  if ($vars['view_mode'] != 'full') {

    $vars['title'] = FALSE; // hides second title
  }
}


Como pegar varios elementos e jogar em um unico item?

Question: Ola, queria saber como posso pegar esses li's todos e colocar somente no primeiro
.

1

2

3

4

5

6

7

8

9

10

Comment: Queres apagar os outros ul?
Answer: Podes fazer assim:
$('li').appendTo('ul:first');

Desse modo deixas os outros ul vazios.
Exemplo: https://jsfiddle.net/dmymq4vo/
Comment: Obrigado @Sergio sua resposta se enquadrou mais no que eu precisava então vou marcar como correta ok.
Answer:

$('li').each(function(){
        $('.nova-ul').append($(this));
    });

1

2

3

4

5

6

7

8

9

10

Mas, tal como o @Sergio perguntou e bem se quiser apagar os
 originais terá de acrescentar $('ul').not('.nova-ul').remove(); depois do ciclo each


Get value of material UI buttons

Question: So I have 2 button with values. I want to run a function when someone clicks them that console logs the value. The problem is that I'm using material UI and when I try to use e.target.value it returns undefined.
I've looked around but only found solutions that update the state onChange but I can't do that because I don't have a textbox.
This is what I've tried to do:
 const search = async (e) => {
     console.log(e.target.value)
 }

 <Button value="buttonValue" onClick={search}>Button</Button>

The code above works if it's a normal button so the problem is with Material UI. Sorry if this is a basic question.
Answer: const search = (value,e) => {
   e.preventDefault();
   console.log(value)
  }

 <Button value="buttonValue" onClick={this.search.bind(this,buttonValue)}>Button</Button>

try this
Answer: Do this:
 const search = async (e) => {
     console.log(e.currentTarget.value)
 }

 <Button value="buttonValue" onClick={search}>Button</Button>

Answer:   onClick={(e)=>console.log(e.currentTarget.value)}

Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
Answer: Use currentTarget instead of target
 const search = (event) => {
        console.log(event.currentTarget.value); //buttonValue
    }

 <Button value="buttonValue" onClick={search}>Button</Button>

Code sample:- https://codesandbox.io/s/epic-darkness-gncu0?file=/src/App.js:128-211

Get value of material UI buttons


Reducing size of data sets while preserving their mathematical properties

Question: So I'm looking at the paper $l_p$ Row Sampling by Lewis Weights in which the authors provide a method to sample the rows of a matrix while preserving their mathematical properties.
More specifically they talk about preserving the $l_2$ and $l_1$ norms of the original matrix in the sub-sampled one. The authors mention:

The p = 1 case is of particular interest due to its relation to robust regression, or $l_1$-regression

They go on to cite the compressive sampling paper.
My question is: For practical matters why is the preservation of the $l_p$ norms important? What kind of guarantees do we get when these norms are preserved in the sub-sampled matrix when it comes, for example, to statistical learning/modeling?
Answer: Data compression is a kind of hoary topic wrt massive data. There is a distinction to be made, however, between compression algorithms such as gzip, tar or winzip and data summarization routines, which are less well known but attempt to create reduced, summary data structures for easier storage. Compression algorithms are efforts focused on reducing the size of data while summarization algorithms attempt to reduce the size while also retaining statistical information related to the variability and covariation inherent in the data. The former is largely the province of computer scientists while the latter is the focus of statisticians.
The pioneers in the summarization field were, for the most part, statisticians at Bell Labs back in the 90s who were facing some of the earliest challenges of big data wrt the rapidly sprawling AT&T databases. These included William DuMouchel and Diane Lambert who wrote some of the earliest data squashing algorithms -- as summarization routines were then called.
These early approaches were brought to the attention of a wider statistical audience at the first joint NSF/ASA conference on massive data in 1996. Massive data became big data but that's no matter. Here's a link to a 2002 ebook that summarizes that early, still excellent work: The Handbook of Massive Data Sets. It is free and fully hyperlinked. In particular, see all of Part III (CS algs) and DuMouchel's paper in Part IV (a stats approach):
<code>      http://mauricio.resende.info/hmds.html
</code>
So, I think that at least partly addresses your question. Not knowing anything about your background, it is likely that you are coming at it from a computer science frame of reference where there is less emphasis put on  retaining information about data variability. For statisticians, the variance in information is extremely valuable and important: in a sense, it is the whole story. Therefore, developing routines sensitive to this requirement has been the key goal.
That said, the compression algorithms have won the day, so to speak, as the squashing algorithms have been, for the most part, sidelined and nowhere near as widely used.
Comment: So the $l_p$ norms are  a way to describe the variance in the data? Where could I find more info regarding this?
Comment: Yes. Again, check out the link to the *Handbook* and the DuMouchel paper. Also try searching for Diane Lambert's pub'd papers on data squashing. Also, there's a ton of pub'd research on lp norms...Hastie and Tibshirani's great book *Elements of Statistical Learning* is one source....


Hashing a value in response data from a REST API endpoint to frontend

Question: We are using video call/chat services from a third-party company and we create tokens and channel names to use their chat services in our platform. After our FE requested from our BE for credentials (token and channel name) endpoint responses back with token and channel name information. The third-party system does not create the tokens for specific channel name so it is quite possible to obtain one chat token and as long as you know or guess the chat channel name you can join and text freely. In order to prevent this happening, we are to hash/encrypt the channel names sent in our responses to FE so that the actual channel name won't be visible in plain text.
What's the best way to do this?
BE: Django
FE: Vue.js
Thanks
Answer: You can use python's builtin lib: hmac.
An example:
CHAT_SERVICE_SECRET_KEY is a key you set yourself in your settings.py
<code>   hashed_channel_name = hmac.new(
       settings.CHAT_SERVICE_SECRET_KEY.encode('utf8'),
       channel_name.encode('utf8'),
       channel_token.encode('utf8'),
       digestmod=hashlib.sha256
   ).hexdigest()
</code>
this value can be the response in the frontend.
Comment: Thanks for the answer! And would it be possible to decode this in JS to the actual channel name? Because it is the FE side which creates the channel with channel name and join users in


Brew update failed on Yosemite

Question: I upgraded my Mac to the new OSX 10.10.
brew update failed with:
/usr/local/bin/brew: /usr/local/Library/brew.rb: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby: bad interpreter: No such file or directory
/usr/local/bin/brew: line 23: /usr/local/Library/brew.rb: Undefined error: 0

I tried to follow "Getting a "bad interpreter" error when using brew", but I couldn't get it working.
I do not have Ruby in /usr/local/bin or /user/bin, which may be for same reason which ruby returns nothing.
I have Xcode 5.1 with the command line tools installed. Whenever I start terminal I get:
-bash: /etc/profile.d/sm.sh: No such file or directory
-bash: /etc/profile.d/rvm.sh: No such file or directory

Can anyone suggest possible solutions?
Comment: Edit your bash file manually. Show all hidden files then navigate to your bash file and edit it. Also try upgrade to xcode 6.1
Comment: What did you upgrade *from* that you still had Ruby 1.8?  Mavericks shipped with 2.0.0..
Comment: from Mavericks only but somehow brew.sh points to 1.8 version on first line
Answer: First off upgrade Xcode to 6.1  This is the version that works with Yosemite.
After that make sure you RUN Xcode and Agree to the license ( i know it sucks ).
Note: After Updating My "Oh My Zsh" tools and restarting Xcode it installed some command line tools that I'm pretty sure are important.
Answer: There are things to note:

Mac OSX does come with a Ruby preinstalled in /bin/ruby. That is Apple's own installation, used for some of their tools, and basically should be ignored. Updating it could break those tools, and worse, deleting it, will break them. Trying to reinstall it is a pain, so it's better to pretend it isn't there.
We generally recommend using either RVM or rbenv to manage/install any other Ruby version. Those tools are well tested and make it easy to switch back and forth between versions.

rbenv is easier to manage but lacks some of the features of RVM.
Closely follow the RVM installation instructions if you go that way; We see a lot of questions on Stack Overflow caused by people who ignore the directions, or who follow directions on a different site besides RVM's home site. (The RVM authors really do know better than anyone else how to make it work.)

Brew can install Ruby, but switching between versions gets stickier.
It sounds like your PATH variable doesn't include /usr/bin, which is odd, because it should. If it did, it should find the default Ruby.
echo $PATH

will display your search path. It's editable and, if
ls /usr/bin/ruby

shows that Ruby does exist in /usr/bin then you should add it back into the path. You can do that by editing ~/.bashrc, but also check ~/.bash_profile to make sure something isn't messing up the path. And, if you don't understand how the path works, take the time to read about it, because a badly set-up PATH variable can slow your use of the command-line, or cause all sorts of weirdness.
By default there is no /usr/local/bin/ruby. It won't exist using RVM or rbenv either, but Homebrew will probably put a symlink; I don't have it supplying my Ruby, so I can't check that.
Comment: tried with sudo \curl -sSL https://get.rvm.io | bash -s stable --ruby
Downloading https://github.com/wayneeseguin/rvm/archive/stable.tar.gz
rm: /Users/joshua/.rvm/src/rvm/bin/ruby-rvm-env: Permission denied
Comment: Why did you do `sudo`?

Brew update failed on Yosemite


Prove that the normalizing constant of the continous categorical distribution is positive

Question: Problem statement
Given a vector $\mathbf{x} \in \mathbb{R}^{K}$, where $x_{i} \neq x_{j}, \forall i \neq j$. Prove that:
\begin{equation}
\sum_{k=1}^{K} \frac{\exp(x_{k})}{\prod_{i \neq k} (x_{k} - x_{i})} \ge 0.
\end{equation}
If it is wrong, I would appreciate if a counter example is provided.
Background
I am reading the paper "The continuous categorical: a novel simplex-valued exponential family". In the paper, the authors proposed a continuous version for the categorical distribution. They then provided the normalizing constant. To calculate the log-likelihood, we need the log of that normalizing constant. However, I do not know how to prove that it is always positive, so that we can take a log. Here, I reformulate the expression of the normalizing constant for convenience. If one read the paper, we can analogize $\mathbf{x}$ as $\pmb{\eta}$. Note that although $\eta_{K} = 0$, we could simply consider it as any vector, and just shift $\eta_{i} - \eta_{K}$ to obtain $\pmb{\eta}$ as in the paper. The non-shifting version does not  change the positivity nature of the expression of interest.
In addition, I tried the implementation provided by the authors, but it was unclear to me since the authors calculated the denominator $\propto (x_{k} - x_{i})$, not $(x_{i} - x_{k})$ as specified in the paper. Of course, it would lead to an additional factor $(-1)^{K - 1}$ in the denominator. This factor would then neutralizes the $(-1)^{K + 1}$. However, the implementation still have something with $(-1)^{K-1}$ (Note that the implementation denotes a variable $K$ as the value $(K - 1)$ in the paper.)
I did try the implementation by passing a vector as input to the provided function. However, it does not always return a value, but sometimes, not-a-number (NaN).
Answer: Good question! The simple answer is that the expression you wrote corresponds to the integral of a positive function, therefore it must be positive. To be more explicit, Gordon-Rodriguez et al. showed (in Section A of the supplement for the original paper):
$$
\int_{\Delta^{K-1}}
 \exp\left( \sum_{k=1}^{K} \eta_k z_k \right) d\mu(\mathbf z)
=
(-1)^{K-1} \sum_{k=1}^K
\frac
 { { \exp\left(\eta_k\right)} }
 { \prod_{i \ne k } \left(\eta_i - \eta_k\right)},
$$
where $\mu$ is the Lebesgue measure, $(\eta_1, \dots, \eta_{K})$ are real numbers such that $\eta_i \ne \eta_j$ whenever $i \ne j$, and the integral is taken over the simplex:
$$
\Delta^{K-1} = \left\{ \mathbf z \in \mathbb R^{K} : z_k \ge 0, \sum_{k=1}^{K} z_k = 1 \right\}.
$$
Now, as you correctly pointed out, the $(-1)^{K-1}$ factor corresponds to the changes in sign on the denominator, and so our two expressions are equivalent. Noting that the integrand $\exp\left( \sum_{k=1}^{K} \eta_k z_k \right)$ is always positive, we can conclude that the RHS is also positive, as required.
Let me add a couple of remarks:

The proof that our expression can indeed be written as such an integral is algebraically involved, but it is helpful to assume WLOG that $\eta_K = 0$ (as you already pointed out), and note that our integral is over a $K-1$ dimensional set and can be written as follows:
$$
\int_{\Delta^{K-1}}
 \exp\left( \sum_{k=1}^{K} \eta_k z_k \right) d\mu(\mathbf z)
= \int_0^1 \int_0^{1-z_1} \cdots \int_0^{1-z_1-\cdots-z_{K-2}} \exp\left(\sum_{k=1}^{K-1} \eta_k z_k\right)
dz_{K-1} \cdots dz_2 dz_1.
$$
You can then proceed by induction (details in the supplement).

As for your question about NaN values, you can take a look at section 3.4 from the original paper, as well as section 5 from this other paper. To summarize - computing the normalizing constant is numerically unstable, a problem which becomes worse as $K$ increases (and as a result, these papers only considered examples with $K \le 10$). In terms of the implementation, note that the product in this line is taken over axis=1, which does in fact index rows (not columns), since the 'zeroth' dimension indexes the minibatch samples.
Comment: Section 2 in the following may also be of interest: https://arxiv.org/abs/2204.13290


Lottery probability help

Question: Lottery probability help
Think lottery (1-49) and the fact that you have 1 in 57 (1 in 56.66) chance of matching 3 numbers of 6 being chosen and 6 drawn.
NOW?! HERE is the question...
What are the odds of STILL matching 3 when 10 are chosen (ie just on paper) BUT still 6 are drawn??
So, in short
What are the odds of matching 3 numbers out of 10 (simply written on paper before draw) via a 6 numbers drawn from 1-49 lottery draw?
Comment: Thanks Joonas,
Yes, I understand. Maybe made an assumption regarding 'regular 6/49 lottery draw'. Question edited to  'a 6 numbers drawn from 1-49 lottery draw?'
Peace
Davy
Comment: Remark: Lottery works differently in different countries. In Finland we choose 7 out of 39 numbers or 6 out of 48.
Answer: Think hypergeometric distribution. For the population size $N$, the chosen numbers $K$ and number of draws $n$, the probability of matching $k$ equals:
$$
     \frac{\binom{K}{k} \binom{N-K}{n-k}}{\binom{N}{n}}
$$
The first case: The population size $N=49$, the number of chosen numbers $K=6$, the number of drawn numbers $n=6$. The probability of matching $k=3$:
$$
    \frac{\binom{6}{3} \binom{43}{3}}{\binom{49}{6}} \approx \frac{1}{56.6559}
$$
For the second case: the population size $N=49$, the number of chosen numbers $K=10$, the number of drawn numbers $n=6$. The probability of matching $k=3$:
$$
    \frac{\binom{10}{3} \binom{39}{3}}{\binom{49}{6}} = \frac{45695}{582659} \approx \frac{1}{12.751}
$$
Answer: For a general solution, let:
\begin{eqnarray*}
N &=& \mbox{Number of numbers in total} \\
D &=& \mbox{Number of numbers drawn} \\
S &=& \mbox{Number of number selected (by the player)} \\
M &=& \mbox{Number of matches.}
\end{eqnarray*}
There are $\binom{D}{M}$ ways of choosing $M$ numbers from $D$ to match with.
There are $\binom{N-D}{S-M}$ ways of choosing the other $S-M$ numbers from $N-D$ to not match with.
There are $\binom{N}{S}$ total possible selections of $S$ numbers from $N$.
Therefore, the probability of getting exactly $M$ matches is:
$$\dfrac{\binom{D}{M} \binom{N-D}{S-M}}{\binom{N}{S}}.$$
Your specific question has:
\begin{eqnarray*}
N &=& 49 \\
D &=& 6 \\
S &=& 10 \\
M &=& 3
\end{eqnarray*}
So the probability is
$$\dfrac{\binom{6}{3} \binom{43}{7}}{\binom{49}{10}} \approx 0.0784\;\; (1 \mbox{ in } 12.75).$$

Lottery probability help


Jeffreys prior for multiple parameters

Question: In certain cases, the Jeffreys prior for a full multidimensional model is generaly considered as inadequate, this is for example the case in:
$$
y_i=\mu + \varepsilon_i \, ,
$$
(where $\varepsilon \sim N(0,\sigma^2)$, with $\mu$ and $\sigma$ unknown) where the following prior is prefered (to the full Jeffreys prior $\pi(\mu,\sigma)\propto \sigma^{-2}$):
$$
p(\mu,\sigma) = \pi(\mu) \cdot \pi(\sigma) \propto \sigma^{-1}\, ,
$$
where $ \pi(\mu)$ is the Jeffreys prior obtained when keeping $\sigma$ fixed (and similarly for $p(\sigma)$). This prior coincides with the reference prior when treating $\sigma$ and $\mu$ in separate groups.
Question 1: Why does treating them as in separate groups make more sense than treating them in the same group (which will result, if I am correct (?), in the full dimensional Jeffreys prior, see [1]) ?

Then consider the following situation:
$$
y_i=g(x_i,\mathbf{\theta}) +\varepsilon_i\, ,
$$
where $\theta \in \mathbb{R}^n$ is unknown, $\varepsilon_i \sim N(0,\sigma^2)$, $\sigma$ is unkown, and $g$ is a known non-linear function. In such a case, it is tempting and from my experience sometimes fruitful to consider the following decomposition:
$$
p(\sigma,\theta)=\pi(\sigma) \pi(\theta) \, ,
$$
where $\pi(\sigma)$ and $\pi(\theta)$ are the Jeffreys prior for the two submodels as for the previous scale location example.
Question 2: In such a situation, can we say anything about the  optimality (from an information theory perspective) of the derived prior $p(\sigma,\theta)$ ?

[1] From https://theses.lib.vt.edu/theses/available/etd-042299-095037/unrestricted/etd.pdf:

Finally,  we note  that  Jeffreys' prior  is  a  special case  of a reference prior. Specifically, Jeffreys' prior corresponds to the reference prior in which all model parameters are treated in a single group.
Comment: I think you mean multivariable model, multivariate regression is strictly speaking reserved for multiple variables on the left hand side.
Answer: What is optimal? There is no general and generic "optimality" result for the Jeffreys prior. It all depends on the purpose of the statistical analysis and of the loss function adopted to evaluate and compare procedures. Otherwise, $\pi(\theta,\sigma)\propto \dfrac{1}{\sigma}$ cannot be compared with $\pi(\theta,\sigma)\propto \dfrac{1}{\sigma}^2$. As I wrote in my most popular answer on X validated, there is no such thing as a best non-informative prior.
Comment: Thks for your input. Nonetheless, to my view, Jeffreys prior offers some sort of optimality in the sense that, at least in the 1d setting, they are the one minimizing an information theoric quantity that can make sense and  be discussed (please let me know if I am wrong). My point is: can we write similar "criterion", the Jeffreys prior procedure satisfies for the two settings given in my question ? From the quote given in my question, it seems that yes and I would enjoy discussing the implication of chosing this criterion instead of another one (from a purely IT perspective :)).

Jeffreys prior for multiple parameters


How to blink flashlight?

Question: I've been trying to blink the flashlight of my android for the last 2 hours, and I can't seem to get it to work. All I want is a repeated blink of the flashlight every 500 milliseconds or so, until I click a button.
Here is what I tried, and it does nothing. It doesn't even turn on the flashlight or produce an exception:
   private void blinkLight() {
        cam = Camera.open();
        params = cam.getParameters();

        Thread t = new Thread(){
            public void run(){
            while(userHasntPressedButton){
                params.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
                try {
                    currentThread().sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);

               }
            }
        };
        t.start();
    }

Most other posts suggest using non-continuous blinking, or using similar to this method, but in a handler, but none are working. This was my closest try.
How can I blink the flashlight? Also, is there any way to do it without the camera permission?
Comment: I think without camera permission it can't be possible.
Comment: don't you want another sleep after `FLASH_MODE_OFF` otherwise it will loop to the top and immediately do `FLASH_MODE_ON` - quicker than the eye
Comment: without calling `camera.startPreview();` it can´t work....I assume..
Comment: and be sure that you have used CAMERA and maybe FLASHLIGHT permission added (not sure about FLASHLIGHT, but this permission exists in Android)...
Answer: look at this code if you had any query u can ask!
Use thread class to handle these kind of tasks hope this will help you :) its work for me also thanks!
public void lightBlinking()
  {
    if (blink) {

        flashThread = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < System.currentTimeMillis(); i++) {

                    if (isFlashOn) {
                        turnOffFlash();<--- // method to OFF flash light

                    } else {
                        turnOnFlash();<--- // method to ON flash light

                    }

                    try {
                            Thread.sleep(1000);<---- // set your time

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (!blink){  <--- // asign true false for this boolean
                                       //when you want to blink your flash
                        flashThread.stop();
                        break;
                    }
                }

            }

    });
    flashThread.start();

    }
}

Answer: Try this code instead of using toggle methods, 0 and 1 for ON and OFF Flash Light.
String myString = "0101010101";
long blinkDelay 500; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
   if (myString.charAt(i) == '0') {
      params.setFlashMode(Parameters.FLASH_MODE_ON);
   } else {
      params.setFlashMode(Parameters.FLASH_MODE_OFF);
   }
   try {
      Thread.sleep(blinkDelay);
   } catch (InterruptedException e) {
      e.printStackTrace();
   }
}

Without the "Thread.sleep()" your code is probably too fast.
Comment: That will only flash 5 times...I want it to flash infinitely.
Comment: use true while loop and use login of even odd number with modulus if reminder is zero it mean off and reminder 1 it means ON

How to blink flashlight?


Remove duplicates from a list of tuples of different length with python

Question: I extract specific names from text using regex etc. The result is a list of tuples containing titles and names. The tuples might be of a different length. lst below shows a list of possible scenarios. I need to remove duplicate names from the result. For example, ('Lord', 'Justice') == ('Lord', 'Justice', 'Smith'), and ('Lady', 'Smiles') == ('Lady', 'Justice', 'Smiles'), but ('Lord', 'Justice', 'Smith') and ('Lady', 'Justice', 'Smiles') are different names. The desired output for each element in lst should be [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles')].
lst = [[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles')],
       [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice')],
       [('Lord', 'Justice', 'Smith'), ('Lady', 'Smiles'), ('Lady', 'Justice', 'Smiles')],
       [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice'), ('Lady', 'Justice', 'Smiles')],
       [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lady', 'Smiles')]]

This is what I have right now but it doesn't yield the desired output. Will really appreciate your help and suggestions.
for l in lst:
    print(l)
    # remove duplicates based on the last index in tuples
    lst_1 = list(dict((v[-1],v) for v in sorted(l, key=lambda l: lst[0])).values())
    print(lst_1)
    # remove duplicates based on the second index [1] in tuples
    lst_2 = list(dict((v[1],v) for v in sorted(lst_1, key=lambda lst_1: lst_1[0])).values())
    print(lst_2)
    print("\n")

UPDATE:
I was probably too specific in my examples. I had to include other names so the solution should work when there are other names present:
lst = [
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Smiles'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lady', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
]

Desirable output:
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]

Comment: What about `('Justice', 'Lord')` and `('Lord', 'Justice')`? Are those equal?
Comment: This shouldn't appear in the results based on how names are extracted. The titles always come first.
Comment: If the actual intent here is for comparing version numbers, you should know that's a [solved problem](https://stackoverflow.com/q/1714027/7851115) (e.g. using tuples instead of strings).
Comment: Not really, I need a list of unique names I have to use further down in my pipeline.
Answer: I came with this solution:
from itertools import chain, groupby

lst = [
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Smiles'), ('Lady', 'Justice', 'Smiles')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice'), ('Lady', 'Justice', 'Smiles')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lady', 'Smiles')]
]

def remove_duplicates(lst):
    rv = []
    for g, v in groupby([g for g, _ in groupby(sorted(lst))], key=lambda v: v[0]):
        rv.append(max(list(v), key=lambda v: len(v)))
    return rv

for option in lst:
    print(remove_duplicates(option))

Outputs:
[('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice', 'Smith')]
[('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice', 'Smith')]
[('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice', 'Smith')]
[('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice', 'Smith')]
[('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice', 'Smith')]

Comment: `lst` is a list of different options I might have when extracting names from text. So I need a script which will output the same result for all these options.
Comment: @aviss I modified my answer
Comment: I was probably too specific in my examples. I had to include other names so the solution should work when there are other names present. I updated my question.
Answer: You can do this easily using itertools.groupby
lst = [
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Smiles'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')],
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lady', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
]
res = [[max(reversed(list(v)), key=len) for k,v in groupby(sl, lambda x: x[0])] for sl in lst]
for l in res:
    print(l)

Output
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]

Comment: I was probably too specific in my examples. I had to include other names so the solution should work when there are other names present. I updated my question.
Comment: @aviss. Updated the answer; let me know if this helps
Comment: Perfect! Thank you a ton!