AD DC in azure as the only DC

Question: I have a small network that consists of 1xSBS2008 (Exchange with about 50 mailboxes, Great Plains SQL, File Shares, Printer Shares, DNS,DHCP, GPOs, etc) and 1xWin2k8 (SQL Server). There are about 10 users at Head Office and then we have links to 5 remote locations with between 3 and 6 PCs each. The remote locations are not AD joined and it is not in the plans to do it anytime soon due 3rd part software/user limitations.
I am researching the option of migrating/replacing both servers to Azure. I will be migrating emails to Office365. File access needs to remain in file shares/mapped drives.
Internet connectivity at Head office is 20/20.
My plan is to create 3 Azure VMs:
1xAD DC (this is a VM not Azure AD)
1xGreat Plains SQL / File Server
1xSQL Server for their LOB custom app
At Head Office I would then set up a VPN to Azure via the existing Endian firewall and change the existing remote site VPN to link directly to Azure. The Endian would also become DHCP and DNS, so no DC on premises. The DHCP options will have the Azure DC as its primary DNS with the Endian as its secondary.
Eventually I will probably move all workstations to an Azure RDS.
Does anyone see any problems with this? Should I have a RODC on prem or a DFS replica? Remote sites only transmit small amounts of data (retail stores) so I am confident this would work for them, but not so much for Head Office. How are you upgrading your SBS environments when customers want just a cloud solution without on prem hardware?
Answer: I've tested a similar configuration, focusing on network latency (on limited consumer broadband). Latency is the key here. Good news is that browsing folders etc was boosted with the "new" network stack in Vista and later. However, file download/upload is still affected. Most file server activity is reads. I used BranchCache to accelerate this - hosted branchcache on a Microserver (maybe also a RODC if that is possible) would be ideal.
The other thing you need to consider is performance of your SQL application. Is the client web based or on the PC? If it's on the PC, have a look at using RemoteApp to run the client in the cloud. Heck, you might like RemoteApp so much that you put all apps in the cloud and don't need to look at BranchCache at all because of client/server traffic would stay in Azure.
The other consideration is availability sets. Azure, etc, were designed for big "designed for the cloud" services. When MSFT does a patch cycle, everything in a fault/update domain is powered down for a short time. That means your services would have downtime. The scehdule is announced as something like "you'll see downtime sometime between Thursday and Sunday". They way around this is to create highly available services that are spread across fault domains using Availability Sets. That's easy with a DC (maybe 2 Basic A2s), but much harder and more expensive with traditional workloads like file servers.
Comment: Thanks Aidan, I am not too concerned about latency on the SQL app. The way it works is a Master PC caches SQL data from the server and it only gets synced every so often. It has been working fine on ADSL (8/1).
I am concerned about Great Plains though. I may have to try backing up and restoring to azure and then testing access.
Comment: I like the idea of a Branch Cache with a RODC. You wouldn't RAID this would you, or even worry about backing it up? I could invest that money on SSD drives instead. I mean if it breaks it is just a cache of what is in Azure.

AD DC in azure as the only DC


Ajax Effects using Ajax #commands

Question: Assuming I have the following PHP. I want to add different effects to each of the ajax commands
function my_ajax_callback($form, $form_state) {
  $result = array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace($selector1, $html1),
      ajax_command_replace($selector2, $html2),
    ),
  );
  return $result;
}

I understand the default is something along the lines of:
ajax_command_replace($selector, $html, $settings = NULL)

However I do not know what to do with the $settings = NULL for a fade or slide to work. I've tried all combinations, but to no avail.
e.g.
ajax_command_replace($selector, $html, array('effect' => 'slide'),
ajax_command_replace($selector, $html, array('#effect' => 'slide'),
ajax_command_replace($selector, $html, 'slide')

Comment: try to add   'effect' => 'slide', in the '#ajax' => array() section for form element.
Comment: This will not work, as I am trying to add different effects to each command. If placed in the form, as you suggest, this applies the effect to the entire callback.
Answer: I found the best solution to this was using ajax_command_invoke() and layering the required ajax effects together.
For example, you won't be able to directly fade in an element, but you can use replace or prepend, etc., then hide the element, then fade it in.
function my_ajax_callback($form, $form_state) {
  $result = array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace($selector1, $html1), //add your element
      ajax_command_invoke($html1, 'hide'), //hide it
      ajax_command_invoke($html1, 'fadeIn'), //now use the effect you're after
      ajax_command_replace($selector2, $html2), //add your other element
      ajax_command_invoke($html2, 'hide'), //hide it
      ajax_command_invoke($html2, 'show'), //use the other effect
    ),
  );
  return $result;
}

Answer: You can add effects to command like this:
$command = ajax_command_replace($selector, $html);
$command['effect'] = 'fade';
$command['speed'] = 2000; // Speed in ms.

Ajax Effects using Ajax #commands


Programmatically load node edit form

Question: I'm able to load node create forms like so
$node    = \Drupal\node\Entity\Node::create(['type' => 'avenue']);
$content = \Drupal::service('entity.form_builder')->getForm($node);

return $content;

However what if I want to load an edit form for a pre-existing node? I looked on this page https://api.drupal.org/api/drupal/core!modules!node!src!Entity!Node.php/class/Node/8.2.x but I can't find anything that would relate to the edit form. Is there a way to load the edit form for a specific node?
Comment: Isn't it the same? As in, pass an existing `$node` object to `getForm`?
Answer: Yes, on the linked page you would find Node::load() to get a pre-existing node:
$node    = \Drupal\node\Entity\Node::load($nid);
$content = \Drupal::service('entity.form_builder')->getForm($node);

return $content;

Answer: In Controller -
if ($node) && !empty($node->id())) {
  $node = \Drupal\node\Entity\Node::load($node->id());
  $build = \Drupal::service('entity.form_builder')->getForm($node);
  return $build;
}
else {
  return $this->redirect('node.add', ['node_type' => 'CONTENT_TYPE']);
}

Programmatically load node edit form


Fetch data using single select statement in HQL (One to many relationsheep)

Question: I have two entities student and college. A single college has multiple student.
@Entity
public class College {

    @Id
    @GeneratedValue
    private int collegeId;

    private String collegeName;

    public int getCollegeId() {
        return collegeId;
    }

    public void setCollegeId(int collegeId) {
        this.collegeId = collegeId;
    }

    public String getCollegeName() {
        return collegeName;
    }

    public void setCollegeName(String collegeName) {
        this.collegeName = collegeName;
    }
}

@Entity
public class Student {

    @Id
    @GeneratedValue
    private int studentId;

    private String studentName;

    @ManyToOne(cascade = CascadeType.ALL)
    private College college;

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public College getCollege() {
        return college;
    }

    public void setCollege(College college) {
        this.college = college;
    }
}

Now I want to select all students with say collegeId = 1. I can achieve this with single select query using native SQL:
Select * from student where collegeid = 1

I'm not able to achieve the same with single select query using HQL. Is it possible? If yes then how?
Utility class :
public class ManyToOne {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.hibernate.examples");

        EntityManager em = emf.createEntityManager();

        College college1 = new College();
        college1.setCollegeName("College1");

        College college2 = new College();
        college2.setCollegeName("College2");

        Student student1 = new Student();
        student1.setStudentName("std1");
        student1.setCollege(college1);

        Student student2 = new Student();
        student2.setStudentName("std2");
        student2.setCollege(college2);

        Student student3 = new Student();
        student3.setStudentName("std3");
        student3.setCollege(college1);

        Student student4 = new Student();
        student4.setStudentName("std4");
        student4.setCollege(college1);

        em.getTransaction().begin();

        em.persist(college1);
        em.persist(college2);
        em.persist(student1);
        em.persist(student2);
        em.persist(student3);
        em.persist(student4);

        em.getTransaction().commit();
        em.close();

        em = emf.createEntityManager();
        em.getTransaction().begin();

        String queryString = "select student from "+Student.class.getName()+" student where student.college.collegeId = 1";

        Query query = em.createQuery(queryString);

        List<Student> students = query.getResultList();

        em.getTransaction().commit();
        em.close();
        emf.close();

    }
}

Generated Queries:
Hibernate: select student0_.studentId as studentId1_1_, student0_.college_collegeId as college_collegeId3_1_, student0_.studentName as studentName2_1_ from mevada.Student student0_ where student0_.college_collegeId=1
Hibernate: select college0_.collegeId as collegeId1_0_0_, college0_.collegeName as collegeName2_0_0_ from mevada.College college0_ where college0_.collegeId=?

Answer: HQL
Select * from Student s where s.college.collegeId = 1

Comment: What are the queries executed by hibernate? You can see them by turning on show_sql=true in hibernate config
Comment: I have already tried the same. However after executing select on student hibernate is executing additional query on college table. Not able to figure out why.
  My HQL: `select student from "+Student.class.getName()+" student where student.college.collegeId = 1`
Comment: I have added generate output queries in question. First query only is sufficient and it is executing well in my database also. Not sure why  second query is being generated.
Comment: The issue with additional query was fixed by additionally setting FetchType of ManyToOne mapping to LAZY as by default it is EAGER.


Why are the columns splitted on xs-viewport in Bootstrap?

Question: I am trying to understand Bootstrap, however - I can't figure out why this ain't working on xs. I have a total of 12 columns, but it still puts the col-xs-11 beneath the col-xs-1.
CSS:
[class^="col-"] {
  height: 20px;
  background-color: #563d7c;
  background-color: rgba(86,61,124,.35) !important;
  border: 1px solid #ddd;
  border: 1px solid rgba(86,61,124,.6);
}

.row {
  margin-top: 15px;
  margin-bottom: 15px;
}

HTML:

1

11

2

8

2

Result on xs:
with border-css
without border-css
Could someone tell me what I am missing here? The 2-8-2 is working properly, but the 1-11 not.
I am working on the latest version of Firefox + I am using Bootstrap version 3, not 4.
Edit 1:
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>

Comment: The code you have posted works perfectly, so it must be something else, e.g. other rules you have in your CSS.
Comment: Thanks for answering. This is literally the only css I am using. Could it have something to do with this line? (Edit 1)
Comment: Sorry, I didn't go small enough :) I see it now. I can see why its happening, I'll post an answer in a minute...
Answer: What's happening is that your col-xs-1 column is reaching its minimum width based on its padding and content, and can't go any smaller. This means the col-xs-11 doesn't have enough space and is being pushed to the next line.
The problem is that the cols have 15px left & right padding so even if it was empty you col can't go any smaller than 30px.
Usually you would redistribute the cols on the smallest screen to allocate more space for the smallest cols, e.g.

1

11

However if that isn't an option, you could use media queries to adjust the padding for smaller screens, e.g.:

[class^="col-"] {
  height: 20px;
  background-color: #563d7c;
  background-color: rgba(86,61,124,.35) !important;
  border: 1px solid #ddd;
  border: 1px solid rgba(86,61,124,.6);
}

.row {
  margin-top: 15px;
  margin-bottom: 15px;
}

@media (max-width: 400px){
   [class^="col-"] {
        padding-left:5px;
        padding-right:5px;
    }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

1

11

1

11

2

8

2

(Note, the media query isn't working in the snippet for some reason, but this code does work in a standalone html page!)


imagepng and imagegif

Question: I need some help about PHP GD. Here is my piece of code.
<code>    header("Content-type: image/gif");

    $image = imagecreatetruecolor(550, 20);
    imagealphablending($image, false);

    $col=imagecolorallocatealpha($image,255,255,255,127);
    $black = imagecolorallocate($image, 0, 0, 0);

    imagefilledrectangle($image,0,0,550,20,$col);
    imagealphablending($image, true);

    $font_path = 'font/arial.ttf';
    imagettftext($image, 9, 0, 16, 13, $black, $font_path, $lastlisten);
    imagesavealpha($image, true);

    imagepng($image);
</code>
The problem is when I use imagepng, it can show the png just fine like this.
But if  I use imagegif instead, it will become this.

I did tried using different header for gif and png. The result for imagegif is still the same.
The question is how do I make in order to display GIF version properly? Thanks you
Comment: Gif does not support transparency, and is limited to 256 colors. Unless you're allocating all possible shades of grey created by your desired anti-aliased text, you're going to get block results like that.
Comment: do you mean allocating it pixel by pixel? manually?
Answer: GIF image supports a maximum of 256 colors. Most importantly, it only supports index transparency: a pixel can be 100% opaque or 100% transparent.
PNG on the other hand supports true (millions of) color images and supports alpha channel transparency. That means a pixel can be 100% opaque, 100% transparent or anything in between.
The PNG image you mentioned probably has its edges partially transparent therefore the browser can easily blend those pixels with the background color giving a smooth effect. PNG is a better choice.
Answer: First problem : your characters are ugly: that's because you need to set a palette with less colors when using imagecreatetruecolor.
<code>$image = imagecreatetruecolor(550, 20);
imagetruecolortopalette($image, true, 256);
</code>
should solve this problem.
Second problem : there is no transparency.
As you can see on PHP manual,

imagesavealpha() sets the flag to attempt to save full alpha channel
  information (as opposed to single-color transparency) when saving PNG
  images.

This function does not work with GIF files.
You can use imagecolortransparent instead but this will not be perfect because fonts has anti-aliasing to make their border sweeter.
Here is my code:
<code><?php

$lastlisten = "test test test test test test";

error_reporting(E_ALL);
header("Content-type: image/gif");

$image = imagecreatetruecolor(550, 20);
imagetruecolortopalette($image, true, 256);

$transparent=imagecolorallocatealpha($image,255,255,255,127);
imagecolortransparent( $image, $transparent);
imagefilledrectangle($image,0,0,550,20,$transparent);

$black = imagecolorallocate($image, 0, 0, 0);
$font_path = dirname(__FILE__) . '/font.ttf';
imagettftext($image, 9, 0, 16, 13, $black, $font_path, $lastlisten);

imagegif($image);
</code>
Result here
Hope this helps.

imagepng and imagegif


What's the difference between endogenous variable and multicollinearity?

Question: Investopedia says that:

Multicollinearity is a statistical concept where independent variables
in a model are correlated.

Also Investopedia says that:

An endogenous variable is a variable in a statistical model that's
changed or determined by its relationship with other variables within
the model.

What's the difference between an endogenous variable and multicollinearity?
Does a pair of independent endogenous variables cause multicollinearity?
Comment: Suppose you have a regression model in which you use $x_1, \dots, x_k$ as leading indicators to try to predict $Y$ for the coming month. All of the variables $x_1, \dots, x_k$ might be called 'endogenous'. It is possible that some of the $x_i$ are correlated with others. Presumably, for an econometric model at least _some_ will be significantly correlated because they all reflect aspects of the recent economy. But theoretically, the $x_i$ need not be significantly correlated with each other.  If $x_i$ are highly correlated, you may want to drop some of them to get a less variable model.
Answer: Both definitions are awful.
Normally when you specify a model you have the left hand side (LHS) of the equation depending on its right hand side (RHS). So the purpose of modeling is to find the coefficients that will help you determine what should be LHS for a given RHS. Endogeneity arises when RHS also depends on LHS. Without getting into details, this can mess up your coefficients.
The variables on RHS not only can be, but usually are correlated with each other. It's rarely the case when they are not. That's why the definition of multicollinearity that you cited is terrible. Multicollinearity is a condition when the correlations are so high that they cause issues. This situation is not uncommon though.
Comment: There is probabilistic dependence and there is causal dependence. Your second paragraph does not specify which one you mean, but the correct one is the causal dependence. The first paragraph (first sentence) is quite correct, though :)
Comment: From your first paragraph, is endogeneity and reverse causality bias the same thing?
Comment: How does "RHS also depends on LHS" can be reconciled with the definition provided by stackoverflow that "Endogeneity refers to a situation where an explanatory variable in a model is correlated with the error term"?
Comment: it reconciles, e.g. see [simultaneity](https://en.wikipedia.org/wiki/Endogeneity_(econometrics)#Simultaneity). I find it more difficult to explain correlation with errors than pointing to RHS that depends on LHS. it just tends to be easier to imagine
Answer: Typically, when we talk about endogeneity, we are interested in interpreting the output from a model as causal.  Of particular concern is that there are causal variables and relationships that exist in the universe, but are not included in our model.  If so, that means that the model's estimates are biased and should not be interpreted causally (but may be fine as estimates of the marginal associations).  It is also possible that there are variables in the model that have complex causal relationships that are not captured by the way the model is set up.  For example, there may be a mediational relationship amongst the X-variables.  Another possibility is that Y causes X, and the data are being modeled the wrong way around.
Multicollinearity is when predictor variables are highly correlated with each other.  If it gets to the point where the correlation is strong enough, it becomes very difficult for the model to determine what the relationships really are.  If you were to get another dataset and fit the same model, you might find that you get very different estimates.  To account for this fact, the standard errors that the model estimates for those variables becomes very large.  A way to assess this possibility is to compute the variance inflation factors (VIFs) for your variables.  The VIF is a multiplicative factor that tells you how much larger the variance of the sampling distribution (${\rm SE}^2$) is than it would have been if the variables had been perfectly uncorrelated.  By convention, it is said that you have a problem with multicollinearity if the VIF is >10.  Considering the case where there are only 2 X-variables, that means their pairwise correlation is >.95.

Note that the problem with multicollinearity is just estimating the marginal association with reasonable precision.  It isn't about whether it is appropriate to interpret that marginal association causally.  Furthermore, variables can be correlated without either being a cause of the other.

If one variable is causally related to another, that correlation need not be very large at all to bias the interpretation of the estimate.  On the other hand, there can be a causal relation between variables without leading to a problem with collinearity, because collinearity doesn't occur until the correlation is really strong.
Comment: I diasagree with *the model's estimates are biased and should not be interpreted causally*. If we take them as estimates of causal effects, they are biased. If we take them as estimates of the best approximation (in case of a linear regression, a linear projection), they need not be unbiased. Thus they are either biased or noncausal, but not both (except when there are other sources of bias in addition to endogeneity). Also, are *casually related* and *casual relation* intentional or typos?
Comment: @RichardHardy, that's what I was trying to say. Let me see if I can edit it to make it clearer.


Why does JavaScript return false when comparing a variable with two true statements?

Question: In the following javascript code,
var a = 5;
console.log(5 <= a >= 6);

False is printed to the console.
However, true is printed for the statements 5 <= a and a >= 6. Is it something to do with the double comparisons?
Thanks!
Comment: `a >= 6` is `false`.
Comment: I think the problem is your understanding of what the two comparisons actually are... `((5 <= a) >= 6)`
Comment: Depends on the precedence and associativity of the operators you've used.
Answer: When you test if 5 is less than or equal to 5 you get true
When you test if true is greater than or equal to 6 you get false
(You would also get false if you tested to see if 5 was greater than or equal to 6)
If you want to do multiple tests with the same value, then you need to actually test that value multiple times.
e.g.
if (5 <= 6 && 5 <= 6)

or
if (5 <= 6 || 5 >= 6)

Answer: When you write things like this, you seem to be testing whether:
(5 <= a) >= 6

"5 <= a" evaluates to true, but the statement "true >= 6" evaluates to false.


how to make big menu in drupal 7

Question: How to make the menu like this in drupal 7. There are many customer module in drupal.org, but I don't know much about which module will suit with this. I would to drop down product category when user puts cursor on product menu item.

Thanks
Answer: You can do this by using any of below modules :

Megamenu

Mega menus are a type of drop-down, which seeks to overcome some of
  the usability drawbacks to traditional style drop-downs.

Bigmenu

THIS MODULE attempts to replace the all-in-one global tree view with a
  similar interface, but sub-trees are "collapsed" below a certain
  level, and can be expanded as needed.

TB Mega Menu

TB Mega Menu allows you to create a mega menu with an innovative
  back-end user interface and synchronized with Drupal core menu.

OM Maximenu

That is now possible by using OM Maximenu which can create menus with
  all other module blocks you want as attachments, modules like views,
  slideshow, menu, user, nice menus, quicktabs, and custom blocks with
  tables, lists, images, videos, etc.

Superfish

Superfish integrates jQuery Superfish plugin with your Drupal menus.

Menu Views

Allows menu items to render views instead of links. This is useful for
  creating "mega-menus".

MuchoMenu

This module allows users to create mega menus that have mini panels as
  their flyout content. The benefit is that ANY type of content or UI
  can be added to the menu flyouts.
Answer: You may want to look at Maximenu . This allows you to build complex menus and also allows you to use blocks as menu items.
However you might need to some research if the menu is expected to be fully responsive.

how to make big menu in drupal 7


How to display "About the author" tab in article display page?

Question: I want to basically override the normal display of article, to include two tabs in that. One tab will be "Read Article", which when clicks loads the article page. Others tab will be "About the Author", which when clicks loads the author page.
So ultimately when I go to any article page, there will be two tabs, "Read Aricle" (selected by default), and "About the author".
Please suggest how can I achieve this. I have tried overriding node display by using Panels, but I am not able to add links or display author information in another tab.
-- Thanks for your time.
Answer: There is Author Pane

Author Pane is a block of information about a given user, like those
  typically found on a forum post, but can be used in other places as
  well. From core, it collects the user picture, name, join date, online
  status, contact link, and profile information. In addition, any module
  or theme can feed it more information via the preprocess system. All
  of this information is then gathered and displayed using a template
  file.

For the tabbed view you cold try Quick Tabs

The Quick Tabs module allows you to create blocks of tabbed content,
  specifically views, blocks, nodes* and other quicktabs*.
Comment: It just display normal block with some data. Actually I have override display of author page too, and I want to load that page and not custom block. -- Thanks


HTML special characters changed to foreign characters

Question: We have a Drupal 6 website and are using tinymce for the editor. Many of our pages included the pound (£) sign as well as other special characters. All of these have now been changed into foreign symbols. The pound sign now appears as £ and other strange symbols such as –.
I've checked the source code and the original characters have been changed into the strange new characters. It seems like the only way to fix it is to manually edit all the pages. I checked the character encoding tag and this is set to utf-8.
Can anyone help with why this might have happened in one go? The only thing I can attribute it to is possibly running update.php. Also, is there an easier way to convert then all back again?
Many thanks,
Ben
Comment: Looks like an issue in DB encoding
Answer: It should work in a proper Drupal environment

Several people have asked how to specify the character encoding that
  Drupal uses. The short answer is: you can't.

How can I change Drupal's character encoding

Drupal uses UTF-8 for encoding all its data. This is a Unicode
  encoding, so it can contain data in any language. You no longer need
  to worry about language specific encodings for your website (such as
  Big5, GB2312, Windows-1251 or 1256, ...). Also, when Drupal imports
  external XML data (such as RSS or XML-RPC), it is automatically
  converted into UTF-8 (iconv support for PHP will be required for most
  encodings).

From Stackers


How to solve this question on time and work?

Question: Question:
"Pipe A can fill the tank in 4 hours, while pipe B can fill it in 6 hours working separately. Pipe C can empty the whole tank in 4 hours. Ramesh opened the pipe A and B simultaneously to fill the empty tank. He wanted to adjust his alarm so that he could open the pipe C when it was half-filled, but he mistakenly adjusted his alarm at a time when his tank would be 3/4th filled. What is the time difference between both the cases, to fill the tank fully."
Doubt:
I am unable to approach the problem properly. A detailed justification into how the problem should be approach will do a lot of benifit.
Comment: $C$'s rate of emptying the tank matches $A$'s rate of filling the tank so when $C$ is opened the tank will fill at $B$'s rate of $\frac{1}{6}$ of a tank per hour. Now just use that number to compare the time it takes to fill a half tank and a quarter of a tank.
Answer: If I interpret it correctly, it's asking for the time difference between filling the tank from 1/2 full and filling the tank from 3/4 full.
Regardless of whatever happened beforehand, the rate of flow into the tank in both of these cases is the same, as all pipes are always opened. So all you must do is simply determine that final rate of flow, and see how long it takes to fill the remaining tank in either case.


How does the harmonic series affect consonance?

Question: NOTE: for the purpose of this question, assume we are talking about 12-TET and assume that references to overtones in the harmonic series are being referred to in relationship to the 12-TET note that they have closest parity with.
In another post, there were many contributions that made reference to the harmonic series and also to the heavy influence 12-TET has had on our understanding of music theory and the language we use to describe it. If you believe that the principles of harmony have an origin in the natural universe and in the harmonic series, then it would seem that the tuning system we use today has permanently set us apart from that.
I have long believed that the overtone series of any given root note strongly affects which intervals will "fit" on top of it harmonically. David Cope, a professor of music at UC Santa Cruz refers to this concept as "interval strength". I have also heard a great deal of support for this concept when talking with professors of harmony and other musicians with graduate degrees in harmony from some of the top music programs in the world, so I believe that this idea is well-established in the music community, even though I haven't seen much research on the topic.
Approximation of overtone series
If we look at the harmonic series, we see that the overtones occur in an order that appears quite related to the consonance of pitches:
8, 5, 8, M3, 5, m7, 8, M2, M3, d5, 5, m6, m7, M7, 8, m2, M2, m3, M3,
wikipedia
Notes
1) I have spelled all intervals enharmonically to represent the most frequently-used intervals in harmony.
2) I have spelled all intervals as closed intervals, regardless of how many octaves separate them from the fundamental.
3) I have not noted the approximations of how sharp or flat these overtones may be in comparison to their 12-TET counterpart.
Here's my four-part question:
1) To what extent does an overtone's first appearance in the overtone series affect the consonance of the 12-TET interval to which it corresponds?
2) If the overtone series is related to consonance as mentioned in #1, to what extent is this consonance reinforced by an overtone which appears repeatedly in the overtone series?
3) If the overtone series is related to consonance as mentioned in #1, to what extent does the inversion of one of the overtones correspond to consonance? For instance, the fifth is supported very well in the overtone series, but the fourth is not present, except as an overtone halfway between the fourth and the augmented fourth. However, the fourth seems to have a similar consonance as the fifth, perhaps because its own overtone series corresponds to the root.
4) I have been challenged before when I have said that the higher the overtone is, the less significant it is, because the overtones become less audible as they get higher and higher. Is it true or not true that overtones become less audible as they get higher? If so, doesn't this mean the lower overtones are of more importance? Has there been any research done on amplitude of various overtones (say, given a certain instrument such as guitar or piano) and the point at which that amplitude is so low that humans can't hear it?
Answer: We first need to categorize each interval, assign it a "consonance amount". That's the first problem we find. In the case of the fourth, for example, some consider it perfect consonance, and others consider it a dissonance, depending context (and who you ask).
For simplicity, let's define ours based on Wikipedia's:

1: Perfect consonances: unison, octave, fourth, fifth.
2: Imperfect consonances: major third, minor third, major sixth, minor sixth
3: Dissonances: minor second, major second, tritone, minor seventh, major seventh

1) To what extent does an overtone's first appearance in the overtone series affect the consonance of the 12-TET interval to which it corresponds?
The problem here with "which it corresponds" is that some harmonics will be not very close to its "corresponding" interval. The difference can be as big as 40-50 cent, which is the max difference before the harmonic is closer to another interval. It's more a "middle" than that particular interval at that point.
But let's ignore that. Here is the order in which the intervals appear in the harmonic series, the place in which they appear, and the difference between the interval and the harmonic in cents:

Interval   1st Appearance  Difference
----------------------------------------
root            1            0.0
fifth           3            1.9
major third     5           13.7
minor seventh   7           31.2
major second    9            3.9
tritone         11          48.7
minor sixth     13          40.5
major seventh   15          11.7
minor second    17           5.0
minor third     19           2.5
fourth          21          29.2
major sixth     27           5.9

The first two intervals that appear in the harmonic series are perfect consonances. The third one is an imperfect consonance. So far, so good. But here we reach a stop. The fourth, fifth, and sixth intervals are all dissonant, but they appear fairly early in the harmonic series (harmonic 7, 9, and 12 respectively). Also worth noting that the major sixth, an imperfect consonance, is the last interval to appear.
Other than the first 3 intervals that appear in the harmonic series (root, fifth, and major third), seems that there is no strong relationship. The order is all over the place in relation to their "consonance amount". To me it seems that the first appearance in the overtone series doesn't affect the consonance of the interval (considering the restrictions of the question: interval = closest interval to the harmonic and 12-TET).
As Bradd Szonye mentioned in the comments, it's worth diving into the interval relationship between harmonics. Here, as we go higher in the harmonic series, the interval between harmonics becomes smaller and smaller, quickly converging in one interval, starting with the minor third, as early as the 6th harmonic. So let's see the first 6 harmonics.

1-2 root
2-3 fifth
3-4 fourth
4-5 major third
5-6 minor third

Here we see the fourth and minor third. I don't know if "they appear early" has any significance here, given the few harmonics we can analyze before they converge in one interval more and more. What might be significant is the fact that they appear, and all of them are consonant. In fact, if we consider their inversions, those 6 harmonics cover all the perfect and imperfect consonances.
In this case, we do see a strong relationship. Dissonances do not appear in the intervals between harmonics (between n harmonic and n + 1) in the pre-convergence range.
2) If the overtone series is related to consonance as mentioned in #1, to what extent is this consonance reinforced by an overtone which appears repeatedly in the overtone series?
We concluded that they are not strongly related, but let's see the data anyway.
First we need to decide how many harmonics we will consider. If you go deep enough, you'll find that several consecutive harmonics will "belong" (be closer to) the same interval, so maybe it's a good idea to stop before that happens. Also, the higher the harmonic, the lower the amplitude (in general, consider a sawtooth wave for simplicity), so higher harmonics will not have as much as an impact as the first ones.
There is no pretty way to avoid this issue. Tritone appears consecutively in harmonics 22 and 23, and minor sixth appears consecutively in harmonics 25 and 26, but major sixth doesn't appear until harmonic 27, so limiting the analysis to harmonic 22 would exclude it. But that's what we are going to do to avoid consecutive appearances.
Here are the intervals and the frequency in which they appear in the harmonic series, first 22 harmonics:

root            5.0
fifth           3.0
major third     3.0
minor seventh   2.0
major second    2.0
tritone         2.0
minor sixth     1.0
major seventh   1.0
minor second    1.0
minor third     1.0
fourth          1.0
major sixth     0.0

Again, root, fifth, and major third are in the top, and again we see dissonances appearing early. Again, we see consonances in the last places. There doesn't seem to be a strong relationship here either, with the exceptions (again) of root, fifth, and major third.
3) If the overtone series is related to consonance as mentioned in #1, to what extent does the inversion of one of the overtones correspond to consonance?
It shouldn't make a difference in our current categorization. All the inverses correspond to an interval in the same category.

Perfect consonances:
P5 - P5

Imperfect consonances:
M3 - m6
m3 - M6

Dissonances:
tri - tri
m2  - M7
M2  - m7

4) I have been challenged before when I have said that the higher the overtone is, the less significant it is, because the overtones become less audible as they get higher and higher. Is it true or not true that overtones become less audible as they get higher?
It depends. You can synthesize a sound with any harmonic ratio you can think of. But yes, less exotic sounds will have that tendency, the higher the harmonic the lower the amplitude It's not a constant, this tendency is commonly broken: some higher harmonics might have a higher amplitude than some lower harmonics. Some lower harmonics might not even be present, as some instruments cancel or attenuate specific harmonics.
It's a tendency, not a constant, there are many exceptions. That's maybe why you were challenged about it.
Alto sax:

Nylon guitar:

Trumpet:

Snare drum:

If so, doesn't this mean the lower overtones are of more importance?
The less amplitude an harmonic has, the less it adds to the sound. So, higher amplitude harmonics add more to the sound, they are "more important". As lower frequency harmonics tend to have more amplitude, there will also be a tendency of lower frequency harmonics being "more important", but it's not necessarily the case, as lower frequency harmonics not always have higher amplitude than other higher frequency harmonics.
It would be more accurate to say "higher amplitude harmonics are more important".
Has there been any research done on amplitude of various overtones (say, given a certain instrument such as guitar or piano) and the point at which that amplitude is so low that humans can't hear it?
Interesting question. Don't know of any study in particular, but you can do it yourself.
Use a very steep high pass (low cut) filter and increase the cutoff frequency until you can't perceive a sound. That's where you stopped hearing the harmonic series at that specific amplitude. Now check the cutoff frequency and the fundamental of the sound you filtered. Divide the cutoff frequency by the fundamental and that's roughly how many harmonics you were able to hear.
That doesn't deal with masking and other dynamics, though. Maybe another experiment you can make is the opposite. Use a very steep low pass (high cut) and decrease the cutoff frequency until you perceive that the sound is changing. If you don't perceive a change, it means that those harmonics (if any) aren't adding something to the sound (at least to your ears). When you perceive the smallest change, do the same: divide the cutoff frequency by the fundamental and that's roughly how many harmonics were "important" enough for you to hear a change.
You can then check the amplitude of those harmonics around the cutoff frequency in relation with the fundamental with an harmonic analyzer.
I wonder if the two experiments yield similar results.
Comment: Excellent answer! One comment regarding point 1: While the perfect fourth and minor third show up very late in the harmonic series as partials, they show up much earlier as inversions. We usually define a just perfect fourth (4:3) as the interval from the just fifth (second partial) to the next octave (third partial). Likewise, the just minor third (6:5) is the interval from the major third to the next fifth.
Comment: @BraddSzonye I'll try to make the same dynamic with the intervals between harmonics too then. Will update the answer in a bit, thanks for the input.
Comment: @BraddSzonye It doesn't seem to be the case of the minor third. The inverse of minor third is the major sixth, and both appear late in the harmonic series. Am I missing something?
Comment: Sorry for any confusion – I meant the other common sense of "inversion," as in "not starting with the fundamental." The minor third is usually defined as the interval from major third to fifth, rather than an interval directly from unison/octave.
Comment: @JCPedroza If you take two notes forming a minor 3rd, so their ratio is 1:6/5, then sixth harmonic at 6 of the lower (corresponding to a musical octave+5th), matches the fifth harmonic of the higher note (corresponding to a musical 3rd).
Comment: @BraddSzonye I see! This analysis is, as the question requested, all based in 12TET and using the fundamental as reference, as we are diving into the consonance and dissonance of the fundamental with its harmonics (basically). Do you think the interval relationships between the harmonics and just intonation is important and relevant in the context of this question? Would it change the conclusions? I'm always up for a revision.
Comment: I do think the interval relationships between overtones are important, especially because the 4th, 5th, and 6th harmonics from a major triad, which contains a stacked minor third. That 4:5:6 ratio is essentially the definition of the stacked thirds in just intonation.
Comment: Wow, great answer. Especially after reading your answer, I agree that it seems hard to prove a relationship of consonance based on this in 12-TET, except for the first three intervals and their inversions. And you're right, in several cases the variance between the harmonic and its "corresponding" note is up to a diesis or higher, which is the amount of difference needed to it to be considered a different note in another tuning system.
Comment: I wonder if, given a more perfect tuning system, the significance of overtones higher than the major third would increase. In that case maybe it would make more sense to analyze the fundamental of a chord and its overtones, as well as the other notes in that chord, and their overtones, and look for a broader relationship.
Comment: @BraddSzonye Added some insight into the interval relationships among harmonics, with very interesting results that I had no idea of. Give it a read, I might be missing something.
Comment: Good update! I've been thinking about this a bit today, and you hit on basically all of the points that occurred to me. Also interesting: Consider the harmonic series one octave at a time. First, you get just an octave (R–P8). Next, a power chord (R–P5–P8). Next, a dominant 7th chord (R–M3–P5–m7–P8). All of those are important in music theory. Or for another way of looking at it, splitting the octave in half gives you the perfect consonances (P5+P4). Then splitting the fifth in half gives you the imperfect consonances (M3+m3 and their inversions).
Comment: @Grey Unfortunately, any tuning system is ultimately an exercise in compromises, because harmony is rooted in the division of wavelengths, and division just doesn't behave nicely. Tune everything perfectly for the tonic and your non-tonic chords become a mess. Also, as Dave's answer notes, real instruments don't actually have mathematically perfect harmonic series. Because strings are stiff, they *don't* divide neatly in reality, and so instruments with very wide ranges aren't even completely in tune with themselves. See "stretch tuning" for piano, for example.
Answer: For your specific points:
1) For most/all* instruments, the amplitude of the partials decreases as the partial number (i.e. frequency goes up).  Thus, for almost all musical sounds there is "more of" the (first) octave and the fifth and less of the higher harmonics.  So adding a second sound whose fundamental is at one of the lower harmonics reinforces something that is "already there", i.e. pretty easily percievable.  Adding a new note whose fundamental is at one of the higher partials "brings out something new" -- i.e. less consonant.
Consider the just-intonated intervals in order of increasing denominator:

  unison    |    1/1
  perf. 5th |    3/2
  perf. 4th |    4/3
  maj.  6th |    5/3
  maj.  3rd |    5/4
[ min.  7th*|    7/4      (7th harmonic) ]
  min.  3rd |    6/5
  min.  6th |    8/5
  maj.  2nd |    9/8
  maj.  7th |   15/8      (5-limit JI)
  min.  7th |   16/9      (5-limit JI)
  min.  2nd |   16/15

If you ignore the pitch related to the 7th harmonic as a special case,
these are pretty much in order of degree of consonance.  Consider the
harmonics on top of each of these pitches, e.g. for the perf. fifth
it will be 3/2,3,9/2,6..., every other harmonic of this note is already
present in the overtone series of the fundamental (which, in  this
representation has frequencies of 1,2,3,4,...).  Similarly, one out of
every three of the overtones of the perfect 4th, and the major 6ths
will already be present in the over tone series of the fundamental.
In this sense, adding a note at a consonant interval is reinforcing harmonic
content that is already present in the fundamental to a greater degree than
notes at dissonant intervals would.
There is also a practical problem for non-synthesized instruments: the partials are not exactly integer multiples of the fundamental; these inharmonious arise due to the physical characteristics and limitations of the instrument.  Thus trying to match a given high partial with another note produced a a different instrument will likely miss, and you'll end up with two frequencies that are close to one another but slightly different, and thus hear them beating against one another, leading to perceived dissonance.
2) Formally, there are an infinite number of each partial; however as mentioned above, the amplitude of the higher ones is smaller than the amplitudes of the higher ones; thus the first appearance is the most important indicator of how significant a given partial is.
3) In this context a way of thinking about inversions is that "the overtones of the higher note match up with overtones of the lower one", take the perfect 4th G-C -- the partial corresponding to a musical fifth (at a frequency 3 times the original) of the fundamental C matches up with one of the octave partials of the G.
4) For most/all* musical instruments the amplitudes of the higher overtones is much lower than the lower overtones; here I'm referring to a note held at steady state. The transient initial attack, if analyzed by itself, may show a variety of high-frequency content that is not related to the steady state note.  A search on "frequency spectrum violin", for example, yielded a series of pages (some of which) include the power spectrum of a violin as measured, thus with  a little searching you should be able to find representative information on any instrument of your choice.  Almost any book on musical acoustics, e.g.  Music Physics and Engineering (H. Olson), will probably also have similar spectral plots.
An important source of dissonance is the physical beating between pairs of closely spaced frequencies; the links in this wikipedia entry on the physiological basis of consonance should provide a pointer into the research in this area.  Another important point is that (except for synthesized sounds) there are inharmonicities in the overtones of a musical note -- the overtones are not exactly integer multiples of the fundamental.  So what happens when you play two notes whose musical interval corresponds to one of the higher partials: they (and all of their partials) tend to miss one another by a small amount; this leads to perceptable amplitude beating, and this is perceived of as dissonance.
I haven't yet worked all the way through it but The Harmonic Experience by W.A. Mathieu covers the aspects of how do the just-intonated harmonic relationships integral to the physics of sound relate to/with modern equal temperament practice.

I can't think of a counter example where the amplitudes of the partials doesn't go down as the frequency goes up.  I'm sure someone, somewhere, has synthesized sounds with this property, but even most standard synth patches have this feature.
Answer: These are all great answers. One little wrinkle:  when the fundamental tone is very low -- i.e., in the subbass register (20-60 Hz), we often hear much more of the higher overtones than the fundamental or first partial. The human ear's sensitivity falls off dramatically as frequency drops below about 200 Hz.
When you play the lowest note on a grand piano (approx 27 Hz), most of what you're hearing is upper partials.
Answer: Researchers in psychoacoustics and music psychology have been studying this for a long time.  I believe it's Plomp and Levitt showed that, with intervals, if you take just the fundamental, interval dissonance simply decreases with interval size (m2, M2, m3, M3...M7...) but if the overtone of each note are added in, you eventually get the well-established interval dissonance ranking of (I believe; I'm too lazy to get up!) m2>M2>A4>m6>m7>M6>P4>P5>P8.
Then the whole problem intensifies when they try to understand the dissonance ranking, based on listener response studies and frequency of usage, of 3-tones (triads): Maj>min>diminished>augmented.  Due to pattern recognition of the harmonic series (we evolved hearing it), there are phenomenon such as tonal fusion where the fundamental of a series will be provided by the hearing system even if not present, since it completes the (gestalt) pattern.
I think the biggest mystery in this field is explaining the consonance of the minor triad, which does not appear, in a prominent way, in the harmonic series.  Check out the experts such as Richard Parncutt and Norman CooK.


Bloquear listagem de diretório no Apache

Question: Estou desenvolvendo um site onde possuo um painel administrativo que é acessado somente por quem possui acesso. nas páginas do painel administrativo, fiz a validação que verifica se o usuário está logado como admin para acessar a página. Por exemplo, se qualquer outro usuario tentar acessar diretamente pela URL nomedosite.com/administrativo/usuarios , ele será redirecionado à página inicial. Porém, se eu somente digitar na barra de endereços: nomedosite.com/administrativo , ele me traz uma listagem de todos os arquivos que possuo na pasta. Como proibir isso, para que ao acessar a pasta que tem os arquivos o usuario seja redirecionado, e nao somente ao acessar a página?
Comment: Via htaccess não dá pra fazer isso?
Comment: Boa dica, ainda não havia tentado. Vou tentar usar.
Answer: Primeiro o fato de aparecer as pastas não é um problema de código php, seu servidor http (talvez seja um apache) esta com o parâmetro Indexes (se for um apache) habilitado o que pode ser um furo de segurança em muitos casos.
Você tem duas opções se tiver acesso as configurações do seu servidor web remova o parâmetro Indexes onde está o diretório do seus arquivos web
Exemplo:
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

Mudar para:
<Directory /var/www/>
        Options FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

Outra alternativa é colocar um .htaccess no diretório em questão com a seguinte linha:
Options -Indexes

Sobre o redirecionamento você também tem algumas opções, você pode criar um index.html ou index.php que simplesmente redireciona todos que conectem neste seu diretório, outra alternativa é utilizar o .htacess novamente, veja vários exemplos aqui


cordova build task customisation

Question: I want to develop a plugin for phonegap/cordova.
I will create a folder into /plugins/
I want to execute from the command line:
phonegap build android or phonegap run android
I would like to have the .java files copied from my plugin folder to /platforms/android/src
Most of plugins at install time are copyed, but not at build, run tasks.
Any idea where to put an xml file for which or which one to edit?
Edit:
From Here it seems I need a before_build file/task declared / created somewhere, where?
- and need to do what after_plugin_add does presented Here
Answer: Here is the source of the installation script.
The code part which need to be executed at run / build is :
// queue up native stuff
        sourceFiles && sourceFiles.forEach(function(source) {
            actions.push(actions.createAction(handler["source-file"].install, [source, plugin_dir, project_dir, plugin_id], handler["source-file"].uninstall, [source, project_dir, plugin_id]));
        });

        headerFiles && headerFiles.forEach(function(header) {
            actions.push(actions.createAction(handler["header-file"].install, [header, plugin_dir, project_dir, plugin_id], handler["header-file"].uninstall, [header, project_dir, plugin_id]));
        });

        resourceFiles && resourceFiles.forEach(function(resource) {
            actions.push(actions.createAction(handler["resource-file"].install, [resource, plugin_dir, project_dir], handler["resource-file"].uninstall, [resource, project_dir]));
        });

        libFiles && libFiles.forEach(function(lib) {
            actions.push(actions.createAction(handler["lib-file"].install, [lib, plugin_dir, project_dir], handler["lib-file"].uninstall, [lib, project_dir]));
        });

// run through the action stack
actions.process(platform, project_dir, function(err) {
    if (err) {
        if (callback) callback(err);
        else throw err;
    } else {

        // queue up the plugin so prepare knows what to do.
        config_changes.add_installed_plugin_to_prepare_queue(plugins_dir, plugin_basename, platform, filtered_variables, is_top_level);
        // call prepare after a successful install
        require('./../plugman').prepare(project_dir, platform, plugins_dir);

        require('../plugman').emit('results', plugin_id + ' installed.');

Here is a response which describe  the folder structure with those names.

cordova build task customisation


Set notation and the difference between $\subseteq,\in,\subset$.

Question:
What does it mean to say $\mathcal F$ is a family of subsets? (an example would be much appreciated :)) What would be a layman's example?
When $B=\{b,c\}$ is it appropriate to write $\{a,\{b,c\}\} \subseteq A \Rightarrow\ B\subseteq A$
$\{a, \{b,c\} \} \in A$ is that good notation?
Would $\{\{a,d\}, \{b,c\}\}$ be considered as a family of subsets?
Answer:
Just that $\mathcal F$ is a set of subsets, of some stated set. "Family" is a more informal term when it helps to think of sets of sets as different from elements (in set theory, this is a relative term only).
No. Just do the substitution. $\{a,B\} \subset A$ means $B \in A$. Just like $\{1,2\} \subset \mathbb N$ means $2 \in \mathbb N$.
Yes, but only if you are intending to write something really complex: "The set that has two elements, the first of which is $a$ and the second of which is the set $\{b,c\}$ itself, itself, is an element of $A$.
I guess it's a family of subsets of $\{a,b,c,d\}$. Again, "family" is a relatively informal term usually, so your (4) would only really make sense if you told me about $\{a,b,c,d\}$ first, and asked me if your example were a family of subsets of that four-element set.

To answer your title question, $\subset$ and $\subseteq$ depend on the author's choice of convention. Usually they mean the same thing, but sometimes an author wants $\subset$ to mean "is a strict subset", that is, not the whole set itself, and $\subseteq$ to mean "is a subset or equal." Presumably this follows how $<$ and $\leq$ work. However, in the usual practice, $\subset$ means "is a subset (or equal)", $\subseteq$ means the same thing, and $\subsetneq$ means "is a strict subset of".
Answer: 1) $\mathcal{F}$ is a family of subsets if it's elements are sets. Good example would be power set of given set. Another example : consider rolling a dice - the set of possible outcomes will be $\{ 1, 2, 3, 4, 5, 6 \}$ here $\mathcal{F}$ could be $\{ \{2, 4, 6\}, \{1, 3, 5\}\}$
2) No. Here $A$ and $B$ are to be understood as collections of sets
3) Yes - if $A$ is collection of sets
4) Yes - by definition!
Answer:
A collection $\mathcal F$ of of a given set $S$ is called family of subsets of $S$.

Example. Let $S=\{a,b,c,d,e\}$, example of family of subsets would be $\mathcal F=\{A_1,A_2\}$  where $A_1=\{a,b,c\},A_2=\{d,e\}.$

No, you can say that $B \in A$ though.
Yes. Here $A$ is collection of sets.
Yes,


find the shortest path of travel from given route between vertices python

Question:
x travels different vertices. some path is given as input. input given as path between different vertices.

For instance:: 1-7 , 1-2 , 2-5 ,5-6. By connecting this output would be finding the shortest path of travel output::7->1->2->5->6. i am new to programming. what logic i have to use?
Comment: Well, which shortest path algorithm did you implement? Where's your code?
Answer: You can use the 2-opt algorithmn.
Answer: Probably the most well-known algorithm for finding the shortest path, is Dijkstra's algorithm. You can find a python implementation here


Statistical significance with insufficient data

Question: There is an article in Wikipedia which talks about p-values. In the example section it gives this example:

One roll of a pair of dice
Suppose a researcher rolls a pair of dice once and assumes a null hypothesis that the dice are fair, not loaded or weighted toward any specific number/roll/result; uniform. The test statistic is "the sum of the rolled numbers" and is one-tailed. The researcher rolls the dice and observes that both dice show 6, yielding a test statistic of 12. The p-value of this outcome is 1/36 (because under the assumption of the null hypothesis, the test statistic is uniformly distributed) or about 0.028 (the highest test statistic out of 6×6 = 36 possible outcomes). If the researcher assumed a significance level of 0.05, this result would be deemed significant and the hypothesis that the dice are fair would be rejected.
In this case, a single roll provides a very weak basis (that is, insufficient data) to draw a meaningful conclusion about the dice. This illustrates the danger with blindly applying p-value without considering the experiment design.

You obviously would not publish a paper on the result, yet the p-value is statistically significant. What are some measures to prevent this type of "error"?
PS. It would be great if both a frequentist and a Bayesian methods presented.
Comment: P-values are great, aren't they?
Comment: It should be "significance level of '0.05'" and not '0.005'
Comment: https://xkcd.com/1132/
Comment: This is a fairly weak p-value resulting from a one-sided hypothesis test. As far as I know, no one advocated blindly testing arbitrary hypotheses, so the suspicion of the dice rolling, on average, more than 7 must be an important scientific question. Furthermore, the 0.05 significance threshold is a regrettable result of people reading Fisher's earlier works. Fisher would have the researcher make his/her own judgements based on new and possibly old evidence while for Neyman/Pearson this would be the single prespecified hypothesis to test. In any case, reviewers would likely ask for replicates.
Answer: This is indeed a weak point of hypothesis testing...it allows you to make "strong" sounding statements even though the data are weak.
Now, if 100 people all performed this same weak experiment, you'd expect about 3 people to get this result. So, if the dice were biased towards 6, then this is evidence for that hypothesis (or at least that they are not fair).
This is a totally valid experiment and conclusion. However, it is incomplete. What we want to know is the range of biases supported by this result (I'll get to this more in a sec.) and the probability that you could reproduce it.
The range of supported probabilities is harder to get than just a Reject/Do Not Reject decision for a hypothesis test. You will need to specify a model for the probabilities (which can be anything from a simple 6-parameter saturated model, to a model where the probability of rolling each number is a function of some underlying parameter $\theta$.) What you would find is that this result, while statistically significant, places very, very loose bounds on the range of actual face probabilities for each die. This is where the weakness would show.
The second way to evaluate this is to use a Bayesian model with a uniform Dirichlet on the prior probabilities for each die face. Then, you can calculate the posterior predictive probability (see (1) on p.4) of rolling a 12 and compare it to the null model of equal face probabilities. You will see that the actual "bump" in the probability of rolling a 12 will increase only slightly, not, say, from $3\%$ to $10\%$. This is another indication of the weakness of the result.
Answer: You have a better chance of rolling more than 3 double-sixes in 45 rolls than you do rolling a double six in only a single roll so the author's single-roll-provides-a-very-weak-basis argument is itself pretty weak.
In fact, it doesn't matter how sophisticated your experimental design is--if your chosen significance level is 5% then 5% of the time you'll end up with statistically significant results by chance alone.

Side note: Bayesians don't use p-values. In fact, some Bayesians will even get a crazed look in their eye if you even mention 'p-values'.
Comment: Bayesians don't use p-values; as far as I know they use factors. But those fail just as miserably here if the models being compared are (chance of 6 = 1/6) vs (chance of 6 = 5/6)
Comment: So the question is what are some procedures for making sure that your experimental design will collect enough data or be sophisticated enough?
Comment: Bayesians start with "prior probabilities" and then update these "priors" (to form "posterior probabilities") as new information comes along.


How do I return two observables joined as the same observable

Question: I'm having trouble getting a function to return. It has a condition that would return an Observable, and another condition that I would like to return the results of two observables with the results of successful being merged together.
Something like this.
getSearchFeed(): Observable<items[]> {
   if (this.condition) {
     return this.populateItemsArray();            //function Returns Items Array Observable
   }

   //second condition
   const someItems = this.populateSearch();       //function Returns Items Array Observable
   const otherItems = this.populateOtherSearch(); //function Returns Items Array Observable

   return forkJoin(someItems,otherItems)
    .pipe((res:Array) => {
      return [...res[0],...res[1]];
   });
}

Other posts talk about joining the results, which I understand how to subscribe and join. My question is more on the lines of how can I return an Observerable for the second condition.
Some of the other things I've tried,
return forkJoin(someItems,otherItems)
 .pipe(map((res:Array<Observerable<Items[]>>) => {
    return [...res[0],res[1]];
});

and
const source = of([someItems,otherItems]);
const merged = source.pipe(mergeMap( q => forkJoin(...q)));
return merged;

Comment: I understand it's your right to downvote the question, but could you please explain why so I have more grounds to improve my question?
Comment: hey there, did my answer solve your issue?
Comment: Thanks for your answer. I believe you might be right but it isn't the right syntax. I'm looking into toArray
Comment: I feel like it should work, but it still has a return type of Observable
Answer: For this situation, you can use the toArray() RxJS operator. According to the documentation, the toArray() operator

Collects all source emissions and emits them as an array when the source completes.

This is how your code should look like. Doing so will concatenate the returned observables into a single array.
import { forkJoin } from 'rxjs';
import { toArray } from 'rxjs/operators';

getSearchFeed(): Observable<items[]> {
   if (this.condition) {
     return this.populateItemsArray();            //function Returns Items Array Observable
   }

   //second condition
   const someItems = this.populateSearch();       //function Returns Items Array Observable
   const otherItems = this.populateOtherSearch(); //function Returns Items Array Observable

   return forkJoin(someItems,otherItems)
     .pipe(
       toArray(),
     );
}

Edit: I just noticed the return type, and that I should be flattening the returned observables into a single array. In that case, you can simply use Array.flat() within the map operator, and that should flatten it into a single array.
import { forkJoin } from 'rxjs';
import { map } from 'rxjs/operators';

getSearchFeed(): Observable<items[]> {
   if (this.condition) {
     return this.populateItemsArray();            //function Returns Items Array Observable
   }

   //second condition
   const someItems = this.populateSearch();       //function Returns Items Array Observable
   const otherItems = this.populateOtherSearch(); //function Returns Items Array Observable

   return forkJoin(someItems,otherItems)
     .pipe(
       map(res => res.flat(2))
     );
}

Comment: I think this is close but it is still off. To me this makes sense but when I try it the exact message I get when trying this is
Type 'Observable<(Items| [Items[], Items[]])[]>' is not assignable to type 'Observable'.
Comment: @ModestMonk hi! I just noticed the return type. In that case, my answer might be a bit off. Let me edit it..
Comment: I tried the second edit. It looks like that fails to flatten because it currently is an array of observables, not an array of items.


Automatic Node Expire / Unpublish with Renew Option

Question: I have a classifieds site and would like to have a node expire after 45 days (unpublished), no matter how many times the user edits and saves the node. However after the node expires, the user has the ability to renew (publish) for another 45 days. I would like the time to be strictly 45 days with simple a renew button when it is expired.
Here is the workflow:

User creates node
Email is sent to node author indicating successful post.
Node is automatically expired 45 days later.
Email is sent to node author indicating expired post.
User has the ability to easily renew ad (expiry date is 45 days later yet again)
Email is sent to node author indicating renewed post (different from step 2)

I would also like to have a countdown for the days remaining until the expiry date.
I have successfully built steps 1-4 using rules only, however the rules are based on the event 'After saving new content', which means when a node is republished/renewed the rules do not follow because it is not new content.
I have also tried using the Scheduler module to set the unpublish date but cannot figure out how to enable renew only after it has expired.
I have also tried Auto Expire but I think it only gives the ability to renew before it expires, not after.
Comment: How the author renew the ad?
Comment: Maybe the author can renew the add by clicking a button on the node edit page, or a renew URL link can be sent to the email address.
Comment: for simplicity it is better done in hook_cron. To expire, just unpublish it.
Answer: I would have opted for a custom code solution with the above work-flow.As an alternate contrib module option classified Ads module can be potential option.
Module Features:

Renewable expired ads during the 'grace period' Simple taxonomy-based
  browsing Ad expiration depending on category selection Per-user
  classified ads lists – custom lists totally sortable Length-limited
  body text with live counter of characters Advanced Help, CCK, Context,
  Panels, Token and Views support
Answer: This is an idea/suggested code but not solution. Use node_save to re-publish node.
$node = node_load($nid);
// set status property to 1
$node->status = 1;
// re-save the node
node_save($node);

Answer:
Create a button and display it in menu local task tab (along with node edit).
Once the user clicked the "Renew" button it will trigger the custom function that contains something like monymirza's answer.

Make sure that the "Renew" button is only visible to node owner only.
function renewAd() {
  $node = node_load($nid);
  // set status property to 1
  $node->status = 1;
  // re-save the node
  node_save($node);
}

See this thread on how to get the nid from URL.
Get a node ID from the URL


Capitalizar string com caracteres acentuados

Question: Estou com um problema ao salvar palavras com acentos no MYSQL.
Meu banco está todo setado em ut8_unicode_ci e nas minhas páginas php tem <meta charset="utf-8">.
Isso resolveu meu problema inicial com acentos, porém queria que os dados fossem salvos no banco apenas com a primeira letra de cada palavra maiúscula.
Encontrei a função ucwords() que resolveu meu problema, o usuário do sistema poderia digitar o nome do cliente todo em caixa alta que o sistema salva do jeito que eu queria no banco.
O problema é que se houver acentos no nome ele salva só até a última letra antes do acento. Ex: Se o nome for João da silva ele salva apena Jo. Gostaria de alguma ajuda com isso pois já estou há algum tempo pesquisando e ainda não consegui resolver isso. Segue abaixo um trecho do código:
function InsereMensalista()
{
    //TRAS AS VARIÁVEIS PARA O ESCOPO DA FUNÇÃO.
    global $conn, $nome, $email, $cpf, $rg, $tel, $celular, $celular2, $estado, $endereco, $bairro, $cidade, $placa1, $modelo1, $placa2, $modelo2, $mensalidade;

    //MUDA AS VARIÁVEIS PARA MINÚSCULO.
    $nome = strtolower($nome);
    $endereco = strtolower($endereco);
    $bairro = strtolower($bairro);
    $cidade = strtolower($cidade);
    $modelo1 = strtolower($modelo1);
    $modelo2 = strtolower($modelo2);

    // MUDA AS VARIÁVEIS COLOCANDO A PRIMEIRA LETRA DE CADA PALAVRA EM MAIÚsCULO ANTES DE INSERIR NO BANCO DE DADOS.
    $nome = ucwords($nome);
    $endereco = ucwords($endereco);
    $bairro = ucwords($bairro);
    $cidade = ucwords($cidade);
    $modelo1 = ucwords($modelo1);
    $modelo2 = ucwords($modelo2);

    //QUERY PARA INSERIR DADOS DIGITADOS NO FORMULÁRIO NO BANCO DE DADOS.
    $sql = "INSERT INTO mensalistas (id, nome, email, cpf, rg, telefone, celular, celular2, endereco, bairro, cidade, estado, placa1, modelo1, placa2, modelo2, mensalidade)
    VALUES ('','$nome','$email','$cpf','$rg','$tel','$celular','$celular2','$endereco','$bairro','$cidade','$estado','$placa1','$modelo1','$placa2','$modelo2','$mensalidade')";

    //TENTA INSERIR OS DADOS NO BANCO DE DADOS.
    if($result = $conn->query($sql))
    {
        //EXIBE UM AVISO DE QUE O CADASTRO FOI EFETUADO COM SUCESSO.
        echo " ";
    }
    else
    {
        //EXIBE UM AVISO DE QUE O USUÁRIO TENTOU INSERIR DADOS JÁ REGISTRADOS NO BANCO DE DADOS.
        echo " ";
    }
}

Comment: O problema é com o ucwords acredito eu. O que o `mysqli_real_escape_string` influencia?
Comment: Já experimentaste o `mysqli_real_escape_string` ?
Comment: @Weverton, pelos meus testes e bem provavel que não seja o ucwords o causador do seu problema, veja o teste: https://ideone.com/XfjzKQ você já tentou ir printando parte por parte do seu código para ver onde a informação se perde ?
Comment: Então estou testando aqui percebi que o problema é no strtolower(). Só com o ucwords ele gravou normal, inseri os dados: "joao, joão, Joao, João, JOAO, JOÃO" e ele gravou no mysql isso: Joao, João, Joao, João, JOAO, JOÃO" Ou seja colocou a primeira letra maiúscula corretamente, o problema é que eu não queria que ele salvasse o nome todo em caixa alta. Se o usuário digitar "JOÃO" ele teria que salvar "João", pra isso usei o strtolower(), e ai ele salva só "Jo".
Comment: Dê uma olhada nesta api também: https://market.mashape.com/semantics/accentwords
Answer: ucwords() é uma das funções para manipulação de strings do php que não suporta multibyte por isso ela não consegue converter caracteres acentuados ou de outras linguas.
Para cada função que manipula string existe uma cópia que trabalha com caracteres multibyte, essas funções tem o prefixo mb.
Para capitalizar sua string use a função mb_convert_case e informe o segundo argumento como MB_CASE_TITLE outras opções são MB_CASE_UPPER e MB_CASE_LOWER
<?php

$str = 'teste éverdade bla bla óooo ýabc';
echo mb_convert_case($str,  MB_CASE_TITLE);
echo ucwords($str);

Saída:
Teste Éverdade Bla Bla Óooo Ýabc
Teste éverdade Bla Bla óooo ýabc

Comment: @rray, se ele tiver problemas, a única coisa que você precisa fazer é passar o terceiro parâmetro, que é a codificação. Sendo assim: `mb_convert_case($str,  MB_CASE_TITLE, 'utf-8')`
Comment: Até agora não entendi para que você quer usar ucwords, sendo que já tem `mb_convert_case`.  É desnecessário fazer isso, @WevertonJúnior. Essa função que o @rray falou tem que funcionar corretamente, ou então está havendo um erro de comunicação
Comment: Tentei mas não deu certo cara coloquei outra resposta pra vc ver. Obrigado.
Comment: Cara com base na sua resposta resolvi pesquisar sobre a função mb_strtolower e consegui resolver meu problema. $nome = mb_strtolower($nome,'UTF-8'); Deu certinho muito obrigado mesmo.
Comment: @WevertonJúnior porque converter para minusculo?
Comment: +1 Essa função é utilizada internamente pelo Laravel, no método `Str::title`
Comment: @rray eu preciso converter para minúsculo porque não quero que salve no banco tudo em caixa alta. Só com o ucwords se o usuário digitar o nome do cliente: JOÃO SILVA eu preciso que salve no banco sempre João Silva. A função ucwords funcionou bem mudando "joão silva" para "João Silva" mas se o usuário digitasse tudo em caixa alta o problema ocorria justo na hora de usar a strtolower() em palavras com acento, e o BD salvava só "Jo". Mas seguindo sua explicação das funções mb_ cheguei nesse resultado que resolveu meu problema: $nome = ucwords(mb_strtolower($nome,'UTF-8')); Obrigado mais uma vez.
Comment: @WevertonJúnior é so usar o mb_convert_case, não precisa do mb_strlower, faz um teste simples, `echo mb_convert_case('AÇÃO', MB_CASE_TITLE);`
Comment: Então @rray, colocquei jeito que você falou (copiei e colei) e ele exibiu na tela "A??ÃO e quanto coloquei $nome = mb_convert_case('AÇÃO', MB_CASE_TITLE) ele gravou só A no BD. Mas não sei bem porque da outra forma: $nome = ucwords(mb_strtolower($nome,'UTF-8')); Funcionou perfeitamente.
Comment: @WevertonJúnior, pode ser o encode do seu arquivo, ele deve estar como utf-8


Interviews of famous modern mathematicians

Question: I was wondering, are there any good collections of interviews of famous modern mathematicians? It can be text interviews, or audio or video recordings.
I am not sure what exactly I mean by "modern". It just feels that mathematics in the last, say, 20 years is different than before in the sense that it is getting more and more abstract, and different mathematical fields become further away from each other. So it seems that now more people are trying to find concrete (or at least more concrete) applications of advanced theories, and also to relate different mathematical subjects, other than to solve hard problems within a field. (This may be completely wrong, this is just an impression I have now ). Therefore, it seems that modern mathematicians have a different approach to math, and it is very interesting to read about their vision of math in interviews.
I have read some very nice interviews by Manin, Kontsevich, Voevodsky, Arnold and some others, but I have found them accidentally. So if you have links to some websites collecting interviews with modern mathematicians, I would really appreciate that!
Thank you very much! I hope this question is appropriate here!
Edit: I have found this very nice collection of interviews, collected by E.Dynkin.
Answer: The Simons Foundation has a number of lengthy high-quality interview videos in its Science Lives section. Most of these mathematicians did their main work more than 20 years ago. Their influence on modern mathematics surely is significant.
Current listing:

Alfred Aho
Michael Atiyah
Sydney Brenner
Egbert Brieskorn
Alexandre Chorin
John Conway
Pierre Deligne
Michael Freedman
Phillip Griffiths
Friedrich Hirzebruch
Richard Karp
Robion Kirby
Peter Lax
László Lovász
Robert D. MacPherson
Yuri Manin
John McCarthy
Dusa McDuff
John W. Milnor
Cathleen Morawetz
John Nash
Louis Nirenberg
Paul Sally
Isadore Singer
James D. Watson
Margaret Wright
Chen-Ning Yang
Comment: proverb: "One live idiot is worth more than a hundred dead geniuses."
Answer: This is a book and very interesting: Mathematical People: Profiles and Interviews by Albers & Alexanderson. http://www.amazon.com/Mathematical-People-Interviews-Donald-Albers/dp/1568813406.
That besides Notices of the AMS has a series of interviews conducted by Christian Skau and another mathematician whose name I don't recall. You can check the Notices site.
Answer: Samuel Hansen has an ongoing audio interview series with mathematicians called Strongly Connected Components - currently at 55 interviews.
A few years ago I did a series of short audio interviews with mathematicians called Travels in a Mathematical World.
Tony Mann did a short series of interviews with mathematicians and historians of mathematics called Being a Professional Mathematician.
Comment: Ah, even though this is a resource request, I can only post two links because I am new. Tony's link is http://www.beingamathematician.org/Mathematicians.html
Answer: Something can be found here: http://celebratio.org/ (in particular there is a very nice interview with Michael Freedman)
Here there is an interview with S. Smale: https://www.youtube.com/watch?v=LmpPUjOeMGI
Here's one with M. Atiyah: https://www.youtube.com/watch?v=dToui7IVwBY
with T. Tao: https://www.youtube.com/watch?v=WGe-nGZLENU
Moreover on Youtube you can find plenty interviews with C. Villani.
Answer: The Clay Mathematics Institute interviewed Terence Tao in this report.
Answer: An interview with J.P. Serre. I found it to be very nice.
Answer: Even though this is a book of essays
rather than interviews,
I found it quite interesting:
"Discrete Thoughts: Essays on Mathematics, Science and Philosophy"
by Mark Kac, Gian-Carlo Rota, Jacob T. Schwartz
An entertaining counterpoint is
"Indiscrete Thoughts"
by Gian-Carlo Rota.
Answer: Interview of Karen Uhlenbeck, first woman to win Abel Prize, it is indeed quite inspiring and thorough
http://celebratio.org/Uhlenbeck_K/article/634/
Answer: An interview with Steve Stogarts: http://grantwiggins.wordpress.com/2012/12/07/math-as-artistry-an-interview-with-steve-strogatz-mathematician/
Answer: AMS notices interviews:
https://www.google.com/search?q=interview+site:www.ams.org/notices
Asia Pacific Mathematics Newletters interviews:
https://www.google.com/search?q=interview+www.asiapacific-mathnews.com/
Clay institute interviews
https://www.google.com/search?q=interview+www.claymath.org
Answer: Interview  with  You tuber Richard Borcherds (Fields Medalist)
Interview Date Mar $17, 2021$
video link


Is there a more elegant way to apply conditions in nginx?

Question: Is there a better way to do this? I can't find a way to nest or apply boolean operators to conditions in nginx.
Basically if there is a cookie set(non-anonymous user) we want to hit the server. If the cookie is not set and the file exists we want to server the file otherwise hit the server.
        set $test "D";
        if ($http_cookie ~* "session" ) {
            set $test  "${test}C";
        }
        if (-f $request_filename/index.html$is_args$args) {
            set $test  "${test}F";
        }
        if ($test = DF){
            rewrite (.*)/ $1/index.html$is_args$args?
            break;
        }
        if ($test = DCF){
            proxy_pass http://django;
            break;
        }
        if ($test = DC){
            proxy_pass http://django;
            break;
        }
        if ($test = D){
            proxy_pass http://django;
            break;
        }

Comment: small note: http://wiki.nginx.org/IfIsEvil
Answer: location / {
    if ($cookie_session) {
        proxy_pass http://django;
    }
    try_files $uri/index.html$is_args$args @django;
}

location @django {
    proxy_pass http://django;
}

Answer: location / {
    if ($cookie_session) {
        rewrite ^ /django/;
    }
    if (-f $request_filename/index.html$is_args$args) {
        rewrite (.*)/ $1/index.html$is_args$args; #did you mean ; instead of ?
    }
    proxy_pass http://django;
}
location /django/ {
    proxy_pass http://django;
}

Not sure if much better, but avoided using things considered unsafe in the if statements.
Comment: You don't need the rewrite capture, nginx already does that for you in $request uri. rewrite ^ /django$request_uri;
Comment: Edited per @Martin Fjordvald rec.


How can I add/remove elements based on total count of element value of another element value in Javascript

Question: I am trying to add/remove elements from array based on total count of another value.
let data = [
    {
  "details": [
    {
      "Name": "DataSet1",
      "Severity": "4",
      "Cost": 20
    },
    {
      "Name": "DataSet2",
      "Severity": "4",
      "Cost": 30
    },
    {
      "Name": "DataSet3",
      "Severity": "4",
      "Cost": 25
    }
  ],
  "charge": 45
}
];

Here, I am trying to get an array such that total value of Cost is near to charge. Here, Sum of Cost is 75 which is greater than 45, so I tried like below:

Calculate difference between charge and total cost, If it's greater than charge, then remove elements from array, such that new array total cost always less or near to charge. So, my new array should be:

let newdata = [
    {
  "details": [
    {
      "Name": "DataSet1",
      "Severity": "4",
      "Cost": 20
    },
    {
      "Name": "DataSet3",
      "Severity": "4",
      "Cost": 25
    }
  ],
  "charge": 50
}
];

Is there any better way to do this? Does Javascript have any built-in functionality that does this?
Comment: Better than what? And no, this sounds like a very specific scenario. You'll have to use loops to loop over the `details` array and determine what entry in the array should be removed. Could you show your attempt?
Comment: Better than using multiple loops.
Answer:

const data = {
  "charge": 50,
  "details": [{
      "Name": "DataSet1",
      "Severity": "4",
      "Cost": 20
    },
    {
      "Name": "DataSet2",
      "Severity": "4",
      "Cost": 30
    }, {
      "Name": "DataSet3",
      "Severity": "4",
      "Cost": 25
    }
  ],
};
const getItemsAndDontGoAboveCharge =
  (charge, list, start = 0, currentCost = 0, result = []) => {
    if (start === list.length) return result
    const {
      Cost
    } = list[start]
    const nextTotal = currentCost + Cost
    if (nextTotal > charge) return result
    return getItemsAndDontGoAboveCharge(charge, list, start + 1, nextTotal, [...result, list[start]]);
  }

console.log(getItemsAndDontGoAboveCharge(data.charge, data.details))
Comment: It worked, thanks! For my learning, Is there any other alternative way to get this using slice and reduce functions?
Comment: there is, but it's not great since filter/reduce traverse the WHOLE array, and there's no way to stop them. So you'll end up traversing items you don't need which obviously isn't good for performance


Seria "Promise.all" (e outras funções similares) um exemplo de paralelismo em JavaScript?

Question: Em JavaScript, temos o Promise.all, que resolve um array de promessas em uma única Promise. Esse processo é aparentemente paralelo, já que as promessas são resolvidas ao mesmo tempo, e não de forma linear.
Além do Promise.all, outras funções como Promise.allSettled e Promise.race também possuem um comportamento similar de executar as promessas "ao mesmo tempo", resolvendo em uma só Promise.
Mas isso realmente é um tipo de paralelismo no JavaScript? Como isso realmente funciona?

Um exemplo que compara as promessas resolvendo-se de forma linear e paralela, respectivamente:

// Irá demorar 500ms para dobrar o número.
const double = (num) => new Promise((resolve) =>
  setTimeout(() => resolve(num * 2), 500)
);

(async () => {
  const doubles = [];

  const start = Date.now();
  for (let i = 1; i <= 5; i++) {
    doubles.push(await double(i));
  }

  console.log(doubles);
  console.log(`Finished in ${Date.now() - start}ms.`);
})();

const double = (num) => new Promise((resolve) =>
  setTimeout(() => resolve(num * 2), 500)
);

(async () => {
  const nums = Array.from({ length: 10 }).map((_, i) => i + 1);

  const start = Date.now();
  const doubles = await Promise.all(nums.map(double));

  console.log(doubles);
  console.log(`Finished in ${Date.now() - start}ms.`);
})();
Comment: O JavaScript não é multithread, sendo assim, não tem como ocorrer o paralelismo (que é a execução **simultânea**). O que acontece é que os códigos são executados **alternadamente**, enquanto é esperado a execução do callback do `setTimeout` outras coisas podem ser executadas. O 1° `await` diz que o retorno da função deve ser aguardado para então continuar o loop, enquanto o 2° cria as promessas e depois aplica a espera, ou seja, no 1° cria e espera o retorna de cada promessa antes de ir pra próxima, no outro, a espera é aplicada depois que todas promessas são iniciadas e já estão esperando
Answer: Na verdade, o paralelismo (ou inexistência dele) reside nas promises em si, não no Promise.all(). O trabalho de uma promise começa quando ela é criada, o que Promise.all(doubles) faz é criar uma promise que finaliza sua execução assim que todas as promises recebidas (doubles) foram finalizadas.
No primeiro trecho de código você chama
doubles.push(await double(i))

dentro do loop, obrigando cada ciclo esperar a resolução da promise, mas não precisa fazer isso; poderia chamar
doubles.push(double(i))

permitindo que double() comece a executar assincronamente, quiçá de forma concorrente; e depois fazer await na promise criada com Promise.all(doubles).
Uma das grandes vantagens de usar Promise.all() é receber uma exceção mais cedo se alguma promise falhar, além de esperar no máximo o tempo da promise mais demorada dentro de doubles.
O Node.js possui um thread pool interno para que operações assíncronas bloqueantes possam correr em paralelo. Mas esse pool está fora do alcance do código Javascript. Promises e operações assíncronas que sejam implementadas em Javascript puro (sem invocar um módulo escrito em C++ que poderia fazer uso da thread pool) não poderão executar de forma concorrente.


hook_inline_entity_form_table_fields_alter add custom field

Question: Need some help with Inline Entity Form hook function hook_inline_entity_form_table_fields_alter.
I'm trying to add columns to the table that is visible when editing a specific node. I have been able to add fields and got the content to print too, but I need to add a checkbox. I've unfortunate not been able to find how to add other custom fields, so I wonder if someone has used this function before?
I guess it would be possible to add a "checkbox" fields to the content type itself, but in this case its more like a function rather than a value that I want to save.
Best,
Fever
Answer: Add the checkbox field to the referenced entity. Also, as an alternative you could use ief_table_view_mode module instead of hook_inline_entity_form_table_fields_alter and then set the fields that should be displayed in the table on the referenced entity in the Entity form table view mode.


In Whitehead & Russell's PM, what makes anything true or false?

Question: It seems that truth and falsehood are fundamental to meanings and types. A proposition is defined as anything that is true or that is false.
PM defines truth as "consisting in the fact that there is a complex corresponding to the discursive thought which is the judgement."* If I'm not mistaken, truth is not one of PM's primitive ideas. In Chapter IV of 1st ed introduction, the reason for pronouncing "$\{(x).\phi(x)\}$ is a man" as meaningless appears rather arbitrary.
I wonder if W&R assumed that the notion of truth is well-known. If so, whose definition were they referring to?
*Chapter II.Tuth and Falsehood.
Comment: I can't comment expertly on PM, but it is a theorem due to Tarski that truth cannot be defined within a formal system implementing arithmetic in a way corresponding to truth in the standard model of arithmetic. This is why modern logic concerns itself more with provability.
Comment: I think you might do better to ask this question on http://philosophy.stackexchange.com
Answer: From the point of view of "logical machinery", we can say that PM assumes "true" and "false" as two undefined concepts that we are able to manage in the context of logic and mathematics.
See the definition of truth-values, page 8 :

The "truth-value" of a proposition is truth if it is true and falsehood if it is false.

In pages 45-on, there is an attempt to define the concepts : truth and falsehood.
The context, as you already noted, is the "act of judgement", involving a mind and several interconnected objects. True is a "property" of the judgement :

When the judgement is true, [...] there is a corresponding complex of the objects of the judgement alone. Falsehood, [...] consists in the absence of a corresponding complex composed of the objects alone.

This seems an enunciation of The Correspondence Theory of Truth  :

Narrowly speaking, the correspondence theory of truth is the view that truth is correspondence to a fact — a view that was advocated by Russell and Moore early in the 20th century.
The correspondence theory is often traced back to Aristotle's well-known definition of truth (Metaphysics 1011b25):

"To say of what is that it is not, or of what is not that it is, is false, while to say of what is that it is, and of what is not that it is not, is true"

but virtually identical formulations can be found in Plato (Cratylus 385b2, Sophist 263b). It is noteworthy that this definition does not highlight the basic correspondence intuition. Although it does allude to a relation (saying something of something) to reality (what is), the relation is not made very explicit, and there is no specification of what on the part of reality is responsible for the truth of a saying.
Aristotle sounds much more like a genuine correspondence theorist in the Categories (12b11, 14b14), where he talks of "underlying things" that make statements true and implies that these "things" (pragmata) are logically structured situations or facts (viz., his sitting, his not sitting). Most influential is his claim in De Interpretatione (16a3) that thoughts are "likenessess" (homoiosis) of things. Although he nowhere defines truth in terms of a thought's likeness to a thing or fact, it is clear that such a definition would fit well into his overall philosophy of mind.

Apart from all metaphysical implications regarding objects (what they are ?) and their "interconnections" into complex (what are relations ?), this basic account - as noted in Kevin's comment above - can be compared to well-known Tarski's Truth Definition.
Comment: I agree that mathematics can manage without a precise definition of truth and falsehood because it deals with implications, not empirical evidence for the truth of a proposition.
Comment: Still, I think it's hard to sum up a generic rule that decides what makes a proposition meaningless. Maybe, we can imitate empirical science and decide such matters case by case.
Comment: Correspondence theory is a sound criterion. Yet there are sentences which, at first sight appear to be meaningless, turn out to be capable of being true or false after clever analysis. E.g., "the so-and-so" ...


Como printar uma função no Python?

Question: Estou tentendo fazer essa código funcionar mas não to conseguindo.
Entra o nome e o ano de nascimento, e retorna os valores corretos dps, mas não to conseguindo voltar o numero de anos... Qual é o meu erro?
print 'Digite seu nome:'
nome = raw_input()

print 'Digite o seu ano de nascimento:'
ano = raw_input()

def ano_covertido(idade):
    ano = raw_input()
    ano_covertido = int(ano)
    ano_atual = date.today().year
    ano_atual - ano

print 'Bem vindo %s' % (nome)
print 'Voce tem %s de idade' % (idade)

Answer: A função ano_covertido não está sendo executada, e ela também não retorna nenhum resultado.
ano_covertido deve ser parecido com isto:
def ano_covertido(ano):
    # Pega o ano do dia atual
    ano_atual = date.today().year
    # Retorna a diferenca entre o ano atual e informado na funcao
    return ano_atual - ano

Para pegar a entrada do usuário, faça assim:
# Guarda em "nome" a entrada do usuario
nome = raw_input('Digite seu nome:')
# Guarda um inteiro em "ano"
ano = int(raw_input('Digite o seu ano de nascimento: '))

Agora que você sabe o ano, chame a função:
idade = ano_covertido(ano)

Finalmente, mostre as informações ao usuário:
print ('Bem vindo %s' % (nome))
print ('Voce tem %s de idade' % (idade))

O código completo fica assim:
from datetime import date

def ano_covertido(ano):
    ano_atual = date.today().year
    return ano_atual - ano

nome = raw_input('Digite seu nome:')

ano = int(raw_input('Digite o seu ano de nascimento: '))

idade = ano_covertido(ano)

print ('Bem vindo %s' % (nome))
print ('Voce tem %s de idade' % (idade))

Como printar uma função no Python?


Topological "closure" of a binary relation

Question: Let $f$ be a binary relation on a set $U$.
Topology $T f = \{ E \in \mathscr{P} U \mid
f [E] \subseteq E \}$ (here $f[E]$ is the image of a set $E$ by binary relation $f$).
Conjecture Closure operator $\operatorname{cl}$ of $T f$ is equal to $E \mapsto ( \operatorname{id}_U \cup f \cup
  f^2 \cup f^3 \cup \ldots ) [E]$.
Comment: @CliveNewstead $g\circ f = \{ (x,z) \mid \exists y: (x,y)\in f\land (y,z)\in g \}$. $f^n = f\circ\dots\circ f$ ($n$ times).
Comment: @CliveNewstead Binary relation is a set of pairs, by definition
Comment: Ah ha! Thanks. I need to check my glasses. I guess I assumed it was a function because you called it $f$ ;)
Comment: $E \mapsto ( \operatorname{id}_U \cup f \cup f^2 \cup f^3 \cup \ldots ) [E]$ maps open sets to itself. So, it can be closure only if all open sets are closed. It remains to find a counterexample $f$.
Answer: $E \mapsto ( \operatorname{id}_U \cup f \cup f^2 \cup f^3 \cup \ldots ) [E]$ maps open sets to itself. So, it can be closure only if all open sets are closed.
For a counterexample for the conjecture take $f = \{ (0, 0), (1, 1), (0, 1) \}$. Open sets are $\{ \}$, $\{ 1 \}$, $\{ 0, 1 \}$. $\{ 1 \}$ is open but not closed.


Pointwise convergence in limit of conditional probabilities implies almost sure convergence?

Question: Consider two sequences of real valued random variables $\{X_n\}_{n\in \mathbb{N}}$ and $\{Y_n\}_{n\in \mathbb{N}}$, with, $\forall n \in \mathbb{N}$, $X_n$ and $Y_n$ defined on the probability space $(\Omega, \mathcal{F}, P), $ respectively with support $\mathcal{X}, \mathcal{Y}$. Consider a sequence of real numbers $\{a_n\}_{n\in \mathbb{N}}$.
Assume that for some $b\in \mathbb{R}$
$$
\lim_{n\rightarrow \infty} | \overbrace{P(X_n\leq b| Y_n=y)}^{\text{scalar}}-a_n|=0 \text{ }\text{ $\forall y \in \mathcal{Y}$}
$$
Does this imply
$$
\overbrace{P(X_n\leq b| Y_n)}^{\text{Random variable because of $Y_n$ (unless $X_n\perp Y_n$)}}-a_n \rightarrow_{a.s.}0 \text{ as $n\rightarrow \infty$}
$$
?
Comment: Sorry, but I don't know how $P(X_n\le b|Y_n)$ is defined.
Comment: Yes, what you wrote is correct.
Comment: Yes, you are correct.
Comment: I think the answer is yes because almost sure convergence by definition means that $P(\omega \in \Omega \text{ s.t. } \lim_{n\rightarrow \infty} |P(X_n\leq x| Y_n=Y_n(\omega))-a_n| =0)=1$ which I think it is implied by pointwise convergence in limit
Comment: But I have doubts since I get always confused with conditional probabilities. Could you confirm this?
Comment: I don't think that it's true but I cannot imagine a counter-example right now.
Comment: Ok. Then, what is the relation between the two objects?
Comment: @LandonCarter Thank you. I also think that the claim does not go the other way around, i.e., almost sure does not imply pointwise convergence in limit. Correct?
Answer: Given:
$$\forall y \in \mathcal Y, \lim_n \frac{E[1_{B_n} 1_{Y_n=y}]}{P(Y_n=y)}= \lim_n a_n$$
Conjecture:
$$\lim_n E[1_{B_n}| Y_n]= \lim_n a_n$$
Ugh, the fact that we can say '$Y_n=y$' means $Y_n$ is discrete? In that case:
$$E[1_{B_n}| Y_n] = \sum_{y \in \mathcal Y} E[1_{B_n}| Y_n = y]1_{\{Y_n=y\}}$$
$$\to \lim E[1_{B_n}| Y_n] = \lim \sum_{y \in \mathcal Y} E[1_{B_n}| Y_n = y]1_{\{Y_n=y\}}$$
$$= \sum_{y \in \mathcal Y} \lim E[1_{B_n}| Y_n = y]1_{\{Y_n=y\}}$$
$$ = \sum_{y \in \mathcal Y} [\lim E[1_{B_n}| Y_n = y]][\lim[1_{\{Y_n=y\}}]]$$
$$ = \sum_{y \in \mathcal Y} [\lim a_n] \lim[1_{\{Y_n=y\}}]$$
$$ = [\lim a_n] \sum_{y \in \mathcal Y} \lim[1_{\{Y_n=y\}}]$$
Well if I proved for the discrete case, then it would not have been sufficient to disprove as a whole. However, I disproved for the discrete case which is sufficient to disprove as a whole.

Observation: In the discrete case, this sounds like:
$$\lim_n b_{n,k} = \lim_n a_n \to \lim_n \sum_{k} b_{n,k}c_k = \lim_n a_n$$