Factorising $t ^6 − 10t ^4 + 31t ^2 − 30$

Question: Does anyone know how I can factorise $t ^6 − 10t ^4 + 31t ^2 − 30$? I can see the answer using WolframAlpha but I want to know how to do it by hand without guessing roots.
Comment: You should guess one root $r_1$ and then do divide the polynom by $(t-r_1)$
Comment: @Nehorai Thanks, I am wondering if there is a shortcut at all
Answer: Write the polynomial in terms of $X:=t^2$ as $X^3-10X^2+31X-30$. Its roots $\alpha$, $\beta$ and $\gamma$ can be found by the rational root test. The roots of $t^6-10t^4+31t^2-30$ are then $\pm\sqrt{\alpha}$, $\pm\sqrt{\beta}$ and $\pm\sqrt{\gamma}$.
Answer: Hint:
$$t^6 - 10t^4 + 31t^2 - 30 = t^2(t^4 - 10t^2 + 25) + (6t^2 - 30)$$
Can you take it from here?
Comment: Hint #2:  Check for a common binomial factor.
Comment: Hint #3: $t^2-5$ is the key factor
Comment: Hint #4: @Servaes, for equations in quadratic form, a quick attempt at factoring can be done by grouping and **completing the square**.  *Warning*: This does not always work for every equation in quadratic form, though.
Comment: I honestly don't see how you found this expression, or how it helps...
Comment: Indeed, @z100!  =)
Comment: Fair enough, this expression makes the factor $t^2-5$ more clear. But I don't see how one is supposed to find the expression you give?
Comment: @Servaes : Experience, a lot of practices :-)
Comment: Aha, I hadn't realised it was a square.
Comment: how did you spot it was a square?
Comment: @helppls,well $t^6 - 10t^4$ is almost a square, whence you can complete the square:

$$(t^6 - 10t^4 + 25t^2) - 25t^2 = {t^2}(t^2 - 5)^2 - 25t^2.$$

Now, all that remains to be done is to group the $-25t^2$ with $31t^2 - 30$.  =)


How to combine a search phrase with a wildcard using Lucene.Net?

Question: I am passing a search query to the Lucene QueryParser.Parse(string query) method, and then passing the result to Searcher.Search(Query query, int n).
A string of:
"system cleaner"

returns 1 hit.
A string of:
"system clean*"

or:
"system clean\*"

returns 0 hits.
How can I provide a search query that uses both a quoted phrase and a wildcard?
Answer: The QueryParser doesn't support that.  You can construct such a query using the SpanQuery API:
SpanQuery firstwordQuery = new SpanTermQuery(new Term("myField", "system"));
//Unfortunately, Lucene.Net doesn't have SpanMultiTermQueryWrapper...
SpanQuery secondwordQuery = new SpanRegexQuery(new Term("myField", "clean.*"));
SpanQuery[] spanClauses = new SpanQuery[] {firstwordQuery, secondwordQuery};
Query finalQuery = new SpanNearQuery(spanClauses, 0, true);

Comment: Nice example. Thanks!
Comment: For people working in JAVA Lucene v8 who came to this answer, you can use `SpanMultiTermQueryWrapper` with `WildcardQuery` as an alternative to `SpanRegexQuery`


How to find the user name who merged the pr to the base branch from the octokit library

Question: Can anyone tell me that how to fetch the user name who merged the pr by the octokit.request api call.
I can fetch all the prs from octokit.request method with the query parameter state=all value. It is returning the array having all PRs (open and closed all). We can see that PRs with merged_at value is not equal to null are the pr which are merged.
Now how to find the user name who merged this pr.
Answer: Let me answer my question.
These are the steps.

Get the merged PR by retrieving closed PRs and check for merged_at!=null.
Get the user login from response of step 1, i.e. by mergedPRs.user.login.
Get All commits of the main branch.
Filter and take those commits only whose commit.commit.commiter.name==='GitHub'. this will filter and take those commit only by which the PR is merged.
now If step2===step4 then you got the answer. i.e. mergedPRs.user.login === filteredCommit.commit.author.login.
You got the answer, it will tell you the pr is created and merged by same person or not.

Here is the code for the same.

     const allCommits : Array<any> = await getAllCommits(data);
     const mergedPRs : Array<any> = await getMergedPRs(data);
     const MergeCommitsUserDetailsWithsha : Array<UserWithCommitSha> = []
     allCommits.forEach(commit => {
         if(commit.commit.committer.name==="GitHub"){
             let objectToPush : UserWithCommitSha = {username:commit.author.login, commitsha:commit.sha};
             MergeCommitsUserDetailsWithsha.push(objectToPush);
            }
         });
     const selfMergedPRs : Array<any> = mergedPRs.filter(pr=>{
         return MergeCommitsUserDetailsWithsha.some(element => element.username===pr.user.login && element.commitsha===pr.merge_commit_sha);
     });

     let result : Array<SelfMergedPRs>=[];
     selfMergedPRs.forEach(pr => {
            result.push({url:pr.html_url, userName:pr.user.login, commit:pr.merge_commit_sha, headBranch:pr.head.ref, baseBranch:pr.base.ref})
     });

     return result;

Here the getAllCommits function is returning all commits of the default branch of the given repository.
getMergedPRs returns the PRs which are closed by merging it.
In some method we are filtering those PRs in which the author's login who created the PRs is same as the merge commit's author's login who merged the PR.


Deriving the moments of Student-t distributions

Question: I am looking to derive moments for several distributions. For example, I've used moment generating functions for the standard normal distribution to get:
mean =0, variance = 1, skewness = 0, kurtosis = 3
I'm looking for a similar method to do the same for the student-t distribution.
Moment generating functions are too complicated (or don't exist) for the this distribution and I've searched for an alternative on google but the only information I've found is it's extremely complicated to derive these:
mean = μ, variance = $\sigma^2 \frac{v}{v-2}$`, skewness = 0, kurtosis = 3 + $\frac{6}{v-4}$
If I have not made it clear enough than what I want to do is derive the moments shown on page 4. Both the lower moments and higher moments.
Comment: Mean equal to $\mu$? Are you talking about the central or non-central distribution?
Comment: Since those are standard results, I think the `self-study` tag should appear in your question. First and third moments (assuming $\nu$ is large enough) are obvious by symmetry. For second and fourth moments, you can use the representation $X=\mu+\sigma\times Z/\sqrt{W/\nu}$ where $Z$ is standard normal and $W$ is $\chi^2_\nu$.
Comment: you could try to use the characteristic function
Comment: @JohnK Central. I'll edit the question to make it more clear.
@Xi'an Can this be applied to the non central distribution? Your comment has confused me somewhat. I understand if `v` is large enough the distribution converges to a normal. But how do you get it by not giving `v` a value?
Answer: There are various ways to find the moments of the T-distribution, but the simplest method is to use the mixture representation using the normal distribution.  If $T$ has a Student's T distribution with $\varphi$ degrees-of-freedom then we can write it via the mixture $T|\lambda \sim \text{N}(0, \tfrac{1}{\lambda})$ with $\lambda \sim \text{Ga}(\tfrac{\varphi}{2}, \tfrac{\varphi}{2})$ (i.e., as a mixture of normal distributions where the precision is gamma distributed).  Using this mixture representation the density function for the Student's T distribution can be written as the integral:
$$\begin{equation} \begin {aligned}
\text{St}(t|\varphi)
&= \int \limits_0^\infty \text{N}(t|0,\tfrac{1}{\lambda}) \text{Ga}(\lambda|\tfrac{\varphi}{2},\tfrac{\varphi}{2}) \ d \lambda.
\end{aligned} \end{equation}$$
Using this mixture representation, the raw moments of $T$ can be obtained via the law of iterated expectation, using the known moments of the normal distribution.  The conditional moments are:
$$\mathbb{E}(T^k|\lambda) = \int \limits_{-\infty}^\infty t^k \text{ N}(t|0,\tfrac{1}{\lambda}) \text{ } dt = \begin{cases}
0 & & \text{if } k \text{ is odd}, \\[6pt]
\frac{k!}{2^{k/2}(k/2)!} \lambda^{-k/2} & & \text{if } k \text{ is even}. \\[6pt]
\end{cases}$$
For values $k \geqslant \varphi$ the moments of the T distribution do not exist.  For odd values $0<k<\varphi$ the moments are zero and for even values $0<k<\varphi$ the moments are:
$$\begin{equation} \begin {aligned}
\mathbb{E}(T^k) = \mathbb{E}( \mathbb{E}(T^k | \lambda ) )
&= \int \limits_0^\infty \frac{k!}{2^{k/2}(k/2)!} \lambda^{-k/2} \text{ Ga}(\lambda|\tfrac{\varphi}{2},\tfrac{\varphi}{2}) \text{ } d\lambda \\[6pt]
&= \int \limits_0^\infty \frac{k!}{2^{k/2}(k/2)!} \lambda^{-k/2} \cdot \frac{\varphi^{\varphi/2}}{2^{\varphi/2} \Gamma(\tfrac{\varphi}{2})} \lambda^{\varphi/2-1} \exp \Big( -
\frac{\varphi}{2} \lambda \Big) \text{ } d\lambda \\[6pt]
&= \frac{k!}{2^k (k/2)!} \cdot \frac{\Gamma(\tfrac{\varphi-k}{2})}{\Gamma(\tfrac{\varphi}{2})} \cdot \varphi^{k/2} \\
&\quad \quad \quad \quad \times \int \limits_0^\infty \frac{\varphi^{(\varphi-k)/2}}{2^{(\varphi-k)/2} \Gamma(\tfrac{\varphi-k}{2})} \lambda^{(\varphi-k)/2-1} \exp \Big( -\frac{\varphi}{2} \lambda \Big) \text{ } d\lambda \\[6pt]
&= \frac{k!}{2^k (k/2)!} \cdot \frac{\Gamma(\tfrac{\varphi-k}{2})}{\Gamma(\tfrac{\varphi}{2})} \cdot \varphi^{k/2} \int \limits_0^\infty \text{Ga}(\lambda|\tfrac{\varphi-k}{2},\tfrac{\varphi}{2}) \text{ } d\lambda \\[6pt]
&= \frac{k!}{2^k (k/2)!} \cdot \frac{\Gamma(\tfrac{\varphi-k}{2})}{\Gamma(\tfrac{\varphi}{2})} \cdot \varphi^{k/2} \\[6pt]
&= \frac{\Gamma(\tfrac{k+1}{2})}{\sqrt{\pi}} \cdot \frac{\Gamma(\tfrac{\varphi-k}{2})}{\Gamma(\tfrac{\varphi}{2})} \cdot \varphi^{k/2}. \\[6pt]
&= \frac{\Gamma(\tfrac{k+1}{2})}{\sqrt{\pi}} \cdot \frac{\varphi^{k/2}}{\prod_{i=1}^{k/2} (\tfrac{\varphi}{2}-i)}. \\[6pt]
\end{aligned} \end{equation}$$
Application of this formula for the even moments yields:
$$\begin{equation} \begin{aligned}
\mathbb{E}(T^2) &= \frac{\varphi}{\varphi-2} & & & \text{for } \varphi > 2, \\[6pt]
\mathbb{E}(T^4) &= \frac{3 \varphi^2}{(\varphi-2) (\varphi-4)} & & & \text{for } \varphi > 4, \\[6pt]
\mathbb{E}(T^6) &= \frac{15 \varphi^3}{(\varphi-2) (\varphi-4) (\varphi-6)} & & & \text{for } \varphi > 6. \\[6pt]
\end{aligned} \end{equation}$$
You can now obtain the kurtosis, etc., via algebraic manipulation of the raw moments.  In particular, the kurtosis is:
$$\begin{equation} \begin{aligned}
\mathbb{Kurt}(T) = \frac{\mathbb{E}(T^4)}{\mathbb{E}(T^2)^2}
&= \frac{3 \varphi^2}{(\varphi-2) (\varphi-4)} \Big/ \Big( \frac{\varphi}{\varphi-2} \Big)^2 \\[6pt]
&= \frac{3 (\varphi-2)}{\varphi-4} \\[6pt]
&= \frac{3 \varphi - 6}{\varphi-4} \\[6pt]
&= \frac{3 \varphi - 12}{\varphi-4} + \frac{6}{\varphi-4} \\[6pt]
&= 3 + \frac{6}{\varphi-4}. \\[6pt]
\end{aligned} \end{equation}$$
Comment: Yes, that is correct, but it has nothing to do with whether they can be expressed in closed form.
Comment: Are there closed form equations to get non-integer moments. For example, for a t-distribution with 2.1 degrees of freedom could we get the 2.05th moment ($k=2.05$)?
Comment: @DylanDijk: I doubt it, but you'd need to do the derivation (e.g., of non-integer normal moments) to check.
Comment: Ok thanks, I was then just wondering if we know that the moments are finite, for moments smaller than the number of degrees of freedom. For example for 3 degrees of freedom is the 2.5th moment finite?


Proof of $n^2 \leq 2^n$.

Question: I am trying to prove that $n^2 \leq 2^n$ for all natural $n$ with $n \ne 3$.
My steps are:

induction base case: $n=0:$ $0² \leq 2⁰$ which is okay.
inductive step: $n \rightarrow n+1:$ $(n+1)²\leq2^{n+1}$ $$(n+1)^2 = n^2 + 2n + 1 = ...help...\leq 2^{n+1}$$

I know the bernoulli inequality but don't know where to use it, if I even need to. I have problems when it comes to proving things which are based on orders..
Comment: Because it is false for $n = 3$, you should only expect the induction step to work when $n \ge 4$.  I would call the case $n=4$ the base case, and check $n=0,1,2$ separately.
Comment: You know you can make $n^2 \leq 2^n$ by the induction assumption (once you've done Trevor's suggestion). Can you make $2n+1$ less than or equal to something useful?
Comment: A proof that is not by induction: You check the cases $0,1,2,4$ directly. For $n\ge5$, note that $n^2=\binom{n}{1}+\binom{n}2+\binom{n}{n-2}<\sum_{i=0}^n\binom{n}{i}=2^n$.
Comment: @anonymous $2n+1 \leq (1+n)^2$ ?
Comment: [Related](http://math.stackexchange.com/q/439026/462).
Answer: First since one must have $n\neq 3$, the induction base must be $n=4$.
For the induction step: Suppose $n^2\le 2^n$.
Then,
$$(n+1)^2=n^2+2n+1\le 2^n+2n+1\le 2^n+2^n=2^{n+1}$$
because $2n+1\le 2^n$ for $n\ge 3$ (why is this true?).
If you had started with inductive base $0,1$ or $2$, then you would have ran into problems because $2n+1\le 2^n$ doesn't hold for $n=2$
Proof of $2n+1\le 2^n$ for $n\ge 3$.
Induction base: For n=3, $$2\cdot 3+1=7\le 8=2^3$$
Induction step: Assume that for $n\ge 3$, $2n+1\le 2^n$. Then
$$2(n+1)+1=2n+1+2\le 2^n+2\le 2^n+2^n=2^{n+1}$$
and so we are done
Comment: Nameless, $2n+1 \leq 2^n$ because $2n+1 \leq n^2$ ?
Comment: @doniyor Hint: (it takes another induction)
Comment: @doniyor To prove $2n+1\le 2^n$ you will need another, but much simpler, induction
Comment: sorry, i am coming back to your question again: i am trying to find why $2n+1\leq 2^n$
this is an induction proof for $n\geq3$, should i do it?
Comment: @doniyor I think my edit will clear your doubts
Comment: oh okay, thanks, so in cases like this, do i have to prove any inequality on the way of main proof?
Comment: @doniyor Perhaps you will need many inductions to reach the end. It all depends on what the problem is
Comment: yeah you are right..
Answer: An analysis type proof.
$x^{1/x}$ has its maximum at $x = e$
and is increasing for $1 < x < e$ and
decreasing for $x > e$.
$2^{1/2} = 4^{1/4}$,
so $x^{1/x} < 2^{1/2}$ for $x > 4$
or $x^2 < 2^x$ for $x > 4$.
I am surprised that this worked out so nicely.
Obvious generalization:
If $x > e$ and $y$ satisfies
$1 < y < e$ and $y^{1/y} = x^{1/x}$
then $z^{1/z} < y^{1/y}$ for $z > x$
or $z^y < y^z$ for $z > x$.
Answer: Another possibility is to write $$2^n = \sum\limits_{k=0}^n C_n^k \geq 1+n+ \frac{n(n-1)}{2} + \frac{n(n-1)(n-2)}{6} \geq n^2$$ for $n \geq 5$. It can be interpreted as follow: the set $\{1,...,n\}$ has at least $n^2$ subsets of cardinality at most three, and exactly $2^n$ subsets; therefore, $2^n \geq n^2$.
Answer: Here's another analytic proof.  First note that $$\frac{2}{\operatorname{log}{2}}\operatorname{log}{4}=4.$$
The value of $2/\operatorname{log}{2}$ is a bit less than $3$.  (Proof. $\frac{2}{\operatorname{log}2}<3\Leftrightarrow 2<3\operatorname{log}2\Leftrightarrow e^2<e^{3\operatorname{log}2}=8$, which is clearly true as $e<2.75=\frac{11}{4}$. $\square$) Thus for $n>4$, $$\frac{d}{dn}\left(\frac {2} {\operatorname{log} {2}}\operatorname{log} {n}\right) = \frac {2} {\operatorname{log}{2}}\frac{1}{n} <1=\frac{d}{dn}\left(n\right).$$
Thus $\frac{2}{\operatorname{log}{2}}\operatorname{log}{n}\leq n$ for $n\geq 4$ by the racetrack principle.  Equivalently, $\log_2 n^2 \leq \log_2 2^n$, from which we obtain $n^2\leq 2^n$.

Proof of $n^2 \leq 2^n$.


ERRO NO FLUTTER - The method '[]' was called on null

Question: Estou começando com o Flutter, e me deparei com o erro

The method '[]' was called on null.

Estou testando uma api para me retornar os dados, porem sempre recebo esse erro. O estranho é que se eu reinicio a aplicação o erro some e os dados aparecem normalmente. Esse erro acontece em todas as telas que uso na api, e em todas elas se reinicio a aplicação ou volto a tela e abro-a novamente o erro não acontece.
    List<GetItems> _item;

    Future<List<GetItems>> _getItem() async {
      List<GetItems> listItem = [];

      final response = await http.get(
          'http://192.168.1.145/crud/index.php?action=getItem&id=' + widget.id);

      if (response.statusCode == 200) {
        var decodeJson = jsonDecode(response.body);
        decodeJson.forEach((item) => listItem.add(GetItems.fromJson(item)));
        return listItem;
      } else {
        print('connection error');
      }
    }

    void initState() {
      super.initState();
      _getItem().then((map) {
        _item = map;
      });
    }

return Scaffold(
  drawer: SideMenu(),
  body: SingleChildScrollView(
    child: Column(
      children: [
        Top(title: _item[0].nome),
        Container(
          margin: EdgeInsets.only(top: 20),
          height: 250,
          width: MediaQuery.of(context).size.width - 20,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(25),
              image: DecorationImage(
                image: AssetImage('assets/img/' + _item[0].imagens),
                fit: BoxFit.fill,
              )
          ),
       ),

Answer: O erro ocorre pois quando a árvore de widgets é feita, ele tenta buildar:
AssetImage('assets/img/' + _item[0].imagens)

Entretanto o _item não é inicializado, ou seja, é null. Por isso dá erro.
Você está fazendo o fetch de dados no init state e depois dando um setState. Por que não utiliza um FutureBuilder?
    FutureBuilder(
      future: _getItem,
      builder: (context, snapshot) {
        if (!snapshot.hasData) return CircularProgressIndicator();
        List<GetItems> _item = snapshot.data;
        return Container(
          margin: EdgeInsets.only(top: 20),
          height: 250,
          width: MediaQuery.of(context).size.width - 20,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(25),
              image: DecorationImage(
                image: AssetImage('assets/img/' + _item[0].imagens),
                fit: BoxFit.fill,
              )),
        );
      },
    ),

Comment: Funcionou! obrigado.
Answer: Aparentemente o seu Widget está sendo construído mais rápido do que o tempo de resposta da API, e seu initState não espera uma resposta da API. É para isso que existe o FutureBuilder você precisa mostrar uma tela de carregamento ou "nada" enquanto os seus dados estiverem carregando, uma vez carregados você pode atualizar o estado do seu Widget com a lista de dados carregadas.
FutureBuilder(
  future: _getItem,
  builder: (context, snapshot) {
    if(snapshot.connectionState == ConnectionState.done){
      if(snapshot.hasError){
        /// Terminou de carregar mas com erro
      } else {
        /// Tudo ok mostre a sua lista que está dentro snapshot.data
      }
    } else {
      /// carregando informações
    }
  },
),

Comment: Funcionou! Obrigado.


How much memory does my SQL need?

Question: I have a VM (SQL database server) that I think has more memory then it needs, however I'm not sure what I can reduce it to because I don't understand exactly what "In use", "Available", "Committed" and "Cached" memory mean.
The following is a screenshot of Task Manager after I did some load testing. Let's assume that the load won't get much more intense than this.

It seems obvious to me that 64GB of RAM is too much. I would like to understand how much I can take away without reducing performance.
Does this mean I only need 8GB because that is more than the "In use" amount? Or do i need to include the "cached" amount when I determine how much is needed?
Answer: SQL Server will hold on to the RAM it allocates, so since it doesn't seem to go above 6-7 GB, I would allocate 8GB for SQL and keep 2-4 GB extra for the OS in this case (SQL always does some tasks outside the memory it allocates for sqlserver.exe.
It would be a good idea to put this value (8 GB) in the min memory settings for your sql server instance. This way, when SQL needs the memory, it wouldn't loose time allocating it first because it 'takes' the 8GB when starting.
When playing around with the RAM, you can always check the Page Life Expectancy. This will tell you how long something stays in RAM. This is a value in seconds, as long as it keeps going up, you're golden.
SELECT object_name, counter_name, cntr_value
FROM sys.dm_os_performance_counters
WHERE [object_name] LIKE '%Buffer Manager%'
AND [counter_name] = 'Page life expectancy'

As long as it stays above 300, you're OK. Lower values would indicate some memory pressure. This could occure after doing large sorts, updating/rebuilding indexes, ... Don't freak out if this value is low after restarting the instance, it can never be greater then the time SQL is running.
A second interesting counter is the Buffer Cache Hit Ratio, this will tell you how many of the previous requests (last few seconds) were fetched from memory.
SELECT CAST(A.cntr_value1 AS NUMERIC) /
 CAST(B.cntr_value2 AS NUMERIC)* 100 AS Buffer_Cache_Hit_Ratio_Percentage, A.cntr_value1 As Cache_Hits, B.cntr_value2 AS Cache_Lookups
 FROM ( SELECT cntr_value AS cntr_value1
 FROM sys.dm_os_performance_counters
 WHERE object_name = 'MSSQL$SQL01:Buffer Manager' AND counter_name = 'Buffer cache hit ratio'
 ) AS A,
(SELECT cntr_value AS cntr_value2
FROM sys.dm_os_performance_counters
WHERE object_name = 'MSSQL$SQL01:Buffer Manager' AND counter_name = 'Buffer cache hit ratio base'
) AS B;

In this example my SQL instance is a named instance SQL01, so change it to your instance name or change MSSQL$SQL01:Buffer Manager to MSSQLServer:Buffer Manager if you have a default instance.
The higher the better. In an ideal situation, you would get 100% here, this means the whole DB is in memory.
Comment: Excellent answer, thanks for the advice. The only question I still have is what does the 3.5 number under cached mean? Does this mean that in addition to the 6.7GB being used there is another 3.5 GB of RAM being used for caching?
Comment: Cached is the sum of standby memory (cached data not in use) and modified pages (must be written to disk before it can be used again by another resource). It's not a metric I use often or know a lot more about. More info: http://blogs.technet.com/b/askperf/archive/2013/08/09/task-manager-in-windows-server-2012-and-windows-8.aspx
Answer: Great definitions in the link below.  One strategy is to guesstimate as the first answer and then to keep an eye on page faults.  As your page faults increase and as your available memory decreases you know you need to increase the amount of memory available to the VM.  VMware should also allow you to set whether or not a VM is limited to the amount of memory specified or if it is allowed to creep over that limit into a shared resource pool.
http://blogs.technet.com/b/askperf/archive/2008/01/25/an-overview-of-troubleshooting-memory-issues.aspx
Comment: I have seen upto 192GB of RAM. It was using biz logic software though.
Comment: depends on the application.  Providing VDI to several thousand users for a simple browser-based application ( required VDI for compliance reasons ) takes around 500MB - 1GB per user using Remote Desktop Services.  Using Xen Desktop or VMware is not much better.  Huge memory consumption.  Even spread across a cluster it takes around 256GB per server.

How much memory does my SQL need?


Number of solutions to equation, range restrictions per variable

Question: Find the number of solutions of the equation $x_1+x_2+x_3+x_4=15$ where variables are constrained as follows:
(a) Each $x_i \geq 2.$
(b) $1 \leq x_1 \leq 3$ , $0 \leq x_2$ , $3 \leq x_3 \leq 5$, $2 \leq x_4 \leq 6$
I believe I understand part A. I can fix the values at greater than two by adding two to each term, as in:
$(x_1 + 2) + (x_2 + 2) + (x_3+2) +(x_4+2) = 15$
$x_1+x_2+x_3+x_4=7$
So, $C(7+4-1,7) = {10! \over 7!3!} = 120$
For part B, i really have no idea where to start. Thanks for any insight!
Answer: Assume $a$ as a real number, such that $0<a <1$
The number of integral solutions should be the same as:
The coefficient of $a ^ {15}$ in
$ \left(a + a^{2} + a^{3} \right)\left(1+a + a^{2} + a^{3} + ... \right)\left(a^{3} + a^{4} + a^{5} \right)\left(a^{2} + a^{3} + a^{4} +a^{5} + a^{6}\right) $
This is same as
the coefficient of $a ^ {9}$ in
$ \left(1 + a + a^{2} \right)^{2}\left(1+a + a^{2} + a^{3} + ... \right)\left(1+a+a^{2} + a^{3} + a^{4}\right) $
This is same as
the coefficient of $a ^ {9}$ in
$  \left(1 -a^{3} \right)^{2}\left(1-a^{5}\right)\left(1-a\right)^{-4} $
Which is same as
the coefficient of $a ^ {9}$ in
$  \left(1 -2a^{3} + a^6 \right)\left(1-a^{5}\right)\left(1+4a+\frac{4.5}{2!}a^2+\frac{4.5.6}{3!}a^3+\frac{18.104.22.168}{4!}a^4+...\right) $
Which is same as
the coefficient of $a ^ {9}$ in
$  \left(1 -2a^{3}  + a^6 - a^5+ 2 a^8 \right)\left(1+4a+\frac{4.5}{2!}a^2+\frac{4.5.6}{3!}a^3+\frac{22.214.171.124}{4!}a^4+...\right) $
Which is
$\binom{12}{3} - 2\binom{9}{3} + \binom{6}{3} - \binom{7}{3} + 2\binom{4}{3} = 45$
Comment: Nice work. But in the last two lines perhaps you have gone for the coefficient of $a^6$ instead of $a^9$? E.g. I think the first factor in the 2nd last line should be $(1-2a^3-a^5+a^6+2a^8)$ instead of $(1-2a^3-a^5+a^6)$.
Answer: By similar reasoning to (a) we can simplify the problem to:
\begin{eqnarray*}
x_1+x_2+x_3+x_4 &=& 9 \qquad\qquad\text{(*)} \\
\text{with } && 0 \leq x_1 \leq 2 \\
&& 0 \leq x_2 \\
&& 0 \leq x_3 \leq 2 \\
&& 0 \leq x_4 \leq 4.
\end{eqnarray*}
Define sets
\begin{eqnarray*}
S\;\, &=& \{\text{all solutions to (*) without upper bounds on the $x_i$}\} \\
S_1 &=& \{\text{all solutions in $S$ where $x_1 \geq 3$}\} \\
S_2 &=& \{\text{all solutions in $S$ where $x_3 \geq 3$}\} \\
S_3 &=& \{\text{all solutions in $S$ where $x_4 \geq 5$}\} \\
\end{eqnarray*}
By the same method used in (a) we calculate:
\begin{eqnarray*}
|S| &=& \binom{9+4-1}{9} = \binom{12}{9} \\
|S_1| = |S_2| &=& \binom{6+4-1}{6} = \binom{9}{6} \\
|S_3| &=& \binom{4+4-1}{4} = \binom{7}{4} \\
|S_1 \cap S_2| &=& \binom{3+4-1}{3} = \binom{6}{3} \\
|S_1 \cap S_3| = |S_2 \cap S_3| &=& \binom{1+4-1}{1} = \binom{4}{1} \\
|S_1 \cap S_2 \cap S_3| &=& 0.
\end{eqnarray*}
Then we require, where set complement is with respect to $S$,
\begin{eqnarray*}
\text{Ans.} &=& |S_1^c \cap S_2^c \cap S_3^c| \\
&=& |S| - |S_1 \cup S_2 \cup S_3| \qquad\qquad\text{by de Morgan's Law} \\
&=& |S| - (|S_1| + |S_2| + |S_3|) + (|S_1 \cap S_2| + |S_1 \cap S_3| + |S_2 \cap S_3|) - |S_1 \cap S_2 \cap S_3| \\
&&\qquad\qquad\qquad\qquad\qquad\qquad\qquad\text{by the Inclusion-Exclusion Principle} \\
&=& \binom{12}{9} - 2\binom{9}{6} - \binom{7}{4} + \binom{6}{3} + 2\binom{4}{1} - 0 \\
&=& 220 - 168 - 35 + 20 + 8 \\
&=& 45.
\end{eqnarray*}


Reasoning about decreasing functions

Question: Is it valid to say that for $n > \frac{9}{2}$,

$\dfrac{n+6}{2n-9}$ is a strictly decreasing function?

Since $2n$ increases faster than $n$ in all cases, is any additional argument needed to establish this?
I ask because I am trying to show that for $n \ge 31$,
$$\frac{n+6}{2n-9} < \frac{7}{10}$$
If $\dfrac{n+6}{2n-9}$ is strictly decreasing, then I only need to point out that $\dfrac{37}{53} < \dfrac{7}{10}$.
Answer: $$f(n)=\frac{n+6}{2n-9} = \frac{1}{2}+\frac{21}{2(2n-9)} $$
$g(n)=2n-9$ is a positive an increasing function for $n>\frac{9}{2}$, hence $f(n)$ is a positive and decreasing function on the same interval.
Comment: Thanks very much!  That really helps me to understand how to analyze the function!
Answer: $$\frac{n+6}{2n-9} = \frac{n-9/2 + 9/2 + 6}{2n-9} = \frac{1}{2} + \frac{21}{4n-18}.$$
Since $1/2$ is constant and $21/(4n-18)$ is strictly decreasing for $n > 9/2$ then so is your sequence.
Answer: If $f(x)=\dfrac{x+6}{2x-9}$ for $x >9/2$, then $f'(x)=\dfrac{-3}{(2x-9)^2}<0$, hence $f$ is strictly decreasing.

Reasoning about decreasing functions


Circular permutation on seating

Question: There are 21 people ,15 boys and 6 girls.how many ways are there to seat at least 2 boys between any two adjacent girls in a round table?.
I get my answer 708480.i m wrong ,i think.please help me.
Comment: Are you distinguishing the possible arrangements only by gender, or also by each individual (gender + name) ?
Comment: I distinguished only by gender.
Answer: Distinguishing only by gender, with the usual assumption of unnumbered seating since it is not explicitly specified otherwise, the problem simplifies to placing $15$ green marbles and $6$ red marbles on an unnumbered circle with the given stipulations.
The $6$ red marbles in a circle will have $6$ gaps or "compartments", in which we can initially place $2$ green marbles each, with the remaining $3$ green marbles placements just enumerated to be $10$:
$|\; 3\; |\; 0\; |\; 0\; |\; 0\; |\; 0\; |\; 0 \; |\; (3)\quad\quad|\; 2\; |\; 1\; |\; 0\; |\; 0\; |\; 0\; |\; 0 \; |\; (2)\quad\quad|\; 2\; |\; 0\; |\; 1\; |\; 0\; |\; 0\; |\; 0 \; |\; (2)$
$|\; 2\; |\; 0\; |\; 0\; |\; 1\; |\; 0\; |\; 0 \; |\; (2)\quad\quad|\; 2\; |\; 0\; |\; 0\; |\; 0\; |\; 1\; |\; 0 \; |\; (2)\quad\quad|\; 2\; |\; 0\; |\; 0\; |\; 0\; |\; 0\; |\; 1 \; |\; (2)$
$|\; 1\; |\; 1\; |\; 1\; |\; 0\; |\; 0\; |\; 0 \; |\; (1)\quad\quad|\; 1\; |\; 1\; |\; 0\; |\; 1\; |\; 0\; |\; 0 \; |\; (1)\quad\quad|\; 1\; |\; 1\; |\; 0\; |\; 0\; |\; 1\; |\; 0 \; |\; (1)$
and the last one,$\;|\; 1\; |\; 0\; |\; 1\; |\; 0\; |\; 1\; |\; 0 \; |\; (1)$

Circular permutation on seating


limit the number of entries and restart after break in the for loop

Question: I have a model and ready-made data in a table. In this model, I added a new field and made a connection with another table.
And in order not to manually fill in these fields for each record, I want to create a migration that will automatically fill in this field for all records.
Relationship table has two fields: post_id and author_id.
I am trying to do like this:
<code>$posts = Posts::find()->all();

foreach ($posts as $index => $post) {
    for($i = 0, $j = 0; $i < $index; $j++, $i++) {
        if ($j >= 4) {
          break;
        }
        $item = new PostAuthor();
        $item->setAttribute('post_id', $posts->id);
        $item->setAttribute('author_id', $j + 1);
        $item->save();
    }
}
</code>
Or:
<code>$posts = Posts::find()->all();

foreach ($posts as $index => $post) {
    for($i = 0; $i < $index && $i < 4; $i++) {
        $item = new PostAuthor();
        $item->setAttribute('post_id', $posts->id);
        $item->setAttribute('author_id', $i + 1);
        $item->save();
    }
}
</code>
But I get the same, only when j reaches 4, the cycle does not start again, and it adds everything else from 1 to 4:

Is it possible to make the loop start over for the post IDs I'm circling in the screenshot?
In idea my table should look like this
Comment: You didn't post enough information to make this solvable. You should post some data about the ideal final result. Also, in your screenshot, you are showing values but no column names.
Comment: "But I would like to redo all this" - what keeps you from doing this? PHP itself does not know about any "offset function", but it should not be too hard to write one
Comment: not a function but a method, I was wrong
Comment: You want to assign each of four authors to each post? If that is correct then there is a lot simple solution.
Comment: From the image provided, its unclear which is the id ? When j reaches 4 you want to restart the loop with offeset 4 ?
Comment: @benkov When j reaches 4, I need the cycle to start over, and for the next posts, the counter starts again. That is, for ID 71 there should be only one value and not 4, for ID 93 2 values, etc.
Comment: @katsarov When j reaches 4, I need the cycle to start over, and for the next posts, the counter starts again. That is, for ID 71 there should be only one value and not 4, for ID 93 2 values, etc.
Comment: Added a screenshot to the post of how my table should look like in the end
Answer: <code>$posts = Posts::find()->all();
$authors = [1,2,3,4]; //ids of the authors
$i = 1;
foreach($posts as $post){
  $postAuthors = array_slice($authors, 0, $i);
  $post->authors()->sync($postAuthors); //I assume your relation is belongsToMany(), otherwise you can foreach $postAuthors to create PostAuthor
  $i++;
  //you can use $i+=rand(1,4) instead to add more randomness
  if($i>4){
    $i=0; //settings to 0 will produce each 5 post to not have authors. If you set to 1 all posts will have author
  }
}
</code>
For each post we take N authors, sync relation then reset counter
Comment: nothing has changed, I end up with the same table, what's in the first screenshot
Comment: Can you explain what exactly you are trying to achieve? Because of the code I see that you want for each post you want to add each of authors
Comment: That's right, add an author_id to each post, but add it so that each post has a different author_id, someone has 1 and 2, someone just has 1, someone doesn't have it at all, as in the last screenshot


Given that the equations in $x$ :- $3[x - 2(x + \frac{a}{3})] = 2x$ and $\frac{3x + a}{3} - \frac{1 + 4x}{6} = 0$ has a common solution , find it .

Question:
Given that the equations in $x$ :- $3[x - 2(x + \frac{a}{3})] = 2x$ and $\frac{3x + a}{3} - \frac{1 + 4x}{6} = 0$ has a common solution , find it .

What I Tried :- We have :-
$\frac{3x + a}{3} - \frac{1 + 4x}{6} = 0$
=> $\frac{6x + 2a - 1 - 4x}{6} = 0$
=> $2x + 2a - 1 = 0$
=> $x = \frac{1 - 2a}{2}$ .
Substitute $x$ in the $1$st equation to get :-
$3[x - 2(x + \frac{a}{3})] = 1 - 2a$
=> $3[-x - \frac{2a}{3}] = 1 - 2a$
=> $-3x - 2a = 1 - 2a$
=> $x = -\frac{1}{3}.$
I got the value of $x$ , and I suppose I will find $a$ too , but how to find the common solution?
Can anyone help me?
Comment: This value of $x$ for the corresponding value of $a$ is your common solution. You can verify by substituting back in both the equations.
Comment: $x=-\frac 1 3$ is not correct. You forgot the parentheis in $(x-2)$.
Comment: Wait , what mistake did I do, there is no parenthesis there.
Answer: After getting $x=\frac   {1-2a}2$ from the second equation you get $3[(\frac   {1-2a}2-2)(\frac   {1-2a}2+\frac a 3)]=2\frac   {1-2a}2$ from the first equation. Solve this for $a$.
Comment: Whatever I get for $a$ , will that be the answer? can you say why?
Comment: That is what you get from the two equations. So the value of $a$ you get from the equation I wrote is the final answer. @SouradipDas
Comment: Oh ok thanks got it
Answer: You already computed $x=-\frac 13$ and $x=\frac{1-2a}2$. From these:$$-\frac13=\frac12-a$$


Finding the equation of a line which is normal to a circle and touches another circle

Question: We are given two circles $S_1$($x^2+y^2-2x-3=0$) and $S_2$($x^2+y^2-4y-6=0$). A line $ax+by=2$ which touches the former circle and is normal to the latter. We have to find the value of a and b.
I was able to find the value of b:-
the center of $S_2$ is (-g,-f)=(0,2)
Now since the line is normal to this circle, it passes through the circle :-
$$y-2=m(x-0)$$
$$y=mx+2$$
So the value of b is 1. I don't know how to find the value of m.
Answer: Get the intersection points equation for the intersected circle. If you use the condition of getting single intersection point (one solution for quadratic equation) you should get two potential relations for a and b. Use the other relation, for the case of the line going through the center of the other circle, with the two relations you got from the intersection - two sets of two equations or one quadratic equation - solving this will provide you with two pairs of (a,b) solutions.
Answer: Plug in $ y = m x +2 $ into equation of circle S1:
$$ x^2 + ( m x+2)^2   - 2 x -3 =0 $$
$$ ( m^2 +1) x^2 + 2 x ( 2 m-1) + 1= 0$$
For tangency to S1 the roots must be same, or discriminant should vanish.
$$ \Delta =0,  ( 2 m-1)^2- (m^2 +1) =0 $$
$$ m ( 3 m-4)= 0 $$
$$ m= (0, 4/3) $$
Thus there are 2 tangents that can be drawn whose slopes are $ (0,4/3) $ from center of S2.
Verify (0,2) as the intersection point of these 2 tangents.
Answer: Since the line is normal to $S_2$ it must pass through the center of $S_2$, which is $C_2(0\mid 2)$ . Since the same line has to be tangent to $S_1$ , the problem boils down to constructing the tangent to $S_1$  from $C_2$  . The center of $S_1$  is $C_1(1\mid 0)$ . Construct the circle $S_3$ whose diameter is $C_2C_1$ . Its equation is $x^2+y^2-x-2y=0$ . Its intersections $P_1(-.6\mid 1.2),P_2(1\mid 2)$ with $S_1$ are the points of tangency. Draw $C_2P_1$  and $C_2P_2$  et voilà!
Answer: $S_1$ has radius $2$ and is centered at $(1,0)$. Therefore, $(1,2)$ is its northern most point and it has the same $y$ value as $(0,2)$ which is the center of $S_2$. Therefore, the line $y=2$ is tangent to $S_1$ and goes through the center of $S_2$.


Math question complex number help?

Question: Write the following numbers as an $(\alpha + \beta i)$ which means as an algebraic expression :
$[2(\cos5 + i\sin5)]^{12}$  and also $(1+i)^8$
.
So,as for the first one, I tried writing $2^{12}(\cos5 + i\sin5)^{12}$ but could not take it further. As for the second one, I took the modulus of $z$, which is $1$ but I don't know how to find $\alpha$ or $\beta$.
Comment: No the first one is trigonometric expression...an algebric expression has the form : alfa +beta*i..
Comment: @Beyondhere: you are missing the point. Any number $\alpha+i\beta$ can be written using sines and cosines. The point of the question is to get rid of the power.
Comment: What's for you "an algebraic expression"? Because both expressions you wrote are "algebraic", so what did you actually meant? Perhaps Polar something?
Answer: Using de Moivre's formula, $(\cos 5^{\circ}+i\sin 5^{\circ})^{12}=\cos 60^{\circ}+i\sin60^{\circ}=\frac12+i\frac{\sqrt3}2$
So, $$\{2(\cos 5^{\circ}+i\sin 5^{\circ})\}^{12}$$
$$=2^{12}(\cos 5^{\circ}+i\sin 5^{\circ})^{12}=4096\left(\frac12+i\frac{\sqrt3}2\right)=2048+i2048\sqrt3$$
$1+i=r(\cos \theta+i\sin\theta)$
Equating the real & the imaginary parts,  $r\cos \theta=r\sin\theta=1$ where $r>0$
Squaring & adding we get, $r=\sqrt 2$
On division, $\tan \theta =1$ so $\theta=45^{\circ}$ as $\cos \theta,\sin\theta>0$
So, $1+i=\sqrt2(\cos45^{\circ}+i\sin45^{\circ})$
Hence, $(1+i)^8=(\sqrt2)^8\{\cos45^{\circ}+i\sin45^{\circ}\}^8=2^4(\cos360^{\circ}+i\sin360^{\circ})=16$
Alternatively,
$(1+i)^2=1+i^2+2i=2i,(1+i)^4=(2i)^2=-4,(1+i)^8=(-4)^2=16$
Comment: In the first one you have 2*(cos5..... but thank you anyway :)
Comment: I've just shown the power part
Comment: If incompleteness is the reason behind the down-voting,  I've just completed it.
Answer: Use the standard formula: $r(\cos\theta + i \sin\theta) = re^{i\theta}.$ From this, we can conclude that
$$[r(\cos\theta + i \sin\theta)]^n = [re^{i\theta}]^n = r^ne^{in\theta} = r^n(\cos(n\theta)+i\sin(n\theta)).$$
In the first case, $r=2$, $\theta =5$ and $n=12$. Putting this into the line above:
$$[2(\cos5+i\sin5)]^{12} = 2^{12}(\cos60+i\sin60).$$
Assuming that you are working in degrees, $\cos60 = 1/2$ while $\sin 60 = \sqrt{3}/2.$ Thus:
$$[2(\cos5+i\sin5)]^{12} = 4096\left(\frac{1}{2} + i \frac{\sqrt{3}}{2}\right) = 2048 + i \, 2048\sqrt{3} \, .$$
In the second case, note that $|1+i| = \sqrt{2}$ while $\arg(1+i) = 45^{\circ}.$ Thus:
$$1+i = \sqrt{2}(\cos45 + i \sin45) \, . $$
In this case, $r=\sqrt{2}$, $\theta = 45$ and $n = 8$, thus:
$$(1+i)^8 = 16(\cos360 + i \sin360) = 16 \, . $$

Math question complex number help?


c# how to use a template in a get property?

Question: I have some problem to use a template in a get property in c#. The following class has no problem:
public class test
{
    public T GetDefault<T>()
    {
        return default(T);
    }
}

But i would like to use get property and then there is a error

unexpected use of generic name

the code is following:
public class test
{
    public T Default<T> => default<T>;
}

Answer: There are no generic properties in C# so far. You can find details here and here:

We must reserve space for the backing store for the generic property
  [...]. But we don't know how much to reserve.
  Even if the compiler had read and understood every possible use of the
  generic.

MSDN states here:

Properties are a natural extension of fields. Both are named members
  with associated types.

They must have an associated type at compile-time.
Answer: I don't think current C# version support such syntax sugar. But you can get similar behavior like this:
public static class test<T>
{
    public static T Default => default(T);
}

And then use it:
var value = test<int>.Default;

Actually, if you strugling between two, I would reccomend to stay at methods:
public static class test
{
    public static T GetDefault<T>() => default(T);
}

Benefit is that you can put different extensions in same test class, on different types.


Creediting points to an iTunes account?

Question: A potential customer of mine wants to build an app for the iPhone, which will effectively "reward" the user with points to buy songs at the iTunes Store. Does anyone know if this is possible? If so, could you point out where I might look for how to do so?
Thanks...
Answer: I dont think this is possible to do through any api.  You could send gift cards... but you probably wont get into the store.  Apple does not allow any kind of app that rewards customers with real-world items.  I tried to submit a lottery app where buying the app would give you a ticket.  It was rejected because Apple has no way to guarantee that you would actually give out any prizes.  What if you dont?  The only thing you can offer is unlocking features in your app, or digital gifts like stuffed-animal pics and such.

Creediting points to an iTunes account?


Programa que retorna os números não comuns de duas listas (python)

Question: Estou tentando fazer um programa, em Python, que retorna uma lista com os elementos não comuns entre duas outras listas. Fiz o seguinte código:
def indice(a,b):
    ind = []
    for i in range (len(a)):
        for w in range (len(b)):
            if not (a[i] in b) and not (b[w] in a):
                ind = ind + [a[i]] + [b[w]]
    return ind

Porém, ele apresenta, eventualmente, repetições na lista retornada e, quando a primeira lista comparada tem mais elementos que a segunda, a função retorna uma lista vazia. Alguém pode me ajudar?
Comment: Por questões de legibilidade do código, recomenda-se utilizar `x not in y` ao invés de `not x in y`, mesmo que ambas as expressões sejam avaliadas da mesma maneira: `not y.__contains__(x)`.
Comment: em uma nota separada: algum bom motivo pra você estar estudando Python 2?  A última versão é de 2010, e ele  não terá mais atualizações - o melhor é prosseguir com Python 3.6
Answer: Aqui tens uma maneira equivalente à da resposta do @nano.galvao:
nao_comuns = list(set(a) ^ set(b))

Mas de uma forma didática e programando a funcionalidade podes fazer sem usar dois ciclos (comentei no código algumas explicações):
def nao_comuns(a,b):
    a_b = a+b # juntar as duas para percorrer todos os elementos
    nao_comuns = []
    for ele in a_b:
        if ele not in a or ele not in b: # nao existe numa delas
            nao_comuns.append(ele)
    return nao_comuns

a = range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = range(0,20,2) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
print nao_comuns(a,b) # [1, 3, 5, 7, 9, 10, 12, 14, 16, 18]

DEMONSTRAÇÃO
Com list compreension podes fazer esse ciclo numa linha:
def nao_comuns(a,b):
    a_b = a+b # juntar as duas para percorrer todos os elementos
    return [ele for ele in a_b if ele not in a or ele not in b]

a = range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = range(0,20,2) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
print nao_comuns(a,b) # [1, 3, 5, 7, 9, 10, 12, 14, 16, 18]

DEMONSTRAÇÃO
Usando um generator:
def nao_comuns(a,b):
    a_b = a+b # juntar as duas para percorrer todos os elementos
    for ele in a_b:
        if ele not in a or ele not in b: # nao existe numa delas
            yield ele

a = range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = range(0,20,2) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
print list(nao_comuns(a,b)) # [1, 3, 5, 7, 9, 10, 12, 14, 16, 18]

DEMONSTRAÇÃO
Answer: def elementos_nao_comuns(a,b):
    return list(set(a).symmetric_difference(set(b)))

Answer: Já agora uma solução um bocado primitiva usando conjuntos:
1) não comuns(a,b)= a∪b  -  a∩b
list((set(a) | set(b)) - (set(a) & set(b)))

2) não comuns(a,b)= a-b   ∪    b-a
list(set(a)-set(b) | set(b)-set(a))

Answer: Boa noite, seguindo sua lógica acredito que o mais correto seria:
def indice(a,b):
    ind = [];
    for ea in a:
        if (not (ea in b)):
            ind.append(ea);
    for eb in b:
        if (not (eb in a)):
            ind.append(eb);
    return ind;

Você percorre item a item de cada lista sempre olhando se o elemento não existe na outra ponta.


pure virtual class c++

Question: I've got a problem when trying to create a sub class from an abstract class
class people
{
public:
   people();
   ~people();
   virtual int comparable(people*);
   void order(people**,int);
};

my subclass
class worker : public people
{
private:
  int salary;
public:
  worker();
  ~worker();
  int comparable (people*);
};

I need to order a dynamic array of people by salary (from worker) but i can't match a people array[j]=worker a;
What so you suggest?
and then how do i call de function order? because a can't create a people object
Comment: Explain what array[j]=worker a; is supposed to mean or do. This isn't even valid syntax.
Comment: You want to sort `people` by `salary` but not `people` doesn't have a `salary`, so how do you plan on doing this? Do you want `salary` to be part of the `people` class? Do you want to have a dynamic list of `workers` instead?
Comment: You have the right idea. Implement `comparable` in `worker` where you can use salary.
Comment: There's no _pure virtual_ declarations in the classes you mention? Did you mean `virtual int comparable(people*) = 0;`?
Answer: Provide a pure virtual function to compare two people.
#include <algorithm>
#include <utility>
#include <stdexcept>

class people
{
   public:
      people();
      ~people();
      virtual int compare(const people* rhs) const = 0;
};

Implement the compare function in worker.
class worker : public people
{
   private:
      int salary;
   public:
      worker();
      ~worker();
      virtual int compare(const people* rhs) const
      {
         const worker* rhsw = dynamic_cast<const worker*>(rhs);
         if ( NULL == rhsw )
         {
            throw std::invalid_argument("rhs");
         }
         return (this->salary - rhsw->salary);
      }
};

Provide a functor that you can use in std::sort.
struct people_compare
{
   bool operator()(people* lhs, people* rhs) const
   {
      return (lhs->compare(rhs) < 0);
   }
};

Use std::sort and the above functor to sort the list of people.
void order(people** plist, int num)
{
   std::sort(plist, plist+num, people_compare());
}

Answer: Seems like a rather strange thing to do, and it would make more sense to have a salary variable in people if you are expected to sort some sort of collection of people by their salary.
It's also not clear to me what the return value from comparable is, but here's a solution that sorts based on salary, and assumes that a people object that isn't of worker type (or derived thereof) has zero salary. It returns 0 for equal salary, 1 for "this object has greater salary than the passed in object" and -1 for "less salary than passed in object".
Note however that this is a pretty bad design, you shouldn't, typically, use dyanamic_cast like this.
int worker::comparable(people *p)
{
   worker *w = dynamic_cast<worker*>(p);
   int wsalary = 0;
   if (w)
      wsalary = w->salary;
   if (salary == wsalary) return 0;
   if (salary > wsalary) return 1;
   return -1;
}

Answer:
I need to order a dynamic array of people by salary (from worker) but [...]. What do you suggest? and then how do I call the function order?

I'd consider refactoring your code. For a dynamic array I would use an std::vector and for ordering you can use std::sort.
If you want a decoupled system you should probably move the "container and sorting specific code" away from the person and worker class.
In fact it turns out that you don't even need a base class or public inheritance at all in this case. You can define a compare function for every class of your hierarchy. In particular for worker:
bool compare(const worker &a, const worker &b) {
    // return true if a is < b
    // example follows
    return a.salary < b.salary;
}

And finally, you are left with:
class worker {
    // ...
};

std::vector<worker> workers;

and when you need to sort the workers vector you can simply do:
std::sort(workers.begin(), workers.end(), compare);

If it makes sense to be able to do worker_a < worker_b (even though discrimination based on the salary is not exactly a popular opinion) you could implement an operator<:
struct worker {
    bool operator<(const worker& rhs) {
        // for example
        return salary < rhs.salary
    }
};

and just sort with:
std::sort(workers.begin(), workers.end());

pure virtual class c++


Lilypond custom lines to denote intervals

Question: I'm trying to display the harmonic series, and highlight the interval between each note and the octave below them. I'm imagining dimension lines as used in blue-prints. I could use some hints on how to do this.

My first try was to use Voice.TupletBracket.
{
  \clef bass
  \override Staff.TimeSignature.stencil = ##f
  \override Score.BarLine.stencil = ##f
  \time 16/4
  \tupletUp
  bes,,,4_"1"
  \tuplet 5/5 { bes,,_"2" f,_"3" }
  \tuplet 5/5 { \tuplet 3/3 { bes,_"4" d_"5" } f_"6" } geseh_"7"
  \tuplet 8/8 { \tuplet 7/7 { \tuplet 5/5 { \tuplet 3/3 { \tuplet 2/2 { bes_"8" c'_"9" } d'_"10" } eeh'_"11" f'_"12" } geh'_"13" gih'_"14" a'_"15" } bes'_"16" }
}

This is almost exactly what I want.  I have the straight brackets, and the numbers are great.  But the main issue is that I'd also like the octaves marked.  To do that, I'd need the bes notes to end the previous tuple before they start the next one.  I tried \tuplet 8/8 \=1{ bes \tuplet 8/8 \=2{ bes \=1} ..., but lilypond caught fire.  I'd also like the lines to be horizontal, but max-slope-factor isn't available in my version of lilypond (2.24).
But thinking of the \=1( notation my next thought was to use slurs which do support that notation.
  bes,,,4_"1"  ^\=8(
  bes,,_"2"    \=8) ^\=8( ^\=5(
  f,_"3"       \=5)
  bes,_"4"     \=8) ^\=8( ^\=5( ^\=3(
  d_"5"        \=3)
  f_"6"        \=5)
  bes_"8"      \=8)  ...

Now I have all of the spanners I need (including the octaves), but this clearly looks awful. I'm having trouble setting offsets for only one slur at a time. They all start at the same point so an \override is not going to target only one.  I also spent a ton of time offsetting that text above the slurs.  Even if I could set the control points for individual slurs that start at the same point, they would be smooth, while I like the jagged look of the other lines.
My next thought was TextSpanner but after an hour of looking up how to make them overlap, I realize that \stopTextSpan cannot point to a specific line, and so it is not possible to make them overlap.

My next thought is markup.  I think this is promising.  After struggling with define-markup-command for a while, I just brute-forced it and wrote part of it out manually.
  bes,,,4^\markup{\center-column{ "8" \rotate #270 \left-brace #25 } }
  bes,,^\markup{\center-column{ "5" \rotate #270 \left-brace #25 } }^\markup{\center-column{ "8" \rotate #270 \left-brace #50 } }
  f,
  bes,^\markup{\center-column{ "3" \rotate #270 \left-brace #25 } }^\markup{\center-column{ "5" \rotate #270 \left-brace #50 } }^\markup{\center-column{ "8" \rotate #270 \left-brace #100 }}
  ...

This might have potential but the horizontal space between the brace and the number really look bad, and the vertical scaling of the brace is a no-go.  I'm not sure if that white-space is from the \rotate #270 taking up a row, or if it is kerning of the bracket.
Answer: The trick to make the tuplets work is to create an empty note and extend the tuplet over it.  To ensure the bracket extends to the next note, tweak the TupletBracket.X-positions:
\tweak TupletBracket.X-positions #'(1 . 7)
\tuplet 8/8 {
  bes,,,4
  \once \override NoteHead.stencil = ##f
  \once \override Stem.stencil = ##f
  bes,,,
}

In lilypond >=2.25, you can ensure each bracket is horizontal with the TupletBracket.max-slope-factor
\override TupletBracket.max-slope-factor = #0

In lilypond <= 2.24, to achieve that you need to manually set the Y-coordinates of each bar:
\tweak TupletBracket.positions #'(4.5 . 4.5)
\tuplet 2/2 {
  bes_"8"
  c'_"9"
}

The final solution:

\version "2.24.1"
{
  \clef bass
  \override Staff.TimeSignature.stencil = ##f
  \override Score.BarLine.stencil = ##f
  \time 16/4
  \tupletUp

  \tweak TupletBracket.X-positions #'(1 . 7.)
  \tuplet 8/8 {
    bes,,,4_"1"
    \once \override NoteHead.stencil = ##f
    \once \override Stem.stencil = ##f
    bes,,,
  }
  \tweak TupletBracket.X-positions #'(1.2 . 10.8)
  \tuplet 8/8 {
    \tuplet 5/5 {
      bes,,_"2"
      f,_"3"
    }
    \once \override NoteHead.stencil = ##f
    \once \override Stem.stencil = ##f
    bes,
  }
  \tweak TupletBracket.X-positions #'(1.2 . 19)
  \tuplet 8/8 {
    \tuplet 5/5 {
      \tuplet 3/3 {
        bes,_"4"
      d_"5"
      }
      f_"6"
    }
    \once \override Voice.NoteHead.color = #(rgb-color 0.8 0.2 0.2)
    \once \override Voice.Stem.color = $(rgb-color 0.8 0.2 0.2)
    \once \override Voice.Accidental.color = $(rgb-color 0.8 0.2 0.2)
    geseh_"7"
  }

  \tweak TupletBracket.positions #'(10.5 . 10.5)
  \tuplet 8/8 {
    \tweak TupletBracket.positions #'(9 . 9)
    \tuplet 7/7 {
      \tweak TupletBracket.positions #'(7.5 . 7.5)
      \tuplet 5/5 {
        \tweak TupletBracket.positions #'(6 . 6)
        \tuplet 3/3 {
          \tweak TupletBracket.positions #'(4.5 . 4.5)
          \tuplet 2/2 {
            bes_"8"
            c'_"9"
          }
          d'_"10"
        }
        \once \override Voice.NoteHead.color = #(rgb-color 0.8 0.2 0.2)
        \once \override Voice.Stem.color = $(rgb-color 0.8 0.2 0.2)
        \once \override Voice.Accidental.color = $(rgb-color 0.8 0.2 0.2)
        eeh'_"11"
        f'_"12"
      }
      \override Voice.NoteHead.color = #(rgb-color 0.8 0.2 0.2)
      \override Voice.Stem.color = $(rgb-color 0.8 0.2 0.2)
      \override Voice.Accidental.color = $(rgb-color 0.8 0.2 0.2)
      geh'_"13"
      gih'_"14"
      \revert Voice.NoteHead.color
      \revert Voice.Stem.color
      \revert Voice.Accidental.color
      a'_"15"
    }
    bes'_"16"
  }
}
\layout {
  \context {
    \Score
    \override SpacingSpanner.common-shortest-duration = #(ly:make-moment 1/16)
  }
}

If you use the same \tweak TupletBracket.positions for all 8, 5, and 3s then you get this:
Answer: Why not manually offset your Slurs? Instead of doing \override (which changes the defaults for the context) change each single Slur individually doing
\tweak extra-offset #'(0 . 2) (

Generally the issue here are restritions at an engraver level. So the best idea would probably be to create a custom engraver for this.
Comment: Thanks, I'll look up custom engravers.


open throat = less air = less voice loss?

Question: I often experience voice loss after singing. I was told this can be caused by too much air through the vocal cords, which irritates them. Are they really related? And is there a relation between "amount of air" and "open throat" too?
I figured out the following equation:
open throat = less air = less voice loss
Is that equation correct? I was also told about "glottal compression" and I suspected this was related to "open throat" as well.
Is there any relation between these concept? If so, then it would be very very important to have an "open throat" to also fix a certain number of other issues with the voice.
Answer: "Open throat" is more concerned with setting up the resonances well in the mouth.  Optimally this will increase the resistance the vocal folds work against and thus reduce their movement for equal volume.  However, that does not really concern air use which is rather governed by the size of the vocal gap.
Both "open throat" and "good closure" (less air) are part of healthy phonation and should be aimed for but they are mostly orthogonal and it's actually an additional challenge to aim for both at once.
So your equation, while indeed concerning itself with "good" things, is mostly gibberish.
Answer: If you are experiencing any problem at all, be it soreness, voice loss, or whatever,  stop singing entirely until you can get evaluated by a professional voice teacher.  Not only are you risking long-term physical damage, but you are also at risk of getting into bad habits; those can be difficult to retrain.


ASP.NET Business Layer Code Persists but I'm not sure where it's stored?

Question: I'm royally confused about ASP.NET now. I believed that everytime you retrieved a webpage business model referred to by that page would be created and that after the display had been sent to the user it would all be torn back down again.
A colleague at work showed me this simple web app which seems to be storing business layer code between page fetches, without using session, cache, application, viewstate, querystrings, or post (as far as I can tell).
The code is as follows:
<code>    <form id="form1" runat="server" enableviewstate="False">
<div>
    <asp:Label ID="Label1" runat="server" Text="Label" EnableViewState="False"></asp:Label>
    <asp:Button ID="Button1"
        runat="server" Text="Button" EnableViewState="False"
        CausesValidation="False" />
</div>
</form>
</code>
Page Load:
<code>            PersistanceTest.BLL.Singleton s = PersistanceTest.BLL.Singleton.GetInstance;
        Label1.Text = "Counter: " + s.GetCounter;
</code>
And Singleton class:
<code>    public class Singleton
{

    private int counter;
    private Singleton()
    {
        counter = 0;
    }

    private static Singleton theSingleton;
    static public Singleton GetInstance
    {
        get
        {
            if(theSingleton == null)
            {
                theSingleton = new Singleton();
            }
        return theSingleton;
        }
    }

    public int GetCounter
    {
        get
        {
            int c = counter;
            counter++;
            return c;
        }
    }
}
</code>
Now when I load the page, the counter increments each time I press the button. But I have no idea where the Singleton instance is being persisted in the framework? I was sure it wouldn't exist between page loads. Can someone shed some light on this? It's driving me crazy.
Answer: I believe Singletons like that one are stored in the Application Domain (AppDomain). When your application restarts, all stored information will be reset as well.
You can read more about AppDomains here: http://odetocode.com/articles/305.aspx
Comment: Cheers, I did find the following sites which talk more about static member variables persisting through the lifetime of the AppDomain/Application: http://devblog.foliotek.com/2009/06/11/avoid-static-variables-in-asp-net/ http://www.navwin.com/Topics/AppDomainRecycling/AppDomainRecycling.aspx


Como gravar dados no firebase pelo Ionic sem apagar o que já está gravado?

Question: Meu metodo Create está assim
create(user: User, uuid: string): Promise<void> {
return this.db.object(`/users/${uuid}`)
  .set(user)
  .catch(this.handlePromiseError);
}

E a minha classe User está assim
export class User {

public $key: string;

constructor(
    public name: string,
    public username: string,
    public email: string,
    public photo: string
) {}

}

Só que quando eu vou gravar no firebase, o id fica indefinido e quando gravo outro dado ele se sobrepõe ao primeiro e apaga.
Comment: https://firebase.google.com/docs/firestore/manage-data/transactions?hl=pt-br Use as transações. Isso deve resolver o seu problema.
Answer: Experimente fazer um push():
create(user: User): Promise<void> {
return this.db.object(`/users`)
  .push(user)
  .catch(this.handlePromiseError);
}

Comment: O push está dando erro
Comment: Está dizendo que o push não existe no AngularFireObject


How do I clone the Windows 2008 Administrator account?

Question: On our Windows 2003 standalone servers we would normally create a new Administrator account (by making the account a member of the Administrators group) and disable the built-in one.
However when doing this on Windows 2008 we find that this new administrator account requires "Run As Administrator" or will perform UAC prompting to access certain folders that the built-in Administrator account doesn't do.
Is there a way around this (without tampering with the UAC settings in the local security policy)?
Answer: Why creating a new account?
You should renamed the builtin administrator account using a GPO instead. You can find details in KB 816109
Comment: Why rename using a GPO instead of using the rename in the computer manager MMC?
Comment: @Kev: Because GPOs allow you to apply a common settings to several servers at once.
And it is transparent. Each new server will automatically 'catch' the settings.
Answer: No. In 2008  even the administrator account does not run a process with admin priviledges normally, but will start an UAC promt once the process needs admin priviledges. This was done to increase security.
Comment: I just got one - ipconfig /flushdns requires elevated priviledges, not a normal command prompt ;)
Comment: Seems to UAC request an awful lot less than an account that's a member of the Administrators group. In fact I don't think I've been prompted so far on the Windows 2008 R2 boxes I've working on just now.
Comment: Not that way on 2008-R2, I'm logged on as "Administrator" on a clean box. When you start cmd.exe it automatically runs with elevated privileges (it even says "Administrator: C:\Windows\system32\CMD.exe" in the window title). The "Run as administrator" advanced property on the shortcut is unchecked.
Comment: This is because the local admin account has a couple of extra UAC rights granted to it which makes everything that happens in the local admin account run under the admin context.  Edit the local security policy and look at the security settings and find the UAC settings at the bottom.


Rugby Union referee yells something like, ~"Use-Its"~?

Question: Or something that sounds like that.
A side has retained control of the ball after a ruck, and the ball is just laying there on the ground and the player is hunched over with his hands on the ball waiting until people get in place.  The referee yells what sounds like "Use-Its".  I occasionally hear this, and I heard it three times in a row last match I watched.  What is he saying?
Edit:
Super Rugby: Hurricanes vs. Highlanders (5/212014 – Round 6 - Forsyth Barr Stadium, Dunedin NZ)
https://www.youtube.com/watch?v=dYlhEzsPcbU
Answer: The referee is shouting 'Use It'.  He is asking the team with possession of the ball to use the ball, and (in most cases) warning that if they do not, they will lose possession of it to the other team. Some referees even say 'Use it or lose it'.
Under the established laws of the game you most often hear this when the ball is in a maul that is no longer moving forward.  Law 17.6 calls this an unsuccessful end of a maul - if the ball stops moving forward for 5 seconds, a scrum is called and the defending team get the put in.  The referee is warning the attacking team that they are about to lose possession and they should do something with the ball - either continue moving the maul forwards, or pass the ball out of the maul.
Until recently you didn't often hear 'use it' in other situations.  In a ruck there is not this 5 second law. If the attacking team keep the ball from emerging (i.e. keep it under the feet of people in the ruck), they can keep the ball in that position for many seconds while they organize their next attack, or just to slow the game down.  The referee can deem too much time to have passed for the ball to emerge and call a scrum, but according to Law 16.7 the referee can allow a 'reasonable amount of time'.  Also in a ruck if there is no obvious 'team moving forward' then the attacking team keeps the put-in so the 'lost it' part is not the case there.  It probably does get called in deliberately slow rucks, but its usually advantageous to the attacking team to quickly recycle the ball and continue to attack, so having to warn the attacking team probably doesn't happen as often.
As pointed out by @Rawling, the Law Amendment Trials include proposed law changes that enforce specific behavior at the ruck - when the ball is available to a team to use, the referee will call 'Use It' after which they have 5 seconds to pick the ball up and use it.  These are currently being trialled, but I'm not sure which competitions are using them - I've only recently watched the Six Nations, and I don't recall seeing this. Looking at the clip provided of the match - Hurricanes v Highlanders - it certainly appears that this game was using amended laws.
However even under existing non-amended laws where this call is not a formal part of the game, it is still a very common convention used by referees to prevent unnecessary stoppages for scrums - to encourage exciting continuous play in the game.

Rugby Union referee yells something like, ~“Use-Its”~?


How to copy contentFiles of NuGet package references via MSBuild Copy task

Question: We have several repositories and each one has its own .editorconfig. Obviously, these are not synced, which is why I would like to distribute the .editorconfig from our framework solution (along with other files) via NuGet package to all our repositories/solutions and copy it via a simple Copy build Task to the solution directory.
I attempted to do the following:
Create a project "EditorConfigDistribution", which is supposed to contain the master .editorconfig file.
<Project Sdk="Microsoft.NET.Sdk">
  ...
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <NoDefaultExcludes>true</NoDefaultExcludes>
  </PropertyGroup>

   <ItemGroup>
    <Content Include=".editorconfig">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Pack>true</Pack>
      <PackageCopyToOutput>false</PackageCopyToOutput>
      <PackagePath>contentFiles\any\any\content</PackagePath>
    </Content>
  </ItemGroup>
</Project>

This all works as expected and I do get the desired .editorconfig file in my project from the other solutions and it is referenced as shortcut in a folder content/.editorconfig (see EditorConfigConsumer Project Structure).
The file is only a reference to C:\Users\<user>\.nuget\packages\editorconfigdistribution\1.0.0\contentFiles\any\any\content\.editorconfig.
Now, I want to copy that .editorconfig file via build task:
<Project Sdk="Microsoft.NET.Sdk">
  ...
  <ItemGroup>
    <PackageReference Include="EditorConfigDistribution" Version="1.0.0">
    </PackageReference>
  </ItemGroup>

  <Target Name="CopyEditorConfig" BeforeTargets="BeforeBuild">
    <ItemGroup>
      <EditorConfigFileToCopy Include="$(MSBuildProjectDirectory)\content\.editorconfig" />
    </ItemGroup>
    <Copy SourceFiles="@(EditorConfigFileToCopy)" DestinationFolder="$(MSBuildProjectDirectory)\.." SkipUnchangedFiles="true" UseHardlinksIfPossible="false" />
  </Target>
</Project>

However, I do get the following error:
Error MSB3030: Could not copy the file "C:\Users\weberma9\source\repos\<some_path>\EditorConfigConsumer\content\.editorconfig" because it was not found. (20, 5)

I can understand that the file (since it is a shortcut) cannot be found, but I just cannot figure out a way to reference that shortcut correctly in my build task.
What do I need to change in that line <EditorConfigFileToCopy Include="$(MSBuildProjectDirectory)\content\.editorconfig" />?
Of course, if you have better approaches to my general problem - I'm glad to hear about it.
Comment: https://stackoverflow.com/questions/49425012/dotnet-core-nuget-package-copying-content-files-on-restore/70713807#70713807
Answer: I was able to find a solution for my problem:
I not only provide the .editorconfig, but also the Copy-Build task via my EditorConfigDistribution project, which looks like this now:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <NoDefaultExcludes>true</NoDefaultExcludes>
  </PropertyGroup>

  <ItemGroup>
    <None Include="..\..\.editorconfig">
      <Link>Rules\.editorconfig</Link>
      <Pack>true</Pack>
      <PackageCopyToOutput>false</PackageCopyToOutput>
      <PackagePath>Rules\</PackagePath>
    </None>
  </ItemGroup>

  <ItemGroup>
    <None Include="build\**">
      <Pack>true</Pack>
      <PackageCopyToOutput>false</PackageCopyToOutput>
      <PackagePath>build\</PackagePath>
    </None>
  </ItemGroup>
</Project>

The .props file is straightforward and due to the convention that <package_id>.props and <package_id>.target are added to projects that consume the package (see Include MSBuild props and targets in a package), it will always be executed before 'BeforeBuild'.
EditorConfigDistribution.props (placed in build folder):
<Project>
  <Target Name="CopyEditorConfig" BeforeTargets="BeforeBuild">
    <ItemGroup>
      <EditorConfigFilesToCopy Include="$(MSBuildThisFileDirectory)..\Rules\.editorconfig" />
    </ItemGroup>
    <Copy SourceFiles="@(EditorConfigFilesToCopy)" DestinationFolder="$(SolutionDir).." SkipUnchangedFiles="true" UseHardlinksIfPossible="false" />
  </Target>
</Project>


PLACES_API_INVALID_APP error from Android Play Places

Question: I am trying Google Place Autocomplete Example from https://github.com/googlesamples/android-play-places.
I have put the correct API key at the correct place. I knew it because when I put a random string invalid API key I will get a different error.
So after I put the correct API key, I run the app in both real device and simulator. Both devices gave me this error:
Status{statusCode=PLACES_API_INVALID_APP, resolution=null}
What causes this error and how to fix it?
Comment: The documentation [here](https://developers.google.com/android/reference/com/google/android/gms/location/places/PlacesStatusCodes.html#INVALID_APP) should help answer your question.
Comment: Thank you Daniel. I am sure this is the same as INVALID_APP error mentioned in the doc.
Comment: This is for debug or release ? I had the same error with the release build variant and had to add an additional SHA1 fingerprint of my keystore
Answer: It's because the package that you put on the credentials section on the Developers Console is different to the project you are building.

Open https://console.developers.google.com
Go to APIs & auth menu on the left side, and go to Credentials
You can add new Android API and put the package you are building, or edit any existing and add another package name and fingerprint (SHA1).
Answer: I was getting the 'PLACES_API_INVALID_APP' even after posting my release SHA1. After trying everything I found out my release app was not even signed with the SHA1 I was getting from the keystore. So I did this:
1.Go to google play console
2.Release Management > App Signing > App signing certificate
3.Copy the SHA1 of App signing certificate and paste in google api console's credential page
Now you are good to go! Sadly it is not documented anywhere currently.
Answer: Follow my steps:
1> Creating one new projects on Google Developer Console
2> API Manager > Credentials > New Credentials > API Key > Android Key > Press Create Button & Generate API KEY
Here, Creating key without applying package of application & SHA fingerprint is working in any application
MUST REMEMBER:
Enable Google Places API for Android
Comment: API Key > Android Key > - There is no option for Android Key.
Answer: In my case SHA-1 certificate fingerprint was for debug build only, I added release SHA-1 key also. Now it's working.

Make sure you use the exact packageName and valid SHA-1
  key for debug as well as release app
Answer:
Status{statusCode=PLACES_API_INVALID_APP, resolution=null}

it means your api key invalid so create API key with your Package name and SHA Fingerprint
STEPS fot Creating API KEY
1.Get information about your app's certificate (SHA fingerprient).
2.Register a project in the Google Developers Console
3.Add the Google Places API as a service for the project, and create an API key.
4.Add the key to your app manifest.
Comment: Thanks for mentioning the SHA1 hash code of the keystore. As a reference for future readers, make sure to update the SHA1 value associated with your API Key (of `Google Places API for Android`) in Google Cloud console if you have changed your keystore (if you have started using `Google Play App Signing`).
Answer: I was seeing this error in the Google Play Console pre-launch report, despite having added the Google Play App Signing SHA-1 certificate.
Turns out there is an option in the pre-launch report's settings menu called pre-launch report version, which says:

Pre-launch report now explores your app even more deeply and may find
  more crashes. However, in order to do so, it will temporarily re-sign
  your APK within our lab environment.

I've enabled the option to opt-out of pre-launch reports where the app is re-signed, and the error has gone away.
Click on your application > Release management > Pre-launch report > Settings > Pre-launch report version.
This won't help you fix the error on a real device, but it fixed my issue.
Credit to this answer for pointing me towards this.
Answer: Although I have enable Android Place API from developer console but i came across this error:

Status{statusCode=PLACES_API_INVALID_APP, resolution=null}

Then I go to developer console and select my project registered earlier, and follow the option of "Get Place API key" for my project.
I resolved it this way.
Answer: Make sure that you have the API meta-data placed in Manifest.xml file
 <meta-data android:name="com.google.android.geo.API_KEY" android:value="You API Key Here"/>


Rails model to model relation in different context

Question: I have records with author and moderator. So I have two models Record and User:
class Record < ActiveRecord::Base
  attr_accessible :content, :author_id, :moderator_id
end

and
class User < ActiveRecord::Base
  attr_accessible :name, :uid

  validates :uid, :presence => true
  validates :name, :presence => true

  has_many :documents
end

Can anyone suggest a good solution for establishing a relation between these models, so that one record can have only one author and only one moderator?
Answer: This can be done by referencing the model User twice in the Record model.
Record creation table should contain two lines something like this :
  t.references :author
  t.references :moderator

Record model should look like
class Record < ActiveRecord::Base
  attr_accessible :content, :author_id, :moderator_id

  validates :author_id, moderator_id, :uniqueness => true  # To have unique author and moderator for each record

  belongs_to :author, class_name => 'User'
  belongs_to :moderator, class_name => 'User'
end


Multiple step definition found for specflow feature steps

Question: I have two feature files with some same scenarios. when i create definitions for them the first feature1.cs file has all the steps. when i click on the second feature file and generate definition it reuses some functions from the first feature1.cs file, as some scenarios are duplicate.
Now i have a [BeforeScenario] for both the file. But when i run the second feature file, it ends up using the [BeforeScenario] of the first file.
I noticed that the Binding tag in the feature1.cs file had the names of both of my feature file like
[Binding, Scope(Feature = "feature1"), Scope(Feature="feature2")]

So i removed second feature2 and placed it in my feature2.cs file.
Now, i am able to run the [BeforeFeature] from feature2.cs but when i click on scenario step and go to defination it says "Multiple Steps found" inspite of all the reusable steps being in the feature1.cs file itself.
I hope that makes sense.
Comment: Please post examples of the steps that it thinks are duplicates.
Answer: The first thing you need to realize is that all step definitions in specflow are global. To illustrate that, lets say I have 3 files: Feature1.feature, Feature2.feature and myStepDefs.cs.
In myStepDefs.cs I have the following code:
[Given(@"I have asked a new question")]
public void GivenIHaveAskedANewQuestion{
   //Some Code
}

Now in my feature1 file I have this Scenario
Scenario: I ask a question and get a bad answer
Given I have asked a new question
When I get an answer
And this answer is not helpful
Then I should Downvote this answer
And I should explain why it does not help answer my question

and In my feature2 file I have this Scenario
Scenario: I ask a question and get a good answer
Given I have asked a new question
When I get an answer
And this answer is helpful
Then I should upvote this answer
And I should mark this answer as accepted

In this case we reuse the given step, but we only need 1 step definition, not one for each feature.
Now you also explain that you have 2 [BeforeScenario] StepDefs. These run before EVERY Scenario, so if they do the same thing, again you only need one. If they do different things and you only want them to run before a given Feature/Scenario, then I would recommend you have a look at this, what you need to do is assign scope to these bindings so that it looks like this:
 [BeforeScenario, Scope(//your scope)]

this way the BeforeScenario steps only run for their given scope
Comment: Thanks for the reply. I guess i should had mentioned the fact that i am aware of the reusablity function of specflow. The issue that i was facing was that i was getting an error saying "Multiple steps found" when there were no multiple steps.
As i've mentioned in my comment, the Binding issues was also fixed when i changed the scope. But then again i was getting Multiple steps found issue.
Comment: Could you show us your file structure, the files you are having the issue with, and the code in each of those files that is having the issue before you made any changes. Thanks


Jquery: why $("#id_pop")[0] is illegal?

Question: In my code when I write code like:
$("#id_pop")[0]

there is an error. When I correct it to:
var $d = $("#id_pop");
$d[0]....

it's ok. Why?
Comment: use `$("#id_pop").first()` or `$("#id_pop").get(0)` I've run into `[0]` problems before. I don't remember what it was, though.
Answer: [0] should work, i.e. get you a DOM object. But you can't continue using jQuery methods once you get back a normal DOM object.
you can also get a DOM object from a jQuery selector like this:
$('#id_pop').get(0);
Also are you sure you only have one element with the id id_pop. If there is then $('#id_pop')[0] should work.
See working example here: http://jsbin.com/udace3
Comment: I see! so $d is still an jquery object but if I only get it from [0] it is a normal dom object, that is why the error is happening.
Comment: @BinChen when you inspected the return object of $('#id_pop') using any debugger avaible (im using visual studio) you can see that the returning object is indeed a jQuery object and have the element selected in and array, so if the selector used it will returns more objects this array will hold them. So basically $("")[0] is accessing the array where the first object will be the one with the id="#id_pop". So is a Dom Object what jQuery do with the .get(0) method is access that array and return also the jQuery Object for mantain chainability.
Answer: You are using an ID selector, you should not be getting an array but the jquery object itself.  In the jQuery documentation of using the #id,
Each id should only be used only once within a document.  If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on...
Answer: Isn't it better to use .eq() instead of .get()?
$('#id_pop').eq(0);

Or for that matter:
$('#id_pop:eq(0)');

Comment: both of these are still jQuery objects and not plain JS DOM objects
Comment: True, but he's using jQuery, so I suggested it.

Jquery: why $("#id_pop")[0] is illegal?


Slow query with left outer join and is null condition

Question: I've got a simple query (postgresql if that matters) that retrieves all items for some_user excluding the ones she has on her wishlist:
select i.*
from core_item i
left outer join core_item_in_basket b on (i.id=b.item_id and b.user_id=__some_user__)
where b.on_wishlist is null;

The above query runs in ~50000ms (yep, the number is correct).
If I remove the "b.on_wishlist is null" condition or make it "b.on_wishlist is not null", the query runs in some 50ms (quite a change).
The query has more joins and conditions but this is irrelevant as only this one slows it down.
Some info on the database size:

core_items has ~ 10.000 records
core_user has ~5.000 records
core_item_in_basket has ~2.000
records (of which some 50% has
on_wishlist = true, the rest is null)

I don't have any indexes (except for ids and foreign keys) on those two tables.
The question is: what should I do to make this run faster? I've got a few ideas myself to check out this evening, but I'd like you guys to help if possible, as well.
Thanks!
Comment: Maybe you could look at the execution plans to see what is the problem. In theory, the requests 'is null' or 'is not null' have to had the same execution plan if the balance is 50/50. The null stastistics for the table must be wrong !
Comment: @Scorpi0 not quite. Remember that this is an outer join. The null stats for core_item_in_basket are indeed 50/50, but the query tries to match each record from core_item with a record from core_item_in_basket, producing lots of additional nulls on the right side of the join.
Comment: Two kinds of row match you condition "where b.on_wishlist is null" 1. Rows in core_item without matching ones in core_item_in_basket;
2. Rows in core_item that do have matching ones in core_item_in_basket, but some of these matches match on_wishlist is null

Do you want both groups of rows?
Comment: @AlexKuznetsov yes, both
Answer: try using not exists:
select i.*
from   core_item i
where  not exists (select * from core_item_in_basket b where i.id=b.item_id and b.user_id=__some_user__)

Comment: But that is neglecting the "b.on_wishlist is null" condition which seems to be the slowing factor here.
Comment: ah then just add that to the where in the exists. also in your join try adding that is null into the join on condititon
Comment: No, this one doesn't help either. PostgreSQL learned to auto-optimize stuff like that in years.
Answer: Sorry for adding 2nd answer, but stackoverflow doesn't let me format comments properly, and since formatting is essential, I have to post answer.
Couple of options:

CREATE INDEX q ON core_item_in_basket (user_id, item_id) WHERE on_wishlist is null;
same index, but change order of columns in it.
SELECT i.* FROM core_item i WHERE i.id not in (select item_id FROM core_item_in_basket WHERE on_wishlist is null AND user_id = __some_user__); (this query can benefit from index from point #1, but will not benefit from index #2.
SELECT * from core_item where id in (select id from core_item EXCEPT select item_id FROM core_item_in_basket WHERE on_wishlist is null AND user_id = __some_user__);

Let us know the results :)
Comment: Answer number 4 is correct. It makes a lot of sense when you think about it. We don't want to have an outer join really (what for?), just exclude those few items that are on the wishlist.

Indexes are no good here as the problem was not the core_item_in_basket table (which is tiny) but the unnecessary join.

All checked in and working already in production, check out at http://filmaster.com

And thanks a lot depesz for saving my butt again :P
Comment: BTW, the new explain analyze is here if you are interested: http://explain.depesz.com/s/sIG
Comment: Thank you for providing option number 2!
Answer: You might want to explain more about the purpose of this query - as some techniques make and some don't make sense, depending on use case.
How often are you running it?
Is it run for only 1 user, or you run it for all users in some kind of loop?
Do: explain analyze  and put the output on explain.depesz.com so you will see why it is so slow.
Comment: @depesz Sure, I will in some 2h when I get back home as I hate writing queries on my mobile over ssh.
As a side note, I actually wanted to ask you directly about this one, but decided not to bother you with all the PSQL issues I have :)
Comment: So, answering your questions:
a) The purpose of the query is to get X next movies to be rated but excluding those that are on someone's wishlist.
b) It runs for one user every time the user wants to rate a random movie here http://filmaster.com/rate-movies/ - although we limit the results to 10, cache them and run the same query again after rating 10 next movies
c) The real query (the one I showed above is a simplified version) together with the explain analyze is here: http://explain.depesz.com/s/Cf
d) And here is same query without the wishlist condition: http://explain.depesz.com/s/BPd
Answer: Have you tried adding an index on on_wishlist?
It seems that this column needs to be checked for every row in the query. If your tables are that big, this might have quite a significant impact on the query speed.
As you put the on_wishlist condition in the where clause, which will cause it (depending on the what the query planer decides) to be evaluated after the join has been performed, that comparison has to be done for potentially every row resulting from the join. Both the core_items and core_item_in_basket tables are pretty big, and you don't have an index for that column, so there is very little for the query optimizer to do, which probably leads to the excessive query time.
The size of core_user should have no influence (as it is not referenced in the query).
Comment: No, indexes on wishlist make little sense as it can only be true or null


Finding an Unknown Location with known distances from location

Question: Lets say that I have a map and an unknown location. If I have multiple locations in which I know the distance away from the unknown location, can I pinpoint the unknown location?
I am aware of Triangulation, but am looking for something that can be used if the distances from the unknown location are not very precise (i.e only a few decimal digits). Would it be possible to increase the accuracy of the determined unknown location by knowing the distances from the unknown location of many locations?
Answer: This problem is relevant from data reconciliation or nonlinear least square fit.
In cartesian coordinates, let us call $(X,Y,Z)$ the coordinates of the point $P$ we look for and $(x_i,y_i,z_i)$ the coordinates of the known points $Q_i$ (there are $n$ of them). The square of the distance between point $P$ and point $Q_i$ is given by $$D_i^2=(X-x_i)^2+(Y-y_i)^2+(Z-z_i)^2$$ while the measured distance is, say, $d_i$.
So, in the sense of least squares, the most natural function to minimize is $$\Phi(X,Y,Z)=\sum_{i=1}^n(D_i-d_i)^2$$ since what have been measured are the $d_i$'s and not their squares.
The problem is for sure nonlinear but good estimates can be found using spheres of radius $d_i$ with centers at $(x_i,y_i,z_i)$; their intersections gives a good idea of the approximate location  of point $P$.
Personally, I am unable to do that (I am almost blind) and what I do is to take three points and consider the equation $$F_1=(X-x_1)^2+(Y-y_1)^2+(Z-z_1)^2-d_1^2=0$$ $$F_2=(X-x_2)^2+(Y-y_2)^2+(Z-z_2)^2-d_2^2=0$$ $$F_3=(X-x_3)^2+(Y-y_3)^2+(Z-z_3)^2-d_3^2=0$$ From here, develop $F_2-F_1$ and $F_3-F_1$; all terms $X^2,Y^2,Z^2$ disappear and then you have two linear equations in $Y,Z$ and you can express the solutions as linear functions of $X$. Plugging these into $F_1$ leads to a quadratic equation in $X$ so two roots $X_1,X_2$ for which you compute the corresponding $Y$ and $Z$ from the linear relations. So, you have your estimates $(X_1,Y_1,Z_1)$ and $(X_2,Y_2,Z_2)$ ; compute $\Phi(X_1,Y_1,Z_1)$ and  $\Phi(X_2,Y_2,Z_2)$ and select the point corresponding to the lowest value.
Newton-Raphson method applied to the system of equations $\Phi'_X=\Phi'_Y=\Phi'_Z=0$ should converge in quite few iterations.
If you use latitudes and longitudes, the problem would be the same except that the parameters will be the latitude and longitude of point $P$; this reduces the number of parameters but the calculation of distances $D_i$ is slightly more complex.
More data points you will have, more accurate will be the location and standard statistical tests will give a good idea of the accuracy of the searched coordinates.
Application for illustration purposes
I selected seven points with coordinates and very approximates distances (rounded for two digits) given below $(x_i,y_i,z_i,d_i)$ $$\left(
\begin{array}{cccc}
 1 & 2 & +1 & 3.4 \\
 2 & 5 & -2 & 4.8 \\
 3 & 1 & -3 & 6.1 \\
 5 & 2 & +3 & 2.5 \\
 5 & 4 & -2 & 4.6 \\
 4 & 6 & +4 & 2.7 \\
 7 & 3 & +2 & 3.6
\end{array}
\right) $$ and applied the procedure.
The results are
$$\begin{array}{clclclclc}
 \text{} & \text{Estimate} & \text{Standard Error} & \text{Confidence Interval} \\
 X & 3.51496 & 0.0224211 & \{3.45271,3.57722\} \\
 Y & 3.87820 & 0.0244705 & \{3.81026,3.94614\} \\
 Z & 2.37088 & 0.0190695 & \{2.31794, 2.42383\} \\
\end{array}  $$
while the point used for the data generation was $X=3.5$, $Y=3.9$, $Z=2.4$ which is pretty accurate for distances in significant errors.
Using the shortcut method for the estimates, using the three points with largest distances, I had $X=3.588$, $Y=3.825$, $Z=2.374$. Quite close isn't it ?
Edit
For the initialization of parameters $(X,Y,Z)$, writing equations $$F_k=(X-x_k)^2+(Y-y_k)^2+(Z-z_k)^2-d_k^2=0$$ subtract one equation from all others to get $$2 (x_j-x_k)X+2 (y_j-y_k) Y+2 (z_j-z_k) Z=(x_j^2+y_j^2+z_j^2-d_j^2)-(x_k^2+y_k^2+z_k^2-d_k^2)$$ ($j=1,2,\cdots,n-1)$, $(k=j+1,j+2,\cdots,n)$ which then leads to a simple multilinear regression (with no intercept) by a simple definition of new regressors and function values. The system is easily solved using matrix calculations (for $n$ points, this gives $\frac{n(n-1)}2$ equations).
This being applied to the problem leads to $$\begin{array}{clclclclc}
 \text{} & \text{Estimate} & \text{Standard Error} & \text{Confidence Interval} \\
 X & 3.52293 & 0.0118497 & \{3.49803,3.54782\} \\
 Y & 3.85637 & 0.0129881 & \{3.82908,3.88366\} \\
 Z & 2.37435 & 0.0089848 & \{2.35547, 2.39323\} \\
\end{array}$$
Please notice that we did not get the same answer  because the two objective functions are different.
Edit
Let us rerun the same problem with very wrong data for the distances (using $3,5,6,2,5,3,4$). The obtained results are then
$$\begin{array}{clclclclc}
 \text{} & \text{Estimate} & \text{Standard Error} & \text{Confidence Interval} \\
 X & 3.22801 & 0.108367 & \{2.92713,3.52888\} \\
 Y & 3.28107 & 0.136145 & \{2.90308,3.65907\} \\
 Z & 2.61077 & 0.097509 & \{2.34004,2.88150\} \\
\end{array}$$
which are not so bad. With more data points, even with large errors, the results would be better.
Answer: Absolutely. If you were able to determine the precise distance between the unknown point and a known point, you could picture that the unknown point is somewhere on a circle centered at the known point. With uncertainty, this circle becomes an annulus. By adding more known points, we intersect this annulus with other annuli to narrow it down to a small region. Each data point refines the region a little bit. After three measurements, you will be left with a shape roughly as big across as your error. Further measurements will give annuli which partially overlap this region, giving you even more accuracy. With enough accuracy, and assuming that your error is a random variable in some continuous distribution, you can achieve arbitrary accuracy.
I remember when I was a teenager, I had one of the first smartphones (it was big and slow, but it was hot stuff back then). I had a GPS app that could ping satellites to determine my location. It would tell me how many satellites I was connected to at any given time. I thought it interesting that it could tell my position with just three, but the accuracy kept going up with each additional satellite. This is the same sort of thing.
Answer: If you can quantify the imprecision it works similar to triangulation. If your known distances are say x km +- y km then you have a region they could be in.
For the first known point you have a ring with a given width. Once you add the second known point you have two regions they could be in. And so forth. Now adding more known points and their distances can help narrow the regions the point can be in assuming your imprecision isn't to large to make the extra information useless.


Passing some data back to RootViewController iOS 7

Question: Suppose , We have 3 ViewControllers called ViewControllerA , ViewControllerB , ViewControllerC  in our UINavigationController. To be specific , ViewControllerA is the RootViewController and ViewControllerB and ViewControllerC are pushed on it. So, Currently ViewControllerC is on the Top and visible to user.
I want to return to ViewControllerA by calling [self.navigationController popToRootViewControllerAnimated:YES]; method and pass some data to ViewControllerA from here. I have to update some UI according to the data passed from ViewControllerC.
If I had to return data from ViewControllerB , then I could implement custom protocol/delegate. But what can be a good approach in the situation described above ?
Thanks in advance for your help.
Comment: use singleton class to share information from lastView controller to first.
Comment: You will use NSNotificationCenter as well to send data to any running view controllers.
Comment: Use localNotification to share information in this case
Comment: use delegates to move data from one viewcontroller to another controller
Answer: You can try NSNotificationCenter as shown below.
Example:
In your ViewControllerA.m
-(void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataReceived:) name:@"passData" object:nil];
}

-(void)dataReceived:(NSNotification *)noti
{
    NSLog(@"dataReceived :%@", noti.object);
}

In your ViewControllerC.m
-(void)gotoHome
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"passData" object:[NSDictionary dictionaryWithObject:@"Sample Data" forKey:@"dataDic"]];

    [self.navigationController popToRootViewControllerAnimated:YES];
}

Answer: Here you can do with delegate methods
This is your root ViewController to call delegate methods
#import "ThirdViewController.h"
#import "SecondViewController.h"
 @interface ViewController ()<ThirdViewControllerDelegate>
  @end

@implementation ViewController
 #pragma mark -
 #pragma mark ThirdViewController Delegate Method

Implementation of delegate methods in your Root ViewController
-(void)didSelectValue:(NSString *)value{
    NSLog(@"%@",value);
}

Pass the last Vc delegate to the next ViewController
-(void)gotoSeconddVc{
    SecondViewController *vc2=[[SecondViewController alloc]init];
    vc2.lastDelegate=self;
    [self.navigationController pushViewController:vc2 animated:YES];
}

 #import "ThirdViewController.h"
     @interface SecondViewController : UIViewController
        @property(nonatomic,retain) id <ThirdViewControllerDelegate> lastDelegate;
        @end

-(void)gotoThirdVc{
    ThirdViewController *vc3=[[ThirdViewController alloc]init];
    vc3.delegate=self.lastDelegate;
    [self.navigationController pushViewController:vc3 animated:YES];
}

Implementation of last viewcontroller
@implementation ThirdViewController

-(void)btnDoneClicked{
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.delegate didSelectValue:strValue]; //call delegate methods here
}

Answer: The best approach is to separate shared information in a different class (I suggest, it will be some model class). Just store the same instance of model class in both view controllers and update them whenever model class changes. Use notifications, KVC or ask model state every viewDidAppear: method.


Show a polynomial is irreducible in $\Bbb C[x,y]$

Question: If I have a polynomial with more than one variable, for example $\Bbb C[x,y]$ (with $\Bbb C$ the complex numbers), how can Ii see whether it is irreducible or not?
For example, if I have $x^2-y^2-1$, what can I do to know whether it is irreducible or not? In this example I tried to used Eisenstein's theorem in $\Bbb C[x][z]$, but I don't know how to do it.
Thanks!
Comment: In this case, if you can factor it, you can factor it into first degree polynomials. It shouldn't be too difficult to either find such factors or prove that they cannot exist. But in general there aren't very many simple, powerful tools the way Eisenstein works with a single variable over $\Bbb Z$.
Comment: supposes it has a nontrivial factorization -- computing the resultant of your polynomial and the (degree 1) polynomial it purportedly factors with... is a good way to go
Comment: To apply Eisenstein you need to find a prime factor of $y^2+1$ in $\Bbb C[y]$ with multiplicity one. Where did you get stuck on that?
Answer: Yes, Eisenstein's criterion is a possibility: rewrite the polynomial as
$$X^2-(Y^2+1)\in \mathbf  C[Y][X]. $$
$Y+\imath$ is an irreducible factor of all coefficients, but the leading coefficient, and $(Y+ \imath)^2=Y^2-2\imath Y-1$ does no divide the constant term.
Comment: Please strive not to add more dupe answers to FAQs. You can quickly locate prior dupes via https://approach0.xyz/search/  besides site search, googling, etc.
Comment: @BillDubuque: I wasn't aware of this link. I'll add it to my bookmarks. Thanks!
Comment: I know that, but I had no way to check. Also, some questions *look* like a standard question, but I feel that the O.P. has specific difficulties with the concepts or techniques involved, and I think I can address these specific difficulties.
Comment: I just wanted to explain why her intuition about Eisenstein was quite correct.
Comment: @Bernard That's what *search* is for. Being here almost 6 years and answering over 8000 questions surely you must know that we have *many* prior instances of such questions. How could you not?
Comment: If need be, you can always add a comment after linking to an (abstract) dupe in order to ensure that the OP knows how to apply the dupe link. By adding yet more dupe answers with no novelty you make it more difficult to locate the" best" answers, and make it more difficult to iteratively refine prior answers (in the hope that they will eventually become "proofs from the book" after enough time being critiqued and improved).
Comment: Yes, but I didn't have myself any dupe to link to, and further, I see links to dupes  as useful more for  someone who doesn't  really know how to start.
Comment: DId you even try to search?
Comment: I didn't know your link.
Comment: You would if you had searched. Why do you refuse to search? If you did you would better see how the many hundreds of (rushed) dupe answers *greatly* complicates using the site to locate (the best) answers to questions.
Comment: Sure! Thank you so much