Mean of overcooking time

Question: This question came up this week when I had to put my rice in the microwave for a third time.
Suppose the perfect cooking time for a meal is given by a random variable $X$ with values in seconds. Now suppose a quick check allows to determine if the food is :

Uncooked,
Perfectly cooked,
Overcooked.

What is the estimated overcooking time in seconds if one uses the following technique :
Start by cooking for $T$ seconds, then
a) Check food state.
b) If food if perfectly cooked or overcooked, stop.
c) If food is uncooked, double the last $T$ used.
An answer could also hint for a better technique or optimize the choice of $T$.
EDIT : As suggested bellow, let us assume that $X\sim N(\mu;\sigma^2)$.
Comment: Can you clarify the algorithm?  Are you checking every $T$ seconds, or are you doubling the cooking interval sizes $\{T, 2T, 4T, 8T, ...\}$, or is the first cook interval $T$ and the remaining ones $2T$? [In other words, does "cook for $2T$ seconds" mean "cook for $2T$ more seconds" or "cook for $T$ more seconds"?]
Comment: I thought $X$ was a discrete r.v., but now it says $X$ is Normal, and remember Normal r.v.'s are supported on the whole real line.  In any case, a Normal seems inappropriate because the cooking time can't be negative.  Maybe logNormal would be a good place to start.
Comment: Quite apart from any mathematical considerations, I have good luck putting my rice in an all-glass container (not even the lid is plastic); the glass lid vents just enough to steam the rice properly.
Comment: A harder problem would suppose that each time one checks the food, one looses $L$ seconds of cooking. Or $p$ percents of cooking.
Comment: This question is not really answerable without a prior distribution of $X$ (there is no uniform distribution on $\mathbb{Z}$)
Comment: Still one could express the answer in terms of P(X=k)? Or answer for common distributions.
Comment: The overcooking time is given by various formulas equivalent to $$T\mathbf 1_{X=0}+\sum_{n=1}^\infty(nT-X)\mathbf 1_{(n-1)T<X\leqslant nT}$$
Comment: To judge whether cooked or not, you need an acceptable range of error, say a percentage within the perfect cooking time within which the rice is considered perfect - say $+-5\%$ as probabiltiy of being exactly right is zero.
Comment: I second Michael's question in the comment above. It is not clear what the checking algorithm is. Also in your edit you assume **T** to be normally distributed. Do you mean **X**?
Comment: I made the suggested changes.
Comment: Why would one _double_ the cooking time if, on checking, it is not yet cooked? What is the cost of checking more often? What are the costs of overcooking (throw it out?) and undercooking (salmonella?).  Why would you eat food from a microwave? :)
Comment: Let's say that checking is unpleasant and overcooking is too. So one would like to minimise the number of checks and the overcooking time. I fixed the research algorithm so we only have to minimize the overcooking time.
Answer: This is not a complete answer, but it is too long to fit in the comments. (No reference here to a similar sentence by a chap named Fermat.)
Let $\{ t_n \}_{n=1}^N$ be the sequence of times at which you plan to stop and check, where $N$ may be finite or infinite. In your question, for instance, this is defined recursively as $a_1 = T$ and $a_n = a_{n-1} + T$.
(Incidentally, for well-behaved distributions, I'd expect that it is better to have $a_n - a_{n-1}$ decreasing, because the longer you have cooked, the higher the risk of overcooking.)
Let $X$ the "perfect time". If $X \le a_1$, you stop cooking at $a_1$: this occurs with probability $P(X \le a_1)$ and gives you an expected overcooking time $E(a_1-X|X\le a_1)$. If If $a_{n-1} < X \le a_n$, you stop cooking at $a_n$: this occurs with probability $P(a_{n-1} < X \le a_n)$ and gives you an expected overcooking time $E(a_n-X|a_{n-1}<X \le a_n)$.
Define $a_0=0$ for convenience. Adding up across all cases, the formula for the expected overcooking is
$$\sum_{n=1}^N P(a_{n-1} < X \le a_n) E(a_n-X|a_{n-1}<X \le a_n)$$
For instance, if $X$ is uniformly distributed between 0 and 100 and we take $T=1$ in your checking schedule and thus $N=100$, we find
$$\sum_{n=1}^N P(a_{n-1} < X \le a_n) E(a_n-X|a_{n-1}<X \le a_n) = \\ \sum_{n=1}^{100} \frac{\left(n - (n-1) \right)}{100} E(n-X|n-1<X \le n) = \\ \sum_{n=1}^{100} \frac{1}{100} E(n-X|n-1<X \le n) = \\ \sum_{n=1}^{100} \frac{1}{100} \frac{1}{2} = \frac{1}{2}$$
Answer: The answer is the remainder of $\frac{\mathbb{E} X}{T}.$  This is essentially the overshoot that you expect based on the step length $T$.  In particular, if $X \sim N(\mu, \sigma^2)$, then this would be the remainder of $\frac{\mu}{T}.$ If $X$ is a discrete r.v. with probabilities $p_1, \dots, p_n$, then the expected overcooking time is the remainder of $\frac{\sum_n p_n x_n}{T}.$
The choices of $T$ that lead to zero expected overcooking time are contained in the set $\{\frac{\mathbb{E} X}{  k }\mid k \in \mathbb{N} \}.$
Something interesting is that no matter what we choose for $T$, even if the expected overcooking time is zero, the wait time will still have a variance of $\mathbb{E}(kT-X)^2, $ where $k = \text{argmin} \{k \in \mathbb{N} \mid kT \ge X\}$.  In particular, when $X \sim N(\mu, \sigma^2),$
$$
\mathbb{E}(kT-X)^2 = T^2 \mathbb{E} k^2 - 2T \mathbb{E} kX + \sigma^2.
$$
This is where I will leave my answer, mostly because I don't know what the distribution of $k$ should be.  The formula for variance that I found does shed some light on the problem -- evidently the variance is quadratic in $T$.  In other words, the more often we check, the less variance we expect in our wait time at the expense of opening and closing the microwave door many times.

Mean of overcooking time


NullReferenceException em C#

Question: Estou com um problema em C#, estou me deparando com uma exceção e não consigo reconhecer o porque da mesma
Detalhes da Exceção:

System.NullReferenceException: "Referência de objeto não definida para uma instância de um objeto."

Trecho de código que lança a exceção é:
public void AdicionarCliente(String nome, String sobrenome)
{
    Clientes.Add(new Cliente(nome, sobrenome));
}

Na classe:
public sealed class Banco
{
    private static readonly Banco instance = new Banco();
    public static Banco Instance
    {
        get
        {
            return instance;
        }
    }

    private List<Cliente> Clientes;

    private Banco()
    {
    }

    public void AdicionarCliente(String nome, String sobrenome)
    {
        Clientes.Add(new Cliente(nome, sobrenome));
    }

    public int GetNumeroDeClientes()
    {
        return Clientes.Count;
    }

    public Cliente GetCliente(int indice)
    {
        return Clientes[indice];
    }
}

Classe Cliente:
public class Cliente
{
    public String Nome
    {
        get;
        private set;
    }
    public String Sobrenome
    {
        get;
        private set;
    }
    private List<Conta> Contas { set; get; }

    public Cliente(String nome, String sobrenome)
    {
        this.Nome = nome;
        this.Sobrenome = sobrenome;
    }

    public Conta GetConta(int indice)
    {
        return Contas[indice];
    }

    public int GetNumeroDeContas()
    {
        return Contas.Count;
    }

    public void AdicionarConta(Conta c)
    {
        Contas.Add(c);
    }
}

Answer: Isso é porque a lista de clientes não foi instanciada.
Não tenho como saber qual é o momento certo de instanciá-la, mas se for logo na inicialização você pode fazer direto na declaração
private List<Cliente> Clientes = new List<Cliente();

NullReferenceException em C#


Joint density for exponential distribution

Question: Let $X_1$ and $X_2$ be independent random variables each having a exponential distribution with mean $\lambda = 1$.
(a) Find the joint density of $Y_1 = X_1$ and $Y_2 = X_1 + X_2$.
(b) Get the marginal density of $f_1(y_1)$ and $f_2(y_2)$.
$f(x_1)=e^{-x_1}$, $f(x_2)=e^{-x_2}$
Since $X_1$ and $X_2$ are independent, $f(x_1, x_2)=f(x_1)f(x_2)=e^{-x_1-x_2}$
However, how could I find the joint density?
I mean, it is quite easy to find marginal ones from the joint one, but how can I do the opposite?
Comment: Hello, welcome tot MSE! If you want to typeset mathematics in a proper way, you can use MathJax. In [this link](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) it is explained how to do use this.
Answer: Hint: Use the transformation theorem.
If $Y=(Y_1,Y_2),$ where $Y_1$ and $Y_2$ are as described by you, $Y=g(X)$, $X=(X_1,X_2)$, then:-
$f_Y(y)=|J(y)|f_X(g^{-1}(y))$, if $y$ is on g's range (and zero otherwise).
Note that $J$ is the jacobian of the inverse transformation, $g^{-1}(Y)$.
Answer: You needn't get the joint distribution from marginals. Unitarity is the result $\int_{[0,\,\infty]^2} e^{-x_1-x_2}dx_1 dx_2=1$. The Jacobian is $1$, so we can restate that as $\int_S e^{-y_2}dy_1 dy_2=1$, where $S$ is the subset of $[0,\,\infty]^2$ satisfying $y_1\le y_2$. Thus $e^{-y_2}1_S(y_1,\,y_2)$ is the joint pdf. I'll leave you to get the marginals from that.


Can the BOSS RC-600 be the master MIDI sync to the RC-300?

Question: So up to this point, the BOSS RC-300 can't be the MIDI tempo sync slave of anything other than another RC-300.
Can the new BOSS RC-600 be the master MIDI sync to the RC-300?
Looking at the manual online, I'm afraid the answer may be "no," but the manual doesn't show the menu trees, so maybe?
I'd like to know before I buy one because I already have an RC-300 and I'm planning on live-looping with another musician who would use my old RC-300.
Comment: Roland is a very helpful company. Send them an email.
Answer: The problem is that RC-300 has a product-specific way of slaving that only works with another RC-300 or time spent analyzing MIDI messages and programming a MIDI pedal. So the answer is no. The RC-600 can slave to any MIDI device and doesn't have this problem.


Why is a Hyperplane called a "Hyper"plane?

Question: I just had this curious question. In other fields, the word "hyper" is actually used to refer to something which is "over; beyond; above" as defined by Google. An example of such terms would be Hyperglycaemia, defined by Wikipedia as:

a condition in which an excessive amount of glucose circulates in the blood plasma.

Or Hypersonic, defined by Google as:

relating to speeds of more than five times the speed of sound.

So, my question is, what would be the motive to give a Hyperplane such a name when it is defined as :

a subspace of one dimension less than its ambient space
Comment: It is called a hyperplane because it is a *higher-dimensional* generalization of a *plane*, a two-dimensional subspace in the dimensions. See also *hypercube*, *hypersphere*, *hyperoctant*, etc.
Comment: Technically you can still talk about hyperplanes in $2$-d geometry: it's just that they also happen to be lines. One could call these hypo-planes if they wanted to maintain a distinction between lines and their duals :)
Comment: We can define hyperplanes as subspaces of codimension 1, from which it follows that hyperlines are subspaces of codimension two.
Answer: Adding hyper- helps the listener know that it is like a plane, and yet it might be more than just an ordinary 2-d plane.
From 3-d geometry, we think of planes as being 2 dimensional things in a 3 dimensional world. In regular Euclidean geometry, there is a unique plane normal to a line through a given point. Similarly, there is a unique line through a given point on a plane that's normal to the plane. We want to take this line-plane connection through to higher dimensions. That's why the definition of "hyperplane" says it is $n-1$ dimensional, because it is the orthogonal complement to a $1$ dimensional piece of the space.
Comment: [Wolfram MathWorld's Hyperplane Definition](http://mathworld.wolfram.com/Hyperplane.html): "More generally, a hyperplane is any codimension-1 vector subspace of a vector space. Equivalently, a hyperplane `V` in a vector space `W` is any subspace such that `W/V` is one-dimensional."


Asynchronous - My app is not work when I download it from app store?

Question: My app has a login page, people need to input a passcode,then they can login into inside. Everything of my app is work on my several iPhone before I submit it to iTuneConnect,then it has been approved by Apple. Something happened when I download it back from app store. Status of the HUD is always loading......It can not login into inside.
Here is my simple code:
<code>@synthesize threadCount = _threadCount;

- (void) initData
{
    _codeIsVaild = NO;
}

- (IBAction)Login:(id)sender
{
    _threadCount = 0;

    //Login procedure
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
        hud.labelText = @"Loading...";
        [hud showAnimated:YES whileExecutingBlock:^{

            [self getData];
            while (_threadCount != 5) {
                //Waiting for all tasks complete...It will be pass when the threads counter is equal 5
            }
        } completionBlock:^{

            if (_codeIsVaild)
            {
                //Password is Vaild
                [self performSegueWithIdentifier:@"loginsegue" sender:self];
            }
            else
            {
                //Show error Alert
            }
            [hud removeFromSuperview];
        }];
    }
}

-(void) getData
{

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    NSString *URLString = [APILink getData];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

    [manager POST:URLString parameters:paras
         success:^(AFHTTPRequestOperation *operation, id responseObject)
        {
            //Tasks
            [self taskone];
            [self tasktwo];
            [self taskthree];
            [self taskfour];
            [self taskfive];
            _codeIsVaild = YES;
        }
        else
        {
             _codeIsVaild = NO;
        }
            dispatch_semaphore_signal(semaphore);
        }
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        _codeIsVaild = NO;
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}

-(void) taskone
{
    NSString *URLString = [APILink taskoneAPIurl];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

    [manager POST:URLString parameters:paras
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             _threadCount += 1;
         }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             _threadCount += 1;
         }];
}

//Same as taskone,but get data from another url
-(void) taskTwo
-(void) taskThree
-(void) taskFour
-(void) taskFive
</code>
I think the problem is asynchronous tasks management. If that is the case, all of my phone should not be able to login.The strangest thing is that it works properly on my phone before I upload it to the app store, but it can not work properly when I download it from app store. What can I do? Thanks everyone.
Comment: Finally,I found a solution,refer to the URL: How to batch request with AFNetworking 2?

This indicates that the code can not wait for the results of several requests, the use of an endless loop to wait.

You should use dispatch_group_t & dispatch_group_notify

Thanks CirrusFlyer & everyone!

Have a good day!
Answer: Finally,I found a solution,refer to the URL: How to batch request with AFNetworking 2?
This indicates that the code can not wait for the results of several requests, the use of an endless loop to wait.
You should use dispatch_group_t & dispatch_group_notify
Thanks CirrusFlyer & everyone!
Have a good day!
Answer: I'd have to watch it through a debugger to offer any genuine help, but it sounds like you're not moving past either the getData() method or your while loop's stop condition is never met (my money is on the later as it doesn't appear you have a thread-safe variable to begin with ... a big no-no if your termination condition is based on it).
As a suggestion you might want to add some logging - something you can get to - to use for debugging purposes in addition to ensuring there are no race conditions.
Comment: I can not use the debugger problem downloading it from the app store later, so that's what I ask. But before I submitted to iTunes connect, everything is ok, debugger displays the results were normal.


I am trying to add a simple pager to my controller, I have managed to get the row limit (5) to be printed but not to see the next or the previous

Question: <?php

namespace Drupal\drupal_block\Controller;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Query\PagerSelectExtender;

class DrupalBlockController extends ControllerBase {
  protected $connection;

  public function __construct(Connection $connection) {
      $this->connection = $connection;
  }

  public static function create(ContainerInterface $container)
  {
      return new static(
          $container ->get('database')
      );
  }

  public function mymodule()
  {
    $data = $this->connection->select('custom_table', 'ct')
      ->fields('ct', ['name', 'lastname', 'sexo', 'email']);

  $pager = $data->extend(PagerSelectExtender::class)->limit(5);
      //$pager->setCurrentPage($page);
      $data = $pager->execute()->fetchAll();
      $rows = array();

      foreach ($data as $row){
        $rows[] = [
          'name' => $row->name,
          'lastname' => $row->lastname,
          'sexo' => $row->sexo,
          'email' => $row->email,
        ];
      }

    return [
      '#theme' => 'table',
      '#pager' => [
        '#type' =>'pager'
      ],
      '#header' => [
        $this->t('Name'),
        $this->t('Last Name'),
        $this->t('Gender'),
        $this->t('Email')
      ],
      '#rows' => $rows,
      ];
      }
    }

Answer: This:
return [
  '#theme' => 'table',
  '#pager' => [
    '#type' =>'pager'
  ],
  '#header' => [
    $this->t('Name'),
    $this->t('Last Name'),
    $this->t('Gender'),
    $this->t('Email')
  ],
  '#rows' => $rows,
];

Should be this:
return [
  'pager' => [
    '#type' =>'pager'
  ],
  'table' => [
    '#theme' => 'table',
    '#header' => [
      $this->t('Name'),
      $this->t('Last Name'),
      $this->t('Gender'),
      $this->t('Email')
    ],
    '#rows' => $rows,
  ],
];

Elements with hashtag prefixes are not rendered, they are metadata. So the hashtag needs to be removed from the array key.
The pager needs to be a separate render array from the table.


Find the probability mass function of $Y = X/2$ knowing that $X \sim Bin(n, 0.5)$.

Question: Given
$$X \sim Bin(n, 0.5)\ \ \text{with PDF}\ \ P(X=x)={n \choose x}\left(\frac{1}{2}\right)^{x}\left(\frac{1}{2}\right)^{n-x} = {n \choose x}\frac{1}{2^{n}},$$
how do I find the probability mass function $p(y) = P(Y = y)$ given that $2Y = X$?
$$2Y = X \iff Y = \frac{X}{2}$$
Answer: First note that what  you are looking for is NOT a density function but a Probability Mass Function.
If you are looking for the pmf of $Y=X/2$, it is always a binomial but with the modified support, thus
$$Y=\{0;0.5;1;1.5;\dots ;n/2\}$$
with the same probabilities as the starting Binomial:
$$\left\{\frac{1}{2^n};\frac{n}{2^n};\frac{n(n-1)}{2^{n+1}};\frac{n(n-1)(n-2)}{3\cdot2^{n+1}};\dots;\frac{1}{2^n}   \right\}$$
respectively


How exactly is climax defined?

Question: I am learning rules of counterpoints using this source. One of the rules there states:

The CF must have a unique culmination (climax).

I would like to be sure that I understand climax properly.
Does it only mean that there should be only one highest (or lowest) tone? Or the rule states more than that?
Comment: I'd give you the advice not only to read this theory but to load down some gregorian chants (the rules for the cantus firmus are adapted from them) and there are many examples by Fux and other counterpoint theorists  ( even  by Haydn and Mozart)

e.g.this https://www.mymusictheory.com/learn-music-theory/reference/579-counterpoint
Comment: That article seems to assume readers will be familiar with treatises from Fux, Jeppesen, etc. You need to read those books first before reading this article. Especially, if you are trying to learn traditional counterpoint, that article isn't the place to start.
Answer: When I looked up for cantus firmus and climax I got this link. It says quoting Jeppesen:
A good cantus firmus has a unique high point or a unique low point called a climax. A climax is a point of rhetorical forcefulness (e.g. "the climax of his speech..."), the point of highest dramatic tension (e.g. "the climax of the movie..."), or simply the culmination of a series of events.

http://www.contrib.andrew.cmu.edu/~randall/publications/ClassnotesforCTP.pdf

How exactly is climax defined?


Smarty output filters with Codeigniter and Ci-Smarty "not callable" error

Question: Im currently using codeigniter 2 with ci-Smarty. Just been trying to add a smarty output filter but not having much luck. Its as if the function cannot be found or something?
I am using a plugin as the output filter function and have the following code:
LOCATION: /libraries/Smarty.php
// Set email output filter
$this->loadFilter('output', 'protect_email');

LOCATION: /third_party/Smarty/plugins/function.protect_email.php
function smarty_function_protect_email($tpl_output, Smarty_Internal_Template $template)
{
    $tpl_output =
       preg_replace('!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!',
                    '$1%40$2', $tpl_output);
    return $tpl_output;
}

The above seems to throw the following smarty error:

Fatal error: Uncaught exception 'SmartyException' with message
  'outputfilter "protect_email" not callable' in
  /home/something/public_html/application/third_party/Smarty/sysplugins/smarty_internal_templatebase.php:717
  Stack trace: #0
  /home/something/public_html/application/libraries/Smarty.php(46):
  Smarty_Internal_TemplateBase->loadFilter('output', 'protect_email') #1
  /home/something/public_html/system/core/Loader.php(1095):
  CI_Smarty->__construct(Array) #2
  /home/something/public_html/system/core/Loader.php(975):
  CI_Loader->_ci_init_class('Smarty', '', NULL, NULL) #3
  /home/something/public_html/system/core/Loader.php(216):
  CI_Loader->_ci_load_class('smarty', NULL, NULL) #4
  /home/something/public_html/application/libraries/MY_Parser.php(29):
  CI_Loader->library('smarty') #5
  /home/something/public_html/system/core/Loader.php(1099):
  MY_Parser->__construct() #6
  /home/something/public_html/system/core/Loader.php(938):
  CI_Loader->_ci_init_class('Parser', 'MY_', NULL, NULL) #7
  /home/something/public_html/system/core/Loader.php(216): CI_Loa in
  /home/something/public_html/application/third_party/Smarty/sysplugins/smarty_internal_templatebase.php
  on line 717

Sorry about it being so long! Just thought seeing the whole error may help.
Thanks a lot for reading and hope someone can help.
-->EDIT
Also just tried to explicitly set the plugins directory location using:
$this->setPluginsDir(config_item('plugin_directory'));

The echoed out the location which is correct but still get the same problem :(
Answer: Okay that was a silly mistake.
For anyone else who has the same problem I was just looking through and realised the plugin should not be referred to as a regular function. For example it should have been called:
outputfilter.protect_email.php

Also make the same amends with the function name as well so in my case it should be called:
smarty_outputfilter_protect_email

This worked great for me.


Is the first character in the URI part of a HTTP handler always a forward slash?

Question: We are implementing a HTTP request handler subsystem in our project. The HTTP RFC says that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as "/" (the server root).
Question:
Does this mean that these two browser requests are guaranteed to result in the same http request verb, uri and host?
Browser request 1:
http://www.foo.com/

Browser request 2:
http://www.foo.com

Http request (not tested, but I assume that this is the case):
GET / HTTP/1.1
Host: www.foo.com

Follow up questions:
If the above assumptions are correct, is the forward slash guaranteed to ALWAYS be the first character of the path in a correct HTTP request?
And the last question: In a framework like Ruby Sinatra, is it a safe assumption to say that the user should ALWAYS begin his or her handlers with a leading forward slash?
Comment: Possible duplicate of [Do HTTP paths have to start with a slash?](http://stackoverflow.com/questions/27638278/do-http-paths-have-to-start-with-a-slash)
Answer: Follow Up Question:
As far as I know:
http://www.foo.com/path
http://www.foo.com/path/
Are two different URLs
A Sinatra route for:
/path
Will not map to a request for URL that has a trailing /
In Nancy however, it doesn't matter if the trailing forward slash exists or not.

Question:
If you create a route for
path
It will map from the base URL, in the same way
/path
Will map.
Basically both are identical.
My personal preference however is to always have the leading forwardslash because it's like saying "The root URL followed by my defined route".
Comment: You say that /path and path are 'basically' identical. The question is if there can be a case when they do not catch the exact same set of URI and are 100% interchangable.
Comment: The question is not about a path with a trailing slash. In the question there is only the host to accompany the a root slash.
Comment: If I get an answer to if there can be a different use case for /path and path in sinatra, I can accept the answer.
Comment: In a request the first character is always a forward slash. It's the beginning of the path after the HOST. Sinatra (from my limited knowledge) must always start with a forward slash. Nancy you don't have to. (hope that makes sense)


Localization of two rings which is an integral extension, then integral extension still holds?

Question: Question seems simple, but I just can't find the solution.
Let $A/B$ be an integral ring extension and let $P$ be a prime ideal of $B$. By lying-over theorem, there is $Q$, a prime ideal of $A$, lying over $P$. Then the ring of fractions of $A$ localized on $Q$ is still integral on that of $B$ localized on $P$?
Answer: Hint: consider an example.
Here is one:  $A = \mathbb Z[i] \supset \mathbb Z = B$, $P = 5\mathbb Z$, $Q = (2+i)\mathbb Z[i].$
The element $1/(2-i)$ lies in $A_Q$.  Is it integral over $B_P$?
Comment: thanks for your exemple. I give a proof in the case for the field of fractions, when this proposition is true. [link](http://mathoverflow.net/questions/152303/localisation-of-two-rings-which-is-an-integral-extension-then-integral-extensio)


When playing in a minor key, will the chords be minor as well?

Question: I've been jumping into music theory myself and I've been stumbling on creating certain melodies and such. I've played guitar all my teenage life and not once have I ever sat down and said I'm going to play in a certain key and write a song off of it. I just played chords till they sounded good together. Now that I've started to play piano I want to make a song/melody within a certain key.
Maybe I'm just confusing myself or just haven't learned scales and chord progressions further. But my question is if I play in D minor, will those chords (triads) be in minor as well? Like I should be playing Dm and not D?
It might be obvious but I don't know why I'm hung on this.
Thanks!
Comment: If you're really interested in learning theory, which is a fun and useful thing if you want to really know what you're doing, I'd recommend taking at least a Piano 101 course. The piano is called "The composer's instrument" because all the scales are easier to visualize. I've played guitar for many (many) years, and can relate everything I hear and play to the underlying theory. It allows me to pick out scales based on chords very easily, and find my way though styles of music by knowing what the chord choices could/should be. If you know theory, jazz, chord voicings and turnarounds are easy.
Answer: When you play in D minor, the scale -- that is your "palette" of notes -- is: D, E, F, G, A, B♭, and C
You'll find it's not possible to play a D major chord using those notes. D major contains an F♯.
The simplest way to find the chord you want is to identify its root note, then play a triad starting on that note, using only the notes in the scale.
So

if the accompanying bass note in your head is D, play D, F, A -- that's a D minor.
if the accompanying bass note in your head is C, play C, E, G -- that's a C major.

If you've been writing music with no background in theory, it's possible you've broken this rule, and it still sounds good. That's fine. They're not "rules", they're conventions, and they're conventions that are broken from time to time. So if the "maths" says you should play a minor, but a major sounds right to you, by all means stick with the major.

Footnote: That's a the "natural minor" scale. There is also the "harmonic minor" in which the 7th is sharpened - so C♯ here - and the "melodic minor" in which the 7th is sometimes sharpened, and sometimes not, largely at the composer's whim. And there are other scales which are considered minor because the 3rd is 3 semitones from the root, but are less common in Western music. But understand how things work with the "natural" scale before worrying about these. The important thing is that generally a scale is restricted to 7 notes from the 12 available, and if you play triads from that palette of 7, you'll find that a mixture of major and minor chords "automatically" happen.
Comment: Nothing's ever that simple. But a question that's evidently from a beginner, requires a beginner level answer.
Comment: Ok, two comments mean I have to add a footnote. But again, look at the question: when Dennis asked, he didn't understand how a piece in D minor might contain an F major chord -- dominants are something to learn about another day.
Comment: It's not quite that simple. It depends on if it's a D-minor dorian, D-minor phrygian, or D-minor aeolian. The dorian mode would be based on the C scale, which doesn't have a B♭, only B.
Comment: Even a beginner should have a C# in their palette of D minor notes -- to allow for A major, the dominant of D minor!
Answer: It's a great question that reveals the ambiguity of a word like "key."
A simple - but slightly vague - answer is that minor keys do involve major chords as well as minor chords. In fact, the most important chord that really makes D minor (aside from D minor, of course!) is major: A major is the "dominant" chord of D minor.
If you understand what that means, then you're on your way to understanding how the tonic-dominant relationship makes music really be "in" a key; it helps to understand not just scales, but harmony, which does't mean just "chords."
Suggestion: listen to music in minor keys to help enrich your hearing. You will find major chords as well as minor chords.
Eleanor Rigby is a great example of a minor key song with some major key-ish notes and chords:

(Technical aside: it actually lacks a strong dominant chord!)
Comment: Should point out that this song is in the dorian mode rather than the aeolian ("minor") mode.
Comment: @lobi Well, not completely (C major chords), but yeah, I agree.
Answer: To make it simple answer we make equation key = scale and minor = natural minor.
So if You want to have song build solely from the chords in minor key (let stick to the D minor) then:

Your scale will be: D E F G A Bb C
Basic triad chords made up of scale notes will be: Dm Em F Gm Am Bb C

To make it more complex using this chords, you can end up with major sounding tune as the same notes are in F major scale (with the same chords) i.e. play F, Bb and C = major tune
So generally not only notes and chords determine tonality, but also which chord with relation to others you choose - but for this You better give yourself some lessons on harmony. In this case learning scales and chords build from them should be your starting point.
Answer: As a guitarist, you're probably used to playing a couple of 'minor' notes against major chords, e.g. in a bar of D major (D F# A) we often use D, F, A and C natural to give a 'bluesy' feel to the solo.Think D pentatonic minor - it's used lots and lots !
The blues just bends or breaks conventional rules. Just consider the 'Hendrix' chord, which effectively plays a major and minor chord at the same time - D F# A C E# - I've called it E# rather than F (minor third) as it's D7#9. So the answer is yes, it's o.k.-the sound you make should be more important than its correctness in official music rules terms!
Answer: When you play in a minor key, you usually are playing in a major key, but using one of the minor chords as a tonal center. And no, you don't just play minor chords, you end up creating chord progressions that are similar to the types of progressions you make in a major key and are often the same chords. The difference is whether or not you "focus" on that minor chord and "resolve to" that minor chord.
I mean you can basically continue doing what you're doing, playing by ear and figuring out which chords in the major key lead to that minor chord. Or you can pick up a book on harmony or take a college course in harmony, which will open it up for you and provide you with a better understanding of what's going on.
Answer: A scale starts on a note which may or may not be the first note you play so to imply that playing in Dm is so complicated isn't fair,start first with your corresponding Maj key which is three half steps above your minor key so in this case it would be F Maj as 1 when you do it you start on Dm forget that it's minor, just your pattern will be whole half whole whole half whole whole which will give you D E F G A Bb C D. F Maj pattern is whole whole half whole whole whole half whole which gives you F G A Bb C D E F.
Now if you start in the key of C which has no sharps or flats and minor a scale, move up 7 half steps to G which is your next key and you will use the same pattern to find which notes to sharp, all of music is based around the same 12 notes B-c and E-F don't have sharps or flats between them for the guitar each string starts on the note you have as it is open so from an E string it goes E F F# G G# A A# B C C# D D# and on the 12th fret you start over on E.
Maybe you already knew that is how you start figuring out your scales for lead, back to your question for each key scale as long as your notes that you choose for your progression are in that range for example C scale 1234567 you can play whatever note you want in that range and you are in C. So if your follow that which I showed earlier as long as you are in the range from Dm scale and play your Dm as tonic then you are playing in Dm you don't even have to play it as tonic it doesn't matter. I would recommend figuring out the patterns and scale for each key if you count from C 7 half steps to G then D and so on use the same patterns to get your scale and practice each individual key you will have it figured out in no time.


Postfix relay host connection fails: timed out while receiving initial server greeting

Question: I have an Elastix server box that I want to send email notifications of voice mails from. I'd like to send them through our company email (hosted by shared web host provider Bluehost). I have followed instructions on how to use Postfix as a relay server. Emails don't go out tho. I get the following in the logs (slightly obfuscated):
Sep 27 16:31:51 TD1000 postfix/smtp[9757]: 1B2C357117: to=<firstname.lastname@example.com>, relay=boxNNN.bluehost.com[a.b.c.d]:465, delay=5241, delays=5076/0.03/165/0, dsn=4.4.2, status=deferred (lost connection with boxNNN.bluehost.com[a.b.c.d] while receiving the initial server greeting)

Various places suggest that it might be a blacklisting issue. However, it seems like that would be an issue for my outlook running on my PC also. What I am trying to do is get the postfix to act like Outlook, and send through Bluehost, using SSL. (my outlook settings: boxNNN.bluehost.com:465, SSL, authentication required)
When I up the debugging level, I get the following message:
dns_query: boxNNN.bluehost.com (MX): Host found but no data record of requested type

But since the ultimate message is no response, and it finds an IP address for the server, I don't the DNS issues are the problem.
postconf -n reveals:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
debug_peer_level = 5
debug_peer_list = boxNNN.bluehost.com
html_directory = no
inet_interfaces = all
mail_owner = postfix
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination = $myhostname, localhost.$mydomain, localhost
mydomain = cenginc-office.local
myhostname = td1000.my-office.local
mynetworks = /etc/postfix/network_table
newaliases_path = /usr/bin/newaliases.postfix
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix-2.5.6/README_FILES
relayhost = boxNNN.bluehost.com:465
sample_directory = /usr/share/doc/postfix-2.5.6/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
smtp_connect_timeout = 300
smtp_enforce_tls = yes
smtp_helo_name = my-phone-system
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options =
smtp_sasl_type = cyrus
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = smtpd
unknown_local_recipient_reject_code = 550
virtual_alias_maps = hash:/etc/postfix/virtual
virtual_mailbox_base = /var/mail/vhosts
virtual_mailbox_domains =
virtual_transport = lmtp:unix:/var/lib/imap/socket/lmtp

(we are using Postifix 2.3.3 according to the Elastix UI, so I'm not sure why the samples say 2.5.6)
When I telnet to the bluehost box and port, the connection remains open for a short time, and then closes, I think because I'm not coming in as SSL.
I used this site (among others) for the configuration, but I don't see what I'm missing. https://www.zulius.com/how-to/set-up-postfix-with-a-remote-smtp-relay-host/
Any ideas on what I'm doing wrong? My theory is that postfix isn't doing something that bluehost expects in the initial connection, but I have no idea what. Thanks for your help.
Comment: I don't see any place in your configuration where you tell postfix to use ssl while connecting to boxNNN.bluehost.com:465. Does it try to connect without ssl?
Comment: Try testing connection with `openssl s_client -connect boxNNN.bluehost.com:465`.
Comment: @befreeandgood: I'm not sure how to tell it to use SSL, then. I thought that's what the smtp_sasl_auth_enable was. But now that I look into it a little more, I'm not sure that it is.
Comment: @kworr: I was able to connect, get a banner and a response to an EHLO command. Sounds like I need to get postfix to actually use SSL
Comment: http://www.eglug.org/book/export/html/1923 showed tunneling the relay through stunnel, which seems to work, but now I've got names all mumbled up. Bounces cuz it is sending `firstname.lastname@example.com` as a sender or reply-to. I'm connecting to the bluehost box, but not sending the correct account names, etc.
Comment: I'm not sure how to give y'all credit for helping: kworr and @befreeandgood I can't mark your comments above as helpful.
Comment: I'm not sure tunneling is a clean solution. Try https://www.zulius.com/how-to/set-up-postfix-with-a-remote-smtp-relay-host/
Comment: @befreeandgood: I looked at that, but I couldn't see how that was using an SSL connection. Does the TLS option mean we are starting an SSL connection? Is there a way to simulate the TLS connection (like I did with the openssl suggestion above)?
Answer: We have two facts here

You are connect to bluehost via port 465
Postfix reported an error message: lost connection with boxNNN.bluehost.com[a.b.c.d] while receiving the initial server greeting

One possible explanation is SMTP client in Postfix 2.11 or older doesn't support SSL.
Explanation
In SMTP, there are two encryptions scheme: STARTTLS and SMTPS. The difference is (1) SMTPS require SSL encryption from the first byte and (2) STARTTLS require plain text mode first and optionally client and server do SSL negotiation after STARTTLS command.
Postfix SMTP Server (smtpd) support both protocols. The problem is SMTP client (before postfix 3.0) - the one who sending email to remote server - doesn't support SMTPS connection. It only support plain text mode or STARTTLS mode.
What happens here is: Postfix SMTP client use plain text mode to connect to Bluehost because postfix want to established STARTTLS. But the Bluehost expect the first byte was SSL negotiation not plain text. This mismatch make Bluehost server silently discard the data and disconnect postfix. Postfix doesn't know what's going here, so it throws the error in maillog
Sep 27 16:31:51 TD1000 postfix/smtp[9757]: 1B2C357117: to=<email@example.com>, relay=boxNNN.bluehost.com[a.b.c.d]:465, delay=5241, delays=5076/0.03/165/0, dsn=4.4.2, status=deferred (lost connection with boxNNN.bluehost.com[a.b.c.d] while receiving the initial server greeting)

Solution
Postfix TLS documentation provide a workaround to use stunnel here. So the solution from MrPhilTX was correct for Postfix < 3.0.
In postfix 3.0, Wietse Venema decided to give additional SMTPS feature for postfix SMTP client. With this feature, the stunnel solution doesn't needed here. There two variations here:
a) Enable SMTPS to all outgoing SMTP connection
Usually, in this case postfix has SMTPS-only relayhost like OP's problem. So
# Client-side SMTPS requires "encrypt" or stronger.
smtp_tls_security_level = encrypt
smtp_tls_wrappermode = yes
# The [] suppress MX lookups.
relayhost = [mail.example.com]:465

b) Enable SMTPS to several host
For other case, you need custom transport and transport_maps to selective turn on SMTPS
# /etc/postfix/main.cf:
transport_maps = hash:/etc/postfix/transport

# /etc/postfix/transport:
example.com  relay-smtps:example.com:465

#/etc/postfix/master.cf:
relay-smtps  unix  -       -       n       -       -       smtp
    # Client-side SMTPS requires "encrypt" or stronger.
    -o smtp_tls_security_level=encrypt
    -o smtp_tls_wrappermode=yes

Comment: Thanks for the explanation and validation of my answer. A clear, understandable answer: well done.
Answer: I'm not sure if this is where I should put this, but here is how I got it working.
So, kworr and befreeandgood put me on the right track. The smtp_sasl_* doesn't do anything with SSL, just with authentication.
I followed a combination of the instructions from the following links:
This one got me close
http://www.eglug.org/book/export/html/1923
but left out a few things to set.
This one http://tech.surveypoint.com/blog/relay-mail-with-postfix-and-stunnel/ added inet_interfaces = loopback_only.
Those options got me to some problems with the mail server rejecting various header names, like "from" and "reply-to". I fixed those via some instructions that I found via googling, (but I'm not allowed to post those links as I have exceeded my link quota already).
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
debug_peer_level = 2
html_directory = no
inet_interfaces = loopback-only
mail_owner = postfix
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination = $myhostname, localhost.$mydomain, localhost
mydomain = my-office.local
myhostname = td1000.my-office.local
mynetworks = /etc/postfix/network_table
newaliases_path = /usr/bin/newaliases.postfix
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix-2.5.6/README_FILES
relayhost = 127.0.0.1:5001
sample_directory = /usr/share/doc/postfix-2.5.6/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
smtp_connect_timeout = 60
smtp_generic_maps = hash:/etc/postfix/generic
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options =
smtp_sasl_type = cyrus
smtp_use_tls = yes
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = smtpd
smtpd_tls_auth_only = no
smtpd_tls_loglevel = 2
smtpd_tls_received_header = no
unknown_local_recipient_reject_code = 550
virtual_alias_maps = hash:/etc/postfix/virtual
virtual_mailbox_base = /var/mail/vhosts
virtual_mailbox_domains =
virtual_transport = lmtp:unix:/var/lib/imap/socket/lmtp

So the smtp_generic_maps was used to rename the various addresses that came up to some address that actually exists. I had to do that for two different names, that I found by looking in the /var/log/maillog file.
So, the summary to connect to Bluehost:

Enable smtp_sasl authentication
Use stunnel to create an SSL tunnel
Use smtp_generic_maps to map the non-existent usernames that asterisk is using.
Dinking around with the mydomain and such might get you around the generic maps requirement. I also saw someone reference $myorigin as a potential work around.
Comment: Have you tried setting up postfix without stunnel first? If so, why did it fail?
Comment: Yes. It failed with the original question: status=deferred then lost connection with boxNNN.bluehost.com[a.b.c.d] while receiving the initial server greeting. How does one tell postfix to use SSL? My google-fu only found the tunneling suggestions. Thanks for following up.
Answer: When destination domain has no MX records SMTP server should try delivering mail to any of domain A records. For example.net this would be any address of example.net.
If the connection to encrypted port fails you need to consult postfix manual about smtp_tls_security_level parameter. You can find there a lengthy explanation but I think in most cases you just need to add to your config:
smtp_tls_security_level=may

Comment: Well, I guess that part is working as intended then. :-) Thanks!


Recuperar uma avaliação geral e exibir em uma lista

Question: Boa noite pessoal, estou na seguinte situação,
Tenho uma tabela chamada carros, e cada carro pode ser avaliada por diferentes usuários, ate ai tudo bem, criei uma tabela secundaria chamada avaliações e cada carro pode ser avaliado por vários usuários diferentes.
Agora preciso que cada carro mostre uma avaliação geral, que e pegar todas as avaliações de todos os usuários em um determinado carro e mostrar em uma lista com todos os carros.
Ai que esta minha duvida, como recuperar todos as avaliações da tabela avaliação.
Inseri a Tabela para melhor entender, vou pegar so a somatória da avaliação geral e quantas pessoas avaliaram o mesmo carro exemplo

GOLF - 2 Avaliações - 7 pontos

$sql = $conex->query("SELECT * FROM carros");
while($rs=$conex->result($sql)){
                    $id_car=$rs['id_car'];
                    $nome_car=$rs['nome_car'];
};

// Tabela ----------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `avaliacao` (
  `id_ava` int(11) NOT NULL,
  `id_car_ava` int(11) NOT NULL,
  `id_usu_ava` int(11) NOT NULL,
  `dirigibilidade_ava` int(11) NOT NULL,
  `estabilidade_ava` int(11) NOT NULL,
  `potencia_ava` int(11) NOT NULL,
  `consumo_ava` int(11) NOT NULL,
  `geral_ava` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

--
-- Extraindo dados da tabela `avaliacao`
--

INSERT INTO `avaliacao` (`id_ava`, `id_car_ava`, `id_usu_ava`, `dirigibilidade_ava`, `estabilidade_ava`, `potencia_ava`, `consumo_ava`, `geral_ava`) VALUES
(1, 1, 2, 4, 2, 2, 4, 4),
(2, 1, 6, 4, 4, 5, 5, 5),
(3, 2, 7, 5, 5, 5, 4, 3),
(4, 3, 9, 4, 4, 4, 4, 3);

-- --------------------------------------------------------

--
-- Estrutura da tabela `carros`
--

CREATE TABLE IF NOT EXISTS `carros` (
  `id_car` int(11) NOT NULL,
  `model_car` varchar(200) NOT NULL,
  `ano_car` int(12) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

--
-- Extraindo dados da tabela `carros`
--

INSERT INTO `carros` (`id_car`, `model_car`, `ano_car`) VALUES
(1, 'Golf', 2000),
(2, 'Pálo', 1998),
(3, 'Jeta', 2015),
(4, 'Peugeout 206', 2006);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `avaliacao`
--
ALTER TABLE `avaliacao`
  ADD PRIMARY KEY (`id_ava`);

--
-- Indexes for table `carros`
--
ALTER TABLE `carros`
  ADD PRIMARY KEY (`id_car`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `avaliacao`
--
ALTER TABLE `avaliacao`
  MODIFY `id_ava` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `carros`
--
ALTER TABLE `carros`
  MODIFY `id_car` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Answer: O SQL que pretende
SELECT *, (SELECT COUNT(*) FROM avaliacao WHERE id_car_ava=id_car) AS QT FROM carros

Exemplo.:
http://sqlfiddle.com/#!9/23cfaf/2
Comment: Obrigado Thiago!

O lance e que e em outra tabela, não na mesma dos carros, entende, tenho que pegar todos as avaliações da outra tabela referente ao carro e mostrar na listagem geral dos carros.

Tenho a tabela, Avaliações e a tabela Carros
Comment: ok, na sua pergunta acrescente as tabelas de base dados por favor
Comment: Após acrescentar as tabelas eu editarei a minha resposta
Comment: Ok, Tiago Gomes, alterei la, e inseri mais detalhes, obrigado pela ajuda!
Comment: Thiago Mais Uma vez obrigado, so mais uma questão, alem de exibir quantas pessoas votaram, eu teria que pegar a somatória dos votos, daria para fazer neste mesmo select?

Creio que seria isso!
Mais minha duvida e como exibir na leta.

`SELECT *, (SELECT COUNT(*) FROM avaliacao WHERE id_car_ava=id_car ),(SELECT SUM(geral_ava) FROM avaliacao WHERE id_car_ava = id_car ) AS QT FROM carros`
Comment: veja se é isso que pretende.: SELECT
 *,
 (
  SELECT
   COUNT(*)
  FROM
   avaliacao
  WHERE
   id_car_ava=id_car
 ) AS QT_AVALIACAO,
 (
  SELECT
   COALESCE(SUM(geral_ava),0)
  FROM
   avaliacao
  WHERE
   id_car_ava = id_car
 )  AS QT_PESSOAS
FROM
 carros


Reducer: Returns Default state

Question: I am new to redux and trying to understand how redux works, I have made a small application of counter which increments the value everytime
Here is the code of store.ts file:
import { iAppState } from './store';
import { INCREMENT } from './actions';
export interface iAppState {
    counter: number
};

export const INITIAL_STATE = {
    counter: 0
}

export function rootReducer(state: iAppState, action): iAppState {
    switch(action.type) {
        case INCREMENT : return {counter: state.counter + 1}
    }
    return state;
}

When i comment the return state line and use console.log(ngRedux.getState()); it returns Nan of type as number, But when i uncomment the same line it displays the correct value.
What is happening internally?
Answer: When redux is first initialized in your application, an action type of @@INIT is usually dispatched on start up.
By commenting out the return state; line at the end of your reducer, this causes the @@INIT action to return undefined. That causes the "next state" of your application after @@INIT to be undefined.
This in turn means that dispatching the INCREMENT action causes your reducer to perform arithmetic on an undefined counter, which will result in the NaN you're currently getting.
Consider also, initializing your reducers state by making the following alteration:
export function rootReducer(state: iAppState = INITIAL_STATE, action): iAppState {
    switch(action.type) {
        case INCREMENT : return {counter: state.counter + 1}
    }
    return state;
}

Reducer: Returns Default state


why to use 'iterator' to loop thru an ArrayList. It can be done without Iterator also right?

Question: why use 'iterator' to loop thru an ArrayList. It can be done without Iterator also right?
so the benefits of using iterator to loop thru an ArrayList
import java.util.ArrayList;
import java.util.Iterator;

 public class IteratorDemo {
  public static void main(String[] args) {

    // Make a collection
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");

    // Get the iterator
    //Iterator<String> it = cars.iterator();

    // Looping without Iterator
    for(int i=0;i<4;i++) {
        //System.out.println(it.next());

        System.out.println(cars.get(i));
    }
  }
 }

Answer: Sometimes you just don't need the index so it is easier.  But try doing this using an indexed for loop.  It can be done, but not as easily.
List<Integer> list = new ArrayList<>(
                List.of(1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10));
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
   // if even, remove it.
   if (it.next() % 2 == 0) {
      it.remove();
   }
}
System.out.println(list);

Prints
[1, 3, 5, 7, 9]

Using an interator allows you to modify lists that might otherwise trigger a concurrent modification exception.
Also, assume you had a class implementation that generated primes or fibonacci numbers.  You could do this to grab them individually.
Fibonacci fib = new Fibonacci(0, 1, 10);
for (long i : fib) {
    System.out.print(i + " ");
}

Prints
0 1 1 2 3 5 8 13 21 34

The Fibonacci class
class Fibonacci implements Iterable<Long> {
    public long start;
    public long next;
    public long count;

    public Fibonacci(int start, int next, int count) {
        this.start = start;
        this.next = next;
        this.count = count;
    }

    private class MyIterator implements Iterator<Long> {
        int n = 0;

        public boolean hasNext() {
            return n < count;
        }

        public Long next() {
            n++;
            long ret = start;
            start = start + next;
            next = ret;
            return ret;
        }
    }

    public Iterator<Long> iterator() {
        return new MyIterator();
    }
}

By implementing Iterable in the class I can use the foreach construct to get elements of the class.
Answer: You probably don't have benefit of using it directly. But the iterator is used by for example the forEach.
Comment: i thought the question was "why use an iterator?". So what I wrote is an answer to that. Not a comment. Maybe I misunderstood the question then.
Answer: Just to loop through it you don't need an iterator, a for loop will suffice. If you need to modify the list then you need it to avoid ConcurrentModificationException.


Custom animation on fragments, but selective

Question: I have base class for all Fragments and overrided method onCreateAnimation to use custom animations at all once, but need to exclude some fragment(s). I did it using instanceof but i use nested fragments and it does work as expected. Is an elegant way to disable animation for some fragments in this situation ?
abstract public class BaseFragment<T> extends Fragment {
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
       if(this instanceof ScannerFragment) {
          return super.onCreateAnimation(transit, enter, nextAnim);
       } else {
          // custom animation
       }
    }
}

Answer: You could try initiating the fragments with a parameter that enables or disables the animation:
public static BaseFragment newInstance(boolean isAnimated) {
    BaseFragment myFragment = new BaseFragment();

    Bundle args = new Bundle();
    args.putBoolean("isAnimated", isAnimated);
    myFragment.setArguments(args);

    return myFragment;
}

In your activity, you create the fragment by calling BaseFragment.newInstance(true/false);
In your Fragment code you can then use getArguments().getBoolean("isAnimated", true); to get the value that you passed.
Comment: I recognize fragments by type, no need to pass another argument. Another argument does't resolve a problem.
Comment: Then can you add some more information as to what does not work as expected? The identification of the fragments or the animation on the nested fragments?


Extremely poor performance with VMWare hosted build server

Question: We are running TeamCity on a Windows Server 2008 as a build server. The build server is hosted in VMWare ESXi 5. (I have very little VMWare experience so my terminology might be wrong).
When we start a build, we more often than not experience extremely poor performance.
The build server guest has been assigned 4 CPUs with no upper limit and no other guest systems are very busy.
What we have observed using vSphere Client is that after a while the CPU rate drops from about 4600 MHz to about 50 MHz. When the build stops, the CPU frequency goes back to normal semi-idle rate.
Another interesting observation is that while the build server is working at about 50 MHz it gets a burst of CPU every six minutes (see graph).
Yet another observation is that the system clock loses time proportional to the missing CPU cycles (about a factor 100 in the low-CPU periods).
EDIT
Added chart with host specs.
Comment: How's the memory and disk IO stats, also how's cpuready?
Comment: Are you sure your build VM is not being resource-starved by other higher-priority VMs?
Comment: Yes, the other VMs are mostly idle. I have double checked with vSphere. Memory consumption is not alarming.
Comment: Just to flesh out on Chopper3's comment can you describe the disk subsystem of the ESXi host, and list any other significant software on the TeamCity VM (e.g. Antivirus).
Comment: The system runs a Plastic SCM server and a YouTrack issue tracker. Neither is especially resource demanding and during the slow builds, they are typically sitting idle. Is there anything special I should notice regarding the disk system?
Answer: What are the server's specifications? RAM, physical CPUs?
One thing you can try quickly is to cut your build server down to ONE or TWO virtual CPUs and repeat your trial. This is the preference, as it's easier for the hypervisor to allocate CPU time for a single vCPU versus finding four free cores to provide resources for four vCPUs you've provisioned.
Comment: Before I kept a few virtual cores (not sockets). Now I have tried running the server as a single socket single core CPU and so far it has made two successful builds. I will try to make a couple of additional builds before drawing any conclusions.
Comment: +1 for de-provisioning virtual CPUs.  My experience has been similar to ewwhite's, and 1 vCPU often offers optimal performance.
Comment: I have now reduced the number of vCPUs to one per VM (in total three running machines), but the exact same thing happens. After the build has been running for a while the CPU MHz drops from about 4000 to around 54.
Comment: I still observe the CPU boost cycles: 5 minutes of about 54 MHz then about one minute of about 4000 MHz. This cycle is repeated until the build completes after which normal operation and performance resumes.
Comment: After a few more builds it is still looking promising. I would prefer a few more cores however.


Vetor fazer uma consulta mysql

Question: Olá pessoal estou tentando fazer um consulta usando vetor, mas até onde já aprendi o comando sql não comporta o vetor da forma que estou fazendo então meu resultado é variável vazia.
$idcliente=$_SESSION['id_cliente'];
$loja=$_POST['loja'];
$quant[0]=$_POST['quant'];
$quant[1]=$_POST['quant2'];
$quant[2]=$_POST['quant3'];
$produtos[0]=$_POST['produto'];
$produtos[1]=$_POST['produto2'];
$produtos[2]=$_POST['produto3'];
$tipo=$_POST['ttipo'];
$acrescimo=$_POST['acrescimo'];
$pedido=$_POST['pedido'];
$entrega=$_POST['entrega'];
$montagem=$_POST['montagem'];
$tsmg=$_POST['tsmg'];

$x=mysqli_query($conn,"select*from produtos where descricao='$produtos'");
$prt=mysqli_fetch_array($x);

    $idproduto[]=$prt['id_produto'];
    $codigo[]=$prt['codigo'];
    $descricao[]=$prt['descricao']."";
    $cor[]=$prt['cores'];
    $marca[]=$prt['marca'];
    $valorm[]=$prt['valormontagem'];

  print_r($descricao);

Aqui é o trecho que envia os dados para os comandos de cima.
    <input list='produtos' name='produto'/>
    <datalist id='produtos'><?php
    $sql= mysqli_query($conn,"select descricao from produtos order by descricao");
    while ($resp = mysqli_fetch_array($sql)) {

     $group=$resp['descricao'];
    echo "
   <option value='$group','$cor'>";
   }

   ?> </datalist>

Fiz com 2 produtos como teste.
   print_r($produtos);
   Array ( [0] => BERCO CHANTILY [1] => BERCO ALEGRIA [2] => )

   print_r($descricao);
   Array ( [0] => )

Comment: Retirei a resposta, visto que não estava  ajudar, basicamente corrigi `foreach($produtos as $prod) {
    $query .= " descricao='$prod' OR";
}
$query = rtrim($query, ' OR');`, de `AND` para `OR`. Se não conseguir não vejo que mais possa ser
Comment: Sua resposta estava certa @Miguel. Algum detalhe que eu não vi também que não deu certo.
Comment: Pois eu testei aqui e também deu @AndreiCoelho, mas estava a ser tão má aceite que retirei a pensar que estava com um erro crasso
Comment: Onde está a variável `$produto`? O que é ela?
Comment: Ela vem de um formulário. Nesse campo ele está lendo uma tabela e exibindo para seleção. Dei um `print_r` e nessa parte está exibindo perfeitamente.
Comment: Ou seja `$produto` é um array certo? Coloque por favor o formato do array para lhe poder ajudar
Comment: Sou estudante então me desculpe essa pergunta idiota. Fora o conteúdo que já mostrei não sei como lhe mostra o formato da array, se puder me dar uma dica eu ficaria muito agradecido.
Comment: Pode colocar exatamente a impressão do `print_r($produtos)`
Comment: Feito, esta editado pra facilitar a organização.
Comment: E quer ir buscar por ex: os produtos cujo as descrições são BERCO CHANTILY e BERCO ALEGRIA certo?
Comment: Certo amigo exatamente isso.
Comment: Veja se isto em baixo resulta
Comment: Exatamente fiz os teste e funcionou perfeitamente obrigado a todos que me ajudaram aprendi algo novo e sou muito grato.
Comment: Relaxe quando corrigiu suas observações funcionou perfeita.
Comment: Não há problema. Entretando DaniloAraujo deveria aceitar a resposta do @AndreiCoelho que funciona bem e é uma solução para o problema
Comment: Na verdade @Miguel sua resposta está mais correta.   Gostaria que quem a negativou que fizesse alguma observaçao.
Comment: Obrigado @AndreiCoelho. Secalhar negativaram no inicio, por lapso fiz uns erros de sintaxe
Comment: Entendi, pode ser. =)
Answer: Tenta fazer assim:
 <?php

// abaixo são enviados 3 produtos

$produtos[0]=$_POST['produto'];
$produtos[1]=$_POST['produto2'];
$produtos[2]=$_POST['produto3'];

// contamos a quantidade

$quantidadeProdutos = count($produtos);

// agora vamos selecionar produto por produto e cada produto faremos a inserção nas arrays

for ($y = 0; $y < $quantidadeProdutos; $y++){

    $produto = $produtos[$y];
    $x=mysqli_query($conn,"select * from produtos where descricao='$produto'");
    while($prt=mysqli_fetch_array($x)){

        $idproduto[]=$prt['id_produto'];
        $codigo[]=$prt['codigo'];
        $descricao[]=$prt['descricao']."";
        $cor[]=$prt['cores'];
        $marca[]=$prt['marca'];
        $valorm[]=$prt['valormontagem'];

    }

}

print_r($descricao);

?>

Comment: Se puder dar uma dica para melhorar @Andrei Coelho. Você aí está a fazer uma chamada à base de dados por loop, podia ser reduzida a uma só para todos. Vou restaurar o minha resposta só para você ver uma alternativa
Comment: @Miguel, nao tenho nada a acrescentar. Gostei da sua resposta. Abraço! =)
Comment: Obrigado @Andrei, para ti também
Answer: Tente assim:
...
$query = "select * from produtos where";
foreach($produtos as $prod) {
    $query .= " descricao='$prod' OR";
}
$query = rtrim($query, ' OR');
$x = mysqli_query($conn, $query);
while ($prt = mysqli_fetch_array($x)) {
    $idproduto[]=$prt['id_produto'];
    $codigo[]=$prt['codigo'];
    $descricao[]=$prt['descricao']."";
    $cor[]=$prt['cores'];
    $marca[]=$prt['marca'];
    $valorm[]=$prt['valormontagem'];
}

print_r($descricao);

Comment: fiz alguns ajustes, pois notei pequenos erros de digitação, mas mesmo assim esta ocorrendo esse erro dentro do `while` Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in..../ line28
Comment: corrigi. Peço desculpa foi um erro parvo de sintaxe. corrigi na linha `... = mysqli_query(...` e na do `while (...`
Comment: esse é seu codigo com os ajustes:                                                   $query = "select * from produtos where";
foreach($produtos as $prod) {
    $query= " descricao='$prod' AND";
}
$query = rtrim($query, ' AND');
$x = mysqli_query($conn,$query);
while($prt=mysqli_fetch_array($x)){
    $idproduto[]=$prt['id_produto'];
    $codigo[]=$prt['codigo'];
    $descricao[]=$prt['descricao'];
    $cor[]=$prt['cores'];
    $marca[]=$prt['marca'];
    $valorm[]=$prt['valormontagem'];
}
Comment: Infelizmente amigo, percebi os equívocos no código e fiz as correções. Inclusive removi `.=` para `=` mas mesmo assim tenho uma falha relatada dentro do `while`, que por sinal nas varias vezes que tentei fazer o código funcionar tive algumas vezes a mesma condição.
Comment: Mas isso é para continuar assim `.=`. serve para incrementar texto à query inicial
Comment: se eu o deixar ele faz o comando mas não me da o `print_r`. deixando a pagina completamente vazia.
Comment: Não exibe nenhum erro? experimente fazer `echo $query` antes do `while` e `echo $prt['descricao'];` dentro do `while`. O que imprime `echo $query`?
Comment: fiz em diversos lugares e antes do while me retorno o seguinte `echo` select * from produtos where descricao='BERCO 8020' AND descricao='BERCO ALEGRIA'
Comment: E dentro do while nada? Secalhar é porque não há nenhuma linha a ser retornada, essa query está certa. Não há erro aí
Comment: Mas espere aí... Agora estou a pensar numa coisa, como é quer que haja um produto com duas descrições diferentes?? Não é possível vou trocar o `AND` por `OR`. Corrigido
Comment: infelizmente dentro do while não acontece nada. fiz junto ao `while` or msqli_print error(). replicou o mesmo erro infinitamente.
Comment: Já pôs com essa correção? Qual é o erro mesmo? Veja que alterei o código em cima

Vetor fazer uma consulta mysql


Prove the set is Jordan- measurable and find the appropriate Jordan measure (volume) of the set V.

Question: Prove the set is Jordan- measurable and find the appropriate Jordan measure (volume) of the set V.
$$V= \{ (x,y,z)|x^2+y^2\geq 1, x^2+y^2\leq2x, x^2+y^2+z^2 \geq 4, x+y+z\leq 8\} $$
I'm not sure if this question is within the curriculum that we have done thus far, i would appreciate any feedback on solving this.. Can it be solved without integrals ?
Answer: This set is not bounded so is not Jordan-mesurable.
Comment: No, spot (3/2,0, -n) for every n >=3 belongs to this set
Comment: Doesnt x+y+z <= 8 make it bounded, sir? ;)
Comment: I agree. Very good answer.


How many characters can be stored in 4KB?

Question: How many characters can i store in 4kb when the characters are in utf-8 encoding ?
Answer: Here is a visual cue how much 1024 or 4096 are. Read @Jon Snyder's message to get a better understanding.
1024 Characters (Assuming Characters have 4 bytes):
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit ve
4096 Characters (Assuming Characters have 1 byte):
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus. Vestibulum volutpat pretium libero. Cras id dui. Aenean ut eros et nisl sagittis vestibulum. Nullam nulla eros, ultricies sit amet, nonummy id, imperdiet feugiat, pede. Sed lectus. Donec mollis hendrerit risus. Phasellus nec sem in justo pellentesque facilisis. Etiam imperdiet imperdiet orci. Nunc nec neque. Phasellus leo dolor, tempus non, auctor et, hendrerit quis, nisi. Curabitur ligula sapien, tincidunt non, euismod vitae, posuere imperdiet, leo. Maecenas malesuada. Praesent congue erat at massa. Sed cursus turpis vitae tortor. Donec posuere vulputate arcu. Phasellus accumsan cursus velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed aliquam, nisi quis porttitor congue, elit erat euismod orci, ac placerat dolor lectus quis orci. Phasellus consectetuer vestibulum elit. Aenean tellus metus, bibendum sed, posuere ac, mattis non, nunc. Vestibulum fringilla pede sit amet augue. In turpis. Pellentesque posuere. Praesent turpis. Aenean posuere, tortor sed cursus feugiat, nunc augue blandit nunc, eu sollicitudin urna dolor sagittis lacus. Donec elit libero, sodales nec, volutpat a, suscipit non, turpis. Nullam sagittis. Suspendisse pulvinar, augue ac venenatis condimentum, sem libero volutpat nibh, nec pellentesque velit pede quis nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce id purus. Ut varius tincidunt libero. Phasellus dolor. Maecenas vestibulum mollis diam. Pellentesque ut neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In dui magna, posuere eget, vestibulum et, tempor auctor, justo. In ac felis quis tortor malesuada pretium. Pellentesque auctor neque nec urna. Proin sapien ipsum, porta a, auctor quis, euismod ut, mi. Aenean viverra rhoncus pede. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Ut non enim eleifend felis pretium feugiat. Vivamus quis mi. Phasellus a est. Phasellus magna. In hac habitasse platea dictumst. Curabitur at lacus ac velit ornare lobortis. Cura
Comment: Seems silly, but this was **very** helpful!
Comment: took me a split second to understand the nonsense in this answer :)
Answer: In UTF-8 characters need between 1 and 4 bytes. So, you can store between 4096 and 1024, respectively, UTF-8 characters in 4KB.
I would assume that in many use cases you can expect that most characters fit into one byte and almost all into 2.
Comment: To expand, characters in ASCII only take 1 byte, other characters can take more.  So one way to estimate where in the range MForster gives is to ask yourself what portion of your characters are likely to be ASCII.  If this is basically text in english with occasional accented characters, you can probably fit closer to 4000 characters.  If your text is in, say, Telugu, it will generally be 3 bytes per character, so you can fit somewhere around 1300 or so.
Comment: This is correct. (Assuming that your question is how many characters of the base64-encoded string fit, not how many of the original cyrillic characters).
Comment: Um i'm using cyrillic and english, but it gets encoded with base64 and then stored. so i guess base64 is pure english and that makes e character per byte right which equeals 4096 characters right?
Comment: Yeah, i added the base64 in the code after i wrote this question
Comment: @JacobMattison Thanks for your intuitive understanding. Helps.
Answer: A UTF-8 character is from 1-4 bytes, so it depends on what character you are encoding.  The majority of english uses 1 byte for each character.  Other western languages use 2 bytes.  Asian characters can use 4 bytes.
So the answer is from 1024 to 4096 depending on the characters.  Additionally, on a windows environment you may need a 3 byte BOM at the start of the document which will lower the amount of characters that you can fit into 4Kb.  See the wikipedia article on UTF-8.


Formula for finding relative chords/scales of the same notes

Question: Is there a way to quickly calculate relative/enharmonic chords or scales that are based off the same notes as another, like you can with the notes themselves, i.e. C being equivalent to A minor? For instance, if you have a C7 chord, which has one flat, making it the equivalent of an F Major chord, correct? Is comparing the key signatures the only way to quickly find a relative chord?
Comment: The quickest, most effective, is to learn your scales and chords, and apply the information to what you need. It appears at the moment you're somewhat confused as to chords and their relations with other chords. C isn't equivalent to Am, and C7 certainly isn't equivalent to F. If you mean *relative keys*, which is completely different, take any major key, count up 6 and you arrive at the relative minor *key*.
Comment: How would you find the equivalent of something like a Cmin/maj7, which only has one flat, but it's an E♭?
Comment: What would you do with this information? In what situation is a C7 chord equivalent to an F major chord? C7 can be a secondary dominant for a Bb based chord like Bbm - C7 - F7 - Bbm. Or it could work as a tritone substitute for F#7, going into Bm. Or it could be used in G-based blues like G7 C7 G7 D7 ... or a C-based or F-based blues. What are you trying to do? :)
Comment: It kind of depends on the instrument you play as well. And, like @piiperi, I am not quite sure what your aim is.
Comment: C7 doesn't contain an F or an A so I don't see how C7 and F are equivalent. Also an F major chord doesn't have any flats. Do you mean scales? But there is C7 scale so I am just totally confused.
Comment: This is a terribly worded question, but I think the OP is asking "How can I quickly figure out what key(s) might be implied by a chord?" If you have only one chord to look at, sharps and flats is the only way. If you have a harmonic progression with several chords, the "trick" is to look for the half steps relationships.
Comment: @コナーゲティ Sorry I removed the unfortunate answer. Cm maj7 chord could used in the key of C minor as e.g. an ending chord, or in the key of G major as a "iv minor", modal interchange sort of way, the Eb being a lowered sixth. Try putting a G, D or F in the bass, e.g. Cmmaj7/F - G. I have no idea how one could come up with these suggestions through any other way than practice.
Comment: C7 = C-E-G-Bflat
Answer:
...Is comparing the key signatures the only way to quickly find a relative chord?

Not necessarily for relative chords.
Relative chords are always a minor triad below a major triad with the root separated by a minor third.

The example above shows relative chord pairs - C & Am, G & Em - we don't really need to know the keys that are indicated before the Roman numerals. In fact, you will notice that pair C & Am in C major flip their order to Am & C in A minor when we take note of the tonic and mediant chord identities in the key. It's nice to know that about the relationship to the keys, but it isn't absolutely necessary.
You can apply the same rule for chords to scales but swap out the term root (for chords) with tonic for scales. The relative scale pairs are a (natural) minor scale below a major scale with the tonics separated by a minor third.
However, I think it may best best to know relative scales by their shared key signatures for the sake of know the specific tones in each scale. So it's fairly easy to say that B minor and D major are relative scales without knowing the key signatures (we know this because the tonics are a minor third apart) but it's very helpful to know that both scales have F# and C#.
Of course all of this relies on knowing the intervals of the musical alphabet. If you don't know A to C is minor third (and not a major third) you won't be able to find relative pairs.
As mentioned in comments, you should refer to these relationships as relative rather than equivalent. The term equivalent is usually used for enharmonic equivalent which is a very different meaning. I have seen some people suggest that relative chords can be used for substitutions. For example, an Am chord could substitute for a C major chord. Even in that case you should say substitution rather than equivalent.

...if you have a C7 chord, which has one flat, making it the equivalent of an F Major chord

I think you may be fixing up relative major/minor and equivalent with some way to know a particular chord belongs to a particular key.
C7 does indeed have one flat, and so does the key signature for F major, and the tonic chord of F major is the F major chord. But, that doesn't make C7 and F equivalent chords. C7 is the dominant chord of F major.
If that is sort of what you were thinking, the formula won't work for all chords/keys. Example, the Bb7 chord uses two flats and is the dominant of Eb major, but Eb major uses three flats. The number of flats doesn't match in that case. The chords B7 and Eb major both used two flats, but again that isn't a rule for all tonic and dominant pairs, example: Ab7 dominant to Db major, none of the flat counts for chords or key match.
If you meant some other association of chords and keys, please update your question with some more detail.
Comment: The OP's comment about the Cm maj7 chord is a better example than the C7. Cmmaj7 is a nice chord to use in e.g. G major as a iv minor in a modal interchange sort of way. To make the example even more extreme: Cmmaj7/F - G is a nice movement to tonic in G. But seeing just the Cmmaj7/F, how could one possibly be able to theoretically calculate that a good probable candidate key is G major, which doesn't have any flats and has an F# instead of F. I think the only working solution is practice. :)
Comment: @piiperi, I gave an approach for relative chords and then tried to point out the "equivalent" idea is unclear or perhaps a misunderstanding of something. Simply put, "How would you find the equivalent of something like a Cmin/maj7" ...the enharmonic equivalent is something like `B#min/maj7`. Anything else seems to be a misunderstanding of terms/concepts.
Comment: The question uses words very liberally. Conceptual interchange! I think the actual question behind the words is to be able to figure out what the key might be, even in the presence of out-of-scale notes and chords. The Cm maj7 chord highlights this problem very well: a chord that does not have B flat, but does have E flat - That's not even any regular key signature... How to know what's happening? Where is tonic? Where are we? Like you say, the solution is to look at the bigger picture, the context. Hear and feel the functions of notes and chords at each moment - they may change over time.
Comment: Yes, piperi. What are you even supposed to make of a chord that starts on E flat instead of B? Does that chord not belong to a scale, or its own unusual scale?
Answer: I'll try to answer this once more, but because many words used in the question are borrowed from different concepts than what is actually meant, we have to get some things straight first:

Equivalent: (mathematical term) having the same outcome in some function https://en.wikipedia.org/wiki/Equivalence_relation If A and B are equivalent, it doesn't matter which one you choose, the outcome will be the same. If A and B are equivalent, and B and C are equivalent, then A and C must be equivalent as well. In this sense, C7 and F cannot be said to be equivalent in any meaningful way.
Relative: "The relative minor of a particular major key, or the relative major of a minor key, is the key which has the same key signature but a different tonic;" https://en.wikipedia.org/wiki/Relative_key For chords, you can say that C major and A minor are relative, and Eb major and C minor are relative. F major and C7 are not relative.
Enharmonic: "if two notes have the same pitch but are represented by different letter names and accidentals, they are enharmonic" https://en.wikipedia.org/wiki/Enharmonic For example, C# and Db are different enharmonic spellings for the pitch that's played with the same key on the piano. C#m and Dbm are two different names for the same minor triad chord. Enharmonic = same sound, different notation. F and C7 are not enharmonic.
Chords do not have key signatures. You can't say what key signature the Am triad has. You cannot compare the key signatures of chords, because chords do not have key signatures. F major and C7 do not have the same key signature, because neither of them has a key signature to begin with. They can be used in songs with different key signatures.

The real question is something like this: if I'm presented with just one chord alone without any context, how can I quickly know possible contexts where that chord might occur, and the sets of other chords and scales that would be used in each of the contexts. And "context" here means a key, centered around a tonic note, and with a basic scale and basic chords and all possible harmonic changes that might happen inside the key while not losing track of the tonic.
If taken literally, this is an impossible task to do with any sort of theoretic logical deduction, because it produces too many possibilities. For example a popular song has F#7 - B7 - E7 - Am. If you see just the F#7 chord, would you consider the possibility that the key might be Am? How about if the same motion is done with dim chords, so A#dim7 - D#dim7 - G#dim7 - Am. Deduction rules for any dim chord would list basically all contexts as possibilities.
Or, an A major chord is often used to get to a Dm chord like: A - Dm - E - Am. If you see an A major chord, remember to add to the logic rules that the key can be A minor. Or the Cm maj7 example… let's make it simpler: Cm. The key might be G major. It's a common trick to use a minor IV chord. The list of rules and tricks to consider is endless. Any chord or note can be used in any key. But once you have some context: bits of preceding chords and melody, then the list of plausible possibilities is narrowed greatly. You feel what the tonic might be.
The only practical way to obtain the ability to do what you want is: practice, experience and training. You play songs in different keys and you develop a sensitivity to feel where the tonic, i.e. home base note is. You instantly remember sets of chords that are normally used in each key. You just think of a key, and it instantly brings a set of notes and chords to mind. You develop a sensitivity to feel when the harmony is leaning on the subdominant or dominant or tonic side. When you know your basic tonic - subdominant - dominant thing well, and then you encounter a secondary dominant, you'll understand how it works. When you've played a few songs in G major that has the C minor trick, you'll remember it. Once you've played tritone substitutions, you'll remember that a dominant V can be replaced with a 7th/9th/13th rooted one semitone above the tonic.
Answer: Check out the circle of fifths... study it, it will change your life. The inner ring are the relative minors of the outer ring.

The major and minor chords within a key can be looked at and grouped "SHAPED" two different ways.
C major for example
Method 1: the major chords will be on each side. The relative minor is below either the remaining two minor chords on each side.
Method two: same concept just using the outer ring,... the minor chords follow the 5th on the outer ring.
The diminished chord also follows just after the the last minor chord on the wheel.
This a great visual tool to reference. It will help open up your understanding of choosing which key you want your music to be in.  For example if you play a C major chord followed by its relative A minor.. you still have the ability to decide if it's going to stay in that key (C major /Ionian) or F Major (C mixolydian) or G Major (C Lydian). It all depends on the remaining chords you chose to fill that "SHAPE".
Please note this is only for the Natural Scale, although it covers the majority of the westernized music we hear today.
Comment: The diagram helps to see a visual grouping of chords that are often used together in harmonically simple songs. But I have a hard time seeing how it would be used to solve the Cm maj7 question. And when you're playing an instrument, do you take glimpses at the diagram all the time? Another important exercise is to learn and play lots of songs on your instrument. Then the things are mapped to something you can play, and the actual instrument becomes a reference. Which instrument has the circle diagram as its playing interface? The accordion's left hand side has a linear non-circular version. :)
Comment: @piiperi as a 12 year old I could play a handful of Van Halen songs that sounded just like the studio version. However at the time if you asked me how to play CMaj7 chord I wouldn't of had a clue. Music is a language and the circle of Fifths clearly give a representation of how each scale gets its notes along with each note relative note. CmMaj7 is not in the natural scale. It can be looked at as the i chord of the harmonic minor scale.
Comment: Yeah I know "where you're coming from" and the circle of fifths is good to know about. I voted it up +1. The OP of this question was apparently looking for tools for more complicated things like the Cmmaj7 chord, in a way that I don't think is even possible with theoretical "calculation". Anyway, I recommend all aspiring musicians to learn to feel elemental harmonic turns by ear. Where does the home base note seem to be now? If you play a random note, which note of the scale does it feel to be relative to what you're hearing? Where is the harmony leaning on now - tonic, subdominant, dominant?


Can anyone explain to me why $(34)(123) = (124)$?

Question: $$\begin{align}
(34)H&=  \{(34)(1),(34)(123),(34)(132)\}\\
& = \{(34),(124),(1432)\}.
\end{align} $$
Can anyone explain to me why $(34)(123) = (124)$?
I don't understand coset multiplying can you help me with this
Comment: I think its a Typo! Since $(34)$ is an odd permutation and $(123)$ is an even permuatation, so the product $(34)(123)$ is must be an odd permuatation. However $(124)$ is even!
Answer: Its depends of the composition is from right to left or the opposite. If you consider from right to left, so $$1 \mapsto 2 \mapsto 2, \qquad 2 \mapsto 3 \mapsto 4, \qquad 4 \mapsto 4 \mapsto 3, \quad \mbox{and} \quad 3 \mapsto 1 \mapsto 1.$$ Hence $(34)(123) = (1243)$. Similiarly, from left to right, we have $(34)(123)=(1234).$ In both cases, $(34)(123) \neq (124)$. Comparing with $(34)(132)=(1432)$, the result was to be $(34)(123) = (1243)$. There must have been just one typo.
Answer: If $\sigma=(123)$, $\tau=(34)$, and we compose right-to-left (as is consistent with your other compositions), then
$$\begin{align}
1 &\stackrel{\sigma}{\mapsto} 2 \stackrel{\tau}{\mapsto}2, \\
2&\stackrel{\sigma}{\mapsto} 3 \stackrel{\tau}{\mapsto} 4, \\
4 &\stackrel{\sigma}{\mapsto} 4 \stackrel{\tau}{\mapsto} 3, \\
3 &\stackrel{\sigma}{\mapsto} 1 \stackrel{\tau}{\mapsto} 1,
\end{align}$$
so $\tau\sigma=(34)(123)=(1243)$.


Is it possible to create entry into LDAP server without RDN with only attributes?

Question: We are using ldapjs node module to communicate with LDAP servers like Microsoft Active Directory, Apache DS and Open LDAP. As per our understanding from here:

DNs can be comprised of zero or more components, which means that it is legal to have a DN without any components at all.

Is it possible to create entry into LDAP server with only attributes without any RDN in my Base DN?
For example, if I wanted to create inetOrgPerson entry into LDAP server without RDN, creating entry as below:
var ldap = require('ldapjs');
var client = ldap.createClient({
  url: 'ldap://xxxxxxxx:389'
});
client.bind('xxxxxxxx', 'xxxxxxxxx', function(err) {
  if(err){
      console.log('error',err);
  }else{
      console.log('bind is success');
  }
});

var newDN = "ou=testou,dc=xxxx,dc=com";
var newUser = {
    objectClass: 'inetOrgPerson',
    sn: 'test'
  }

client.add(newDN, newUser, function(err) {
  if(err){
      console.log('error',err);
  }else{
      client.unbind(function(err) {
          if(err){
              console.log('error unbind : ',err);
          }else{
              console.log('unbind is success');
          }
        });
  }
})

After executing above code there should be entry in the OU testou with sn as test. Any inputs will help. Thank you all.
Comment: What do you mean 'without RDN'? when you are using the RDN 'ou=testou,dc=xxxx,dc=com'?
Comment: As per the RFC4514 the RDN will have any one below:
      CN  -    commonName (22.214.171.124)
      L     -  localityName (188.8.131.52)
      ST  -   stateOrProvinceName (22.214.171.124)
      O   -    organizationName (184.108.40.206)
      OU  -    organizationalUnitName (18.104.22.168)
      C    -   countryName (188.8.131.52)
      STREET - streetAddress (188.8.131.52)
      DC  -    domainComponent (0.9.2342.19200300.100.1.25)
      UID  -   userId (0.9.2342.19200300.100.1.1)
Now when I say without RDN, without any of the attribute type in DN. Thank you.
Answer: While it is legal to have a DN with zero component, it is reserved for the rootDSE.
It is mandatory for any entry to have a non-empty DN, and therefore to have a non-empty RDN.


Why is $2\sqrt{x+1}-2\geq\frac{\sqrt{x}}{2}$ for $x \in \mathbb{N}$?

Question: I have found following formula stands:
$2\sqrt{x+1}-2\geq\frac{\sqrt{x}}{2}$
($x \in \mathbb{N}$)
I have wondered why this is true. I have checked its rightness on the graph drawing tools, but I want to know the mathematical proof of this.
Although I can prove it for $x \in \mathbb{N}, x\geq2$, as following:
$2\sqrt{x+1} - \sqrt{x}/2 \geq 2\sqrt{x} - \sqrt{x}/2 = \frac{3}{2}\sqrt{x}\geq\frac{3}{2}\cdot \sqrt{2} \geq2$
and prove the rightness in case $x=1$ by direct calculation,
I want to know whether it is possible to prove this formula without dividing the case of $x=1$ and others.
Thank you.
Comment: Try using induction
Comment: Decide if you  are using $x$ or $t$. Then square both sides...
Comment: In the induction, try multiplying by $\frac{\sqrt{n+1}}{\sqrt{n}}$
Comment: That last inequality is not true. We have to instead prove $\frac{2(x+1)-2\sqrt{x+1}}{\sqrt{x}} \leq 2\sqrt{x+2} - 2$. Since the difference is quite small, derivatives are useful
Comment: @LukeTux Thank you for your answer.
I have tried the induction proof by following way:
1. It is true for $x = 1$
2.Assuming it is true in $x$,
prove $2\sqrt{x+2} - 2 \geq \sqrt{t+1}/2$ as following direction:

$2\sqrt{x+2} - 2 -\sqrt{t+1}/2 \geq 2\sqrt{t+1} - 2 -\sqrt{t+1}/2$

And I am wondering how to do the left part of the proof
Comment: @YuvalPeres Thank you for your suggestion. and editting  I revised $t$ to $x$.
Comment: @LukeTux
Thank you for your advices. Based on your advice, I come up as following:

If it is true for x,
$2\sqrt{x+1} - 2 \geq \frac {\sqrt{x}}{2}$.
Then, multiplying by $\frac{\sqrt{x+1}}{\sqrt{x}}$, following is obtained:
$2\frac{x+1}{\sqrt{x}} - 2 \frac{\sqrt{x+1}}{\sqrt{x}} \geq \frac{\sqrt{x+1}}{2}$.
As for the left side,
$2\frac{x+1}{\sqrt{x}} - 2 \frac{\sqrt{x+1}}{\sqrt{x}} \leq 2\frac{x+2}{\sqrt{2}} - 2 $,
If I can show $\frac{x+2}{\sqrt{x}} \leq \sqrt{x+2}$ is true, then this proof by induction is completed.
Could you please give me some hints to show this part? Thank you.
Comment: The last inequality is :
$2\frac{x+1}{\sqrt{x}} - 2 \frac{\sqrt{x+1}}{\sqrt{x}} \geq 2\frac{x+2}{\sqrt{x}} -2$

(I wrote the formula mistakenly. It is not $2\frac{x+1}{\sqrt{x}} - 2 \frac{\sqrt{x+1}}{\sqrt{x}} \geq 2\frac{x+2}{\sqrt{2}} -2$)

$-2\frac{\sqrt{x+1}}{\sqrt{x}} = -2\sqrt{\frac{x+1}{x}} = -2\sqrt{1+\frac{1}{x}} \leq -2$
Comment: In the above comment, I wrote mistakenly and the first two formula is not $\geq$, but should be $\leq$.
And as for $2\frac{x+1}{\sqrt{x}} \leq 2\frac{x+2}{\sqrt{x}}$, thus, the following formula (also shown in above comments) is true:
$2\frac{x+1}{\sqrt{x}} -2\frac{\sqrt{x+1}}{\sqrt{x}} \leq 2\frac{x+2}{\sqrt{x}} -2$
Comment: @LukeTux Also, there might be ways to prove deductive without using derivatives, it is really a strong way to use derivatives to prove it is true.
Answer: You can set $f(x)=2\sqrt{x+1}-2-\frac 12\sqrt{x}$
The derivative $f'(x)=\frac 1{\sqrt{x+1}}-\frac 1{4\sqrt{x}}$
It is zero when $(4\sqrt{x})^2=(\sqrt{x+1})^2\iff 16x=x+1\iff x=\frac 1{15}$
The derivative is $-$ then $+$ so $f$ is $\searrow$ then $\nearrow$ with a minimum in $\frac 1{15}$.
We could calculate $f(\frac 1{15})$ but since we are only interested in naturals let just calculate
$f(1)=2\sqrt{2}-2-\frac 12\sqrt{2}>0$ as you have noticed yourself.
And since it is increasing, it's true for all $x\ge 1$ not only integers.

For sake of completion, $f(\frac 1{15})=\frac 12\sqrt{15}-2<\frac 12\sqrt{16}-2=0$
So there exists a zero of $f$ in the interval $[\frac 1{15},1]$ in addition to $x=0$.
We can calculate it by squaring both sides:
$(2\sqrt{x+1})^2=(2+\frac 12\sqrt{x})^2\iff 4x+4=4+\frac 14x+2\sqrt{x}\iff\frac {15}4x=2\sqrt{x}\iff \\\sqrt{x}=\frac{8}{15}\text{ or }x=0$
So actually the inequality is true for all $x\ge \frac{64}{225}$
Side note: this direct calculation of the zero, shows there are only two zeroes, $x=0$ and $x=\frac{64}{225}$, so you can deduce directly (without derivative) that since $f(1)>0$ and $f$ is continuous then $f$ cannot change sign on $[1,+\infty)$
Comment: Yes it's because $f$ is continuous which is quite immediate, should have mentioned it.
Comment: Thank you for your answer.
Using derivative is actually a good way to prove this. I didn't consider this way.
Comment: Thank you for your additional remarks and sharing aother solution.
 I have a question regarding it, is the fact "f cannot change sign on $[1, \infty)$" deduced from "the continuity of f" and the fact that there is no x where f(x) = 0 in $[1, \infty)$?
Comment: +1 and I was about to answer this way but scroll down and saw your answer.
Answer: Say $y=\sqrt{x} \geq 1$ if $x\geq 1$. Then you have to prove $$4\sqrt{y^2+1}\geq 4+y$$ i.e. (you can square inequality since both sides are nonegative) $$16(y^2+1)\geq 16+8y+y^2$$ i.e.
$$y(15y-8)\geq 0$$ which is clearly true.
Comment: Thank you for your answer. It is exactly very useful for to take the square of both sides to prove inquality.
Answer: Using the fact that $\sqrt{a}-\sqrt{b}=\dfrac{a-b}{\sqrt{a}+\sqrt{b}}$ , we have
$$\begin{aligned}2\sqrt{x+1}-\frac{\sqrt{x}}{2}&=\frac12\left(4\sqrt{x+1}-\sqrt{x}\right)\\
&=\frac12\cdot\frac{16(x+1)-x}{4\sqrt{x+1}+\sqrt{x}}\\
&=\frac{15x+16}{2(4\sqrt{x+1}+\sqrt{x})}\\
&\geqslant\dfrac{15(x+1)}{10\sqrt{x+1}}\\
&=\dfrac32\sqrt{x+1}\\
&\geqslant\frac32\sqrt{2}\\
&=\sqrt{\frac92}>2 \end{aligned}$$
for $x\in\mathbb{N}$, so in fact the inequality is strict.
Comment: Thank you for your answer. I have tried rationalizing denominator, but I couldn't find any good ways to evaluate the result of the formula after it by myself.


Como mostrar tela de "carregando" com modal bootstrap em qualquer processo do servidor c#

Question: Necessito de que as minhas páginas mostrem a todo processo do servidor uma tela com um tipo de Carregando usando o modal bootstrap que criei abaixo. Meu problema é conseguir mostrar isso em todos os processos.

Existe alguma forma de fazer isso?
Alguém tem alguma ideia?

Meu código:

                                     Aguarde

Answer: Você pode fazer isso para todos os ajax da sua aplicação, utilizando os eventos  globais.
Exemplo:
$(document).ajaxSend(function () {
    ///chama seu processando
});

$(document).ajaxComplete(function () {
    //finaliza seu processando
});

Você também pode usar o .ajaxError() para criar um tratamento de erro global, conforme expliquei aqui.
Comment: muito obrigado mesmo pela sua ajuda.. na verdade a dica que você me passou não resolveu, mas eu encontrei outra forma de fazer que funcionou perfeitamente como eu queria.. apenas defino o onchange de todos os controles que preciso desse processo e quando termina eu apenas faço a chamada para fechar o modal.. de qualquer forma, vou definir sua resposta como correta, pois nos testes eu percebi que funciona também, para outras formas de se fazer.. =D
Comment: agradeço pela informação que me passou, mas aparentemente não funciona pra o que eu quero.. esse procedimento executa perfeitamente na abertura da página, mas em todos os procedimentos restantes nada acontece.. será que estou fazendo algo errado? tem alguma ideia do que possa ser?
Comment: @AlisonVieira, então amigo, esse processo ele vai funcionar só para suas requisições ajax. para as de mais eu uso nas minhas aplicações de uma forma um pouco diferente. Crio a waitbar apartir de uma class especifica e deixo a mesma no body de todas as minhas paginas, ao finalizar o carregamento com $(document).ready eu removo a class.