Find the values of p for the p-norm in a $L^p (R, dx)$ space.

Question: I was given the following conditions in an exercise:

Define an $L^p (R,dx)$ space, for $p \geq 1$ as a space of the class of equivalence of functions $f$ that satisfies the condition: $$\int {\vert f(x) \vert}^p dx < \infty  $$
For such functions, the p-norm is defined as follows: $$ {\vert \vert f \vert \vert}_p = {\left[ \int {\vert f(x) \vert}^{p} dx \right]}^{1/p}$$

Find the values of p for which ${\vert \vert \cdot \vert \vert}_p$ derives from an inner product, then give the explicit forms of those inner products.
Attempt at solution:
So my first thought was that if I manage to prove that the parallelogram law holds for a given norm, then that norm was induced by an inner product. After that, I could possibly find the explicit form of the inner product using the polarization identity, but the question still is how do I find the values of p? I clearly have no idea how to approach that.
Edit: Thinking about how to approach this, is it possible to use characteristic functions from some intervals, say, from $[0,1]$ and $[1,2]$ for instance? That way I could just pin-point the norms that are actually induced from inner products. Could it be easier that way?
Answer: A standard way of working with these things is to just test against characteristic functions. Take $A$ and $B$ disjoint sets so that the $L^p$ norms of the characteristic functions are $|A|^{1/p}$ and $|B|^{1/p}$ respectively.
Now write down the parallelogram law applied to $\chi_A$ and $\chi_B$. You get (spoilers!) that

 $$2 |A|^{2/p} + 2 |B|^{2/p} = 2 |A \cup B|^{2/p} = 2 (|A| + |B|)^{2/p}.$$

It should be pretty quick from here to deduce the (one and only) correct value of $p$.

 The value is $p = 2$, unsurprisingly, since this is induced by the inner product $\langle f, g \rangle = \int f \overline{g} \, d\mu$.


Unable to retrieve calendar data from freebusy query

Question: I'm trying to get the busy free times from my calendar.
Here is my code:
var freeRequest = gapi.client.calendar.freebusy.query({
   timeMin: (new Date(2016, 3, 1)).toISOString(),
   timeMax: (new Date(2016, 3, 30)).toISOString()
});

freeRequest.execute(function(resp) {
   console.log(resp);
});

It returns the same results as I get from here. In both cases, I do not get any calendars back. Here is the response I do get:
{
  "kind": "calendar#freeBusy",
  "timeMin": "2016-05-01T04:00:00.000Z",
  "timeMax": "2016-05-30T05:00:00.000Z"
}

Answer: Add items to your request like this:
var freeRequest = gapi.client.calendar.freebusy.query({
    items: [
      {id: "calendar id"}
    ],
    timeMin: (new Date(2016, 3, 1)).toISOString(),
    timeMax: (new Date(2016, 3, 30)).toISOString()
});

The calendar id can be found like this.


What are the variables does one search for when trying to render a custom form?

Question: In Drupal 8, the following code renders the node creation form (node/add/page) when integrating it into a custom module:
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create(['type' => 'page']);

$form = \Drupal::service('entity.form_builder')->getForm($node);

print \Drupal::service('renderer')->render($form);

We know the module in question is the Node module, which generates the content type page. What should I do to render the user creation form (/admin/people/create)?
I can easily change the code to the following, and replace 'node' with 'user' and 'page' with 'user'.
  ->getStorage('user')
  ->create(['type' => 'user']);

This would now render the user creation form. For me to come to the conclusion that it would render the user form was only a guess and apparently it works. But this problem solving approach will not work if I wanted to render some other form that might not be so obvious.
What does one have to grep for in the code base or other investigative work to come to the conclusion of the following 2 lines in the above code?
Comment: Happy to help - and also more than happy to be proven wrong by someone!
Comment: I stand by my [previous comment](http://drupal.stackexchange.com/questions/208743/why-doesnt-loading-a-form-in-the-view-header-work#comment254934_208743), it applies directly to this question too. By the time you know what to grep for, you'll already have more than enough context to tell you what class defines the form, making the grep redundant
Comment: Ok, taking your stance of **by the time you know what to grep for, you'll already have more than enough context**... Then before you even grep it, you still have to compile all the hints from something. That something is the thing I want to know. Even if it requires 20 other steps before it to conclude on what to grep for. Reason why is being able to debug a form, you'd first have to know where it came from. How does a developer know where it came from? Does one use devel? Or does one just look for something in the html source? I'm trying to take a step by step approach to understanding this.
Comment: I've already answered thst exact question from you 3 or more times now. Not doing it again, sorry, I don't have another way to phrase it :)
Comment: :( I just don't agree that there is absolutely no way for someone coming to D8 to not be able to debug a form by saying there are **absolutely** no universal steps into debugging this. It could even be as simple as grep for the label of the input box. That could be one universal method. No worries Clive!!! I'll figure it out.... but your hints have given me a lead at least. I just want to understand this system better before pushing it to clients. Thanks for everything thus far.
Comment: In OOP, reading document of interface is very important for understanding how further you work with them. If you know Java and other OOP, you will understand that. It is the reason why many Java programmers cannot work without a IDE....
Comment: My main workspace is Vim and bash commands (I do alot of grepping) and my workflow is usually I find something I want to change, I'd inspect element it, find some hints to grep for. Then start grepping everywhere until I narrow it down to the source file that might be in question. Then do some output debug test to make sure I'm in the right place and then work from there on modifications. But your saying D8's OOP setup I wouldn't be able to do this?
Comment: At the risk of being bashed (no pun intended)  by devs older than myself - unless you're a ninja with it, or have the natural lean towards becoming one, vim is rarely the tool to use any more. Our brains work much better with graphical UIs. Generally speaking, of course, thst won't apply to everyone, and it's just my experience and the devs I've known over the last 15 years. But using a graphical IDE like PHPStorm makes debugging and following the code trail 1000% easier. You should try it for a bit, at least so you can see the difference
Comment: The way you usually work, as you've outlined, is basically dependant on one thing: being able to reverse engineer the source of markup from the markup itself. _That's_ the difference here. You can still use grep to find things, assuming you actually know what to search for. That info isn't in the HTML any more, so you need somewhere else t get thst info from. And the only places are 1. Someone telling you, or 2. Looking at the code. Option 2 also requires some working knowledge of Drupal's architecture
Answer: To answer your explicit question (and to reiterate what Clive said), there's no one thing that you could grep to conclude the arguments to change for the getStorage() & create() methods.
The above solution assumes:

You're looking for an entity form.
You're aware that EntityFormBuilderInterface::getForm() needs an entity object.
You can build an entity object with Drupal::entityTypeManager().

It's a specific solution to building entity forms. If you're looking for a method to find any arbitrary constructed form, this solution isn't going to help here.
The most generic thing one could search for to find such a form (an invoke it for rendering), is probably a label that is unique to the custom form, but it really depends on how the form is constructed (e.g. EntityFormBuilderInterface::getForm(), FormBuilderInterface::getForm(), or some arbitrary form array builder function).
If you're familiar with the pattern of construction, there might be some specific terms to search for (e.g. searching for classes implementing FormBuilderInterface or EntityFormBuilderInterface), but there's not going to be one search pattern that works for all forms.


Using a common folder in multiple repos on Github

Question: I've been looking for an answer for a long time but I suppose it's time to ask someone who knows how to use Github :)
I'd like to have a common folder for multiple repos. What I mean with common folder is, whenever I make changes on a specific folder and sync, same folder should be updated in all repos.
Real world example may clarify the situation. I'm developing four different Wordpress themes and they share same folder, "framework". Either I need a master framework folder that pushes updates to all repos or a master repo that pushes updates to all repos.
Mine is simple logic but I believe this should be one of basic features of Github although I wasn't able to find out for a long time.
Answer: You can create a "common" repository, then add it as a submodule to your other repositories.  Then add a post-commit hook to update the submodule across your repos when you update the "common" repo.  AFAIK, this is the only way to "share" across repositories.
Great, in depth examples here: http://git-scm.com/book/en/v2/Git-Tools-Submodules
Edit:
Lots of info on hooks: http://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks
Comment: Great! Apparently it's going to be lots of readings on Submodule. I really appreciate for your help.
Comment: Finally I managed to separate framework folder as a repo and use it as submodule, works as expected. However, although cloning a repo allows to get submodules and makes easier to work with, downloading as zip excludes submodule content and it makes impossible to distribute project. Only way looks like using git-archive-all script but it requires to clone project first. What is the proper way to archive and export repo with submodules?


Standard errors for estimates of smoothing parameters

Question: My question is based on the "forecast"  package for R used in Forecasting with Exponential Smoothing. The State Space Approach - Hyndman et al. 2008. I am using the ets function to estimate the parameters of a model.
Is there a way to obtain standard errors for the estimates of the smoothing parameters?
Answer: Not all methods lead to analytic expressions (preferably based on proper asymptotic results) that provides this.
But the bootstrap allows you to approximate this via simulation. In essence, you generate (lots of) surrogate 'fake' data sets, employ your estimator on each of these and then use the population of your estimates to make inferences.  However, doing bootstrapping in a time series context has its own challenges...
Comment: +1 it is always nice to bootstrap something. On the other hand every challenge is easy with R: http://stat.ethz.ch/R-manual/R-devel/library/boot/html/tsboot.html
Comment: Thanks Dirk and mbq. I have one time series I collected. I am not using a data generating process to produce different series. So in this case I understand that I cannot get std deviations? Please correct me if I'm wrong. Thanks again!
Comment: You could try 'chunked' resampling. Google for block bootstrap.
Answer: The ets() function uses maximum likelihood estimation. So it would be possible to obtain standard errors based on the Hessian matrix in the usual way. However, in forecasting, the value of the model parameters is usually of very limited interest -- what we care about are the forecasts and their variances.
I can't think of a situation where you might want a confidence interval for a smoothing parameter, for example. What could you do with the information that the "true" value of alpha (whatever that means) lies between 0.2 and 0.4?
Consequently, I have not included the calculation of the standard errors of parameters in the package.
Comment: Point taken.

The problem appeared because the estimates of the smoothing parameters of the best fitting model (an ETS(M,A,N) ) are 0.0001 and 0.9999 which I think are the set limits for the possible values the estimates can take. So I was trying to find out what was going on.

I was looking for standard errors because I'm used to finding out about a model's parameters' distributions whenever I have to estimate one..:) thinking that if they vary too much they are not too reliable.
Comment: I did bootstrap as advised earlier. I found that the standard deviation was not that useful because the distribution was very skewed.
Comment: @noworries. Yes, they are the boundaries of the parameter region. A value close to zero is not a problem -- it indicates the associated state variable is extremely stable and essentially does not change over time. A value close to one usually indicates the model is trying to adapt quickly to each new observation which probably means the model is mis-specified.


Diferenças entre definições de eventos

Question: Exemplos
1.
<button onclick="clickTeste()">Teste</button>

function clickTeste() {
    alert("click");
}

2. (a que vejo ser mais utilizada)
$("#testeid").click(function() {
    alert("click");
});

3.
$(document).ready(function() {
    $(document).on("click","#testeid",function() {
        alert("click");
    });
});

Quais vantagens/desvantagens se tem em cada uma delas?
Há mais formas de definição além dessas?
Comment: Sua pergunta diz respeito somente ao que é feito via jQuery? E tem algum motivo especial para o exemplo 3 ter document.ready e o 2 não ter?
Comment: @bfavaretto Sim, seria específico para jQuery. Sobre o `document.ready`, pelo que andei lendo, tem relatos que usando o `.on` sem estar em `.ready`, houveram casos que não funcionaram. Por isso fiquei mais ainda na dúvida... Até então, acho que o 2o é o mais usado, pois elimina a necessidade de setar atributo no HTML, e o uso de `.ready`.
Comment: Marquei como duplicata porque tem um monte de pergunta sobre o assunto aqui. Seu exemplo 1 não tem jQuery, então os links não tratam dele (tem outras perguntas no site que tratam). Os 2 últimos links são sobre a questão do document.ready, que seria uma dúvida à parte.
Comment: @bfavaretto Obrigado, vou dar uma olhada!
Answer: Basicamente os 3 métodos irão realizar a mesma ação. Usar JavaScript ou JQuery realmente depende das necessidades do projeto a ser desenvolvido.
Utilizar Jquery torna o processo de desenvolvimento mais ágil para ser finalizado. Se você precisa desenvolver algo em javascript que não possa demorar tanto para ser lançado, com certeza o jquery pode ser explorado. De qualquer modo, você estará utilizando ótimas tecnologias para desenvolvimento de suas aplicações.
Answer: O chamando ele desta forma .click(function(){}) você esta usando um shortcut para a chamada .on('click',function(){}).
Já chamando ele sem passar uma função, ou seja, desta forma .click() você esta fazendo um shortcut para a chamada .trigger('click').
Esta é a forma de definir o evento através do HTML <button onclick="clickTeste()">
.on(type,listener) este método aceita alem do evento click,change e todos os outros evento do html, ele também aceita eventos customizados.
Exemplo: evento de abertura de modal do bootstrap, .on('show.bs.modal',function(){})
Existem ainda o

<HTMLElement>.onclick=function(){}
<HTMLElement>.addEventListener(type,listener[, options])

<HTMLElement>.onclick=function(){} nesse você esta adicionando um evento ao elemento de forma direta, usando dessa forma você só vai conseguir manter um evento no elemento e para remover o evento é só colocar o valor para null ou uma função vazia.
<HTMLElement>.addEventListener(type,listener[, options]) já esta forma é bem parecida com o jquery você pode colocar n eventos e para remover você tem que chamar o <HTMLElement>.removeEventListener(type, listener[, useCapture]). Eu acredito que o jQuery.on, jQuery.off faça uso desses eventos.

Posso esta errado mas não acho que haja uma vantagem/desvantagem entre .click(function(){}) e .on('click',function(){}) nesta forma, acho que é apenas uma questão de praticidade e padronização.
jquery.click, jquery.on( type [, selector ] [, data ], listener )
Comment: Mas Icaro, qual a vantagem e desvantagem de cada? Mera "organização" do código? Por que a maioria que vejo, usa `.click(function(){})` e não utilizando o atributo no HTML? Ou pq, utilizar o `ready`? Me traria uma segurança que todo o documento foi carregado antes de executar qualquer ação!?
Gostaria de mais detalhes por favor... Mas agradeço a resposta! ✌

Diferenças entre definições de eventos


Como mudar o formato da data em java script?

Question: Estou pegando a data informada pelo usuário, que seleciona de um datepicker. No formulário o formato fica exibido certo dd/mm/yyyy, mas o problema é quando pego a data pra jogar em uma variável, ela vem da seguinte forma:
Wed Mar 23 2016 00:00:00 GMT-0300 (BRT)

Como faço a conversão da variável em yyyy/mm/dd?
pois vou precisar dessa informação para que seja inserida em meu banco.
Answer: Crie uma função para isso:
function formatarData(data) {
    var d = new Date(data),
        mes = '' + (d.getMonth() + 1),
        dia = '' + d.getDate(),
        ano = d.getFullYear();

    if (mes.length < 2) mes = '0' + mes;
    if (dia.length < 2) dia = '0' + dia;

    return [ano, mes, dia].join('/');
}

alert(formatarData('Wed Mar 23 2016 00:00:00 GMT-0300 (BRT)'));

Resultado:

2016/03/23

Fiddle
Comment: Valeu Marllon, vou tentar.
Comment: Tem outras formas, ok? Se quiser eu edito a resposta e adiciono pra você... mas essa solução, na minha opinião, é a mais simples.


Unique periodic orbit for ODE consequence of Poincaré–Bendixson and Dulac's Criterion

Question: The Chicone exercise 1.201 asks prove that the system
$$\dot x=x+y-x^3=g(x,y)$$ $$\dot y=x-y-y^3=h(x,y)$$
has a unique globally attracting limit cycle on the punctured plane.
I prove that if exist a function $B(x,y)$ such that $(Bg)_x+(Bh)_y$ is not identically zero and of fixed sign on annular set then exist a unique periodic orbit.
This result should make things easier but I still can not see what is the function I need. If you have any idea or suggestion I would help
Answer: First you can use Poincare-Bendixon and Dulac's Criterion to obtain a limit cycle and then use the following argument the limit cycle is a global attractor. Let $u=x^2+y^2$. Then
\begin{eqnarray}
u'&=&2xx'+yy'\\
&=&2[x^2+2xy-y^2-(x^4+y^4)]\\
&\le&2[x^2+2xy+y^2-\frac{(x^2+y^2)^2}{2}]\\
&=&2u-u^2\\
&=&u(2-u).
\end{eqnarray}
For $u\in(0,2)$, we have
$$ \frac{u'}{u(2-u)}\le 1.$$
Integrating both sides from $0$ to $t$ for $u_0=u(0)\in(0,2)$, we have
$$ u\le\frac{2}{1+e^{-2t-c_0}}<2.$$
where $c_0=\ln\frac{u_0}{|2-u_0|}$. For $u>2$, do the same trick we have
$$ u\le\frac{2}{1-e^{-2t-c_0}}.$$
Thus in both cases, we have
$$ \limsup_{t\to\infty}u(t)\le 2$$
where means that the system has a global attractor in $x^2+y^2\le2$.
Comment: I dont understand the second equality, how you got an equation without derivative of x and y?
Comment: Do you know $a^2+b^2\ge(\frac{a+b}{2})^2$?
Comment: I was a little confused
Comment: The inequality should be $a^2+b^2\ge\frac{(a+b)^2}{2}$.

Unique periodic orbit for ODE consequence of Poincaré–Bendixson and Dulac’s Criterion


Hierarchical Clustering: What is the difference between linkages and distance measures?

Question: Clustering algorithm defines a particular distance (correlation or euclidean) and a linkage (which, strangely some books call distance - single, complete, average or centroid). Conceptually, correlation or euclidean distance measure distance between two points (but not clusters, perhaps); linkages measure distance between one cluster and other clusters (or points).
So, when the algorithm is applied, how does it matter what distance (correlation/euclidean) I choose, if the dissimilarity and subsequent grouping done only on the basis of linkages?
I know the distance choice matters because it gave me a different answer and dendograms for both measures.
Please help, thanks!
Comment: Distance measure is a formula how to define, compute adistance between two points. Linkage method in HCA is how to compute the distance (whichever selected) in case where one or both of the two points are actually not singleton points but clusters, group of points.
Comment: Note that many linkage methods (Ward, centroid, etc) require euclidean distance for geometric validity of the clustering.
Answer: The linkage defines how the distances are aggregated.
Without the underlying distance, there would be nothing to aggregate. Nothing to take the minimum/maximum/average of. The definitions of linkages require a distance.
Answer: The linkage criterion is a function of the distance metric that you choose.
For instance, let's consider the average-linkage criterion. Here's the formula:

Notice that the d in the above formula is the chosen distance metric.
If you had chosen Euclidean distance, then that could provide a different value for the linkage function as compared to say, the Mahalanobis distance.


Multiple axis voting system (star rating)

Question: I tried Multiple Axis Voting System using Drupal FiveStar and Computed Field, but I am not able to understand the below 2 points:

Add a node reference field to the voting node type, make the targeted node type selected.
Setup the voting(aka.review) node type, add all needed field and fivestar fields for multiple axis voting. Remember set the "target" option to #3 field.

May anyone help me understanding this?
Comment: Also just an FYI, this is possible with fivestar 6.x-2.x and 7.x-2.x without any extra modules.
Answer: The idea behind this technique, is to have a node that can be reviewed, and then create review nodes that contain the votes.
The first step you list, requires you to add a node reference field on the review node, where you can select nodes of the type that can be reviewed. That will enable uses to select what they are reviewing.
The second step is to setup fivestar for the review node. You need to add the axis that should be voted on, and which users will be able to set when creating the node.
Answer: I think you can try Rate.

This module provides flexible voting widgets for nodes and comments.
Administrators can add multiple widgets. By default, there are 6 widget types to choose from.
Comment: This works great for me. Thanks for the suggestion.


What is the geometric meaning of the variance of a multivarite normal distribution?

Question: While studying a multivariate normal distribution with $(\vec{\mu}, \Sigma)$, For a beginner, it feels a bit difficult to picture what the shape of the variance of a multivariate normal distribution will look like. Hope to hear some explanation.
Answer: For a normal distribution over $n$ variables, you have an $n \times n$ covariance matrix, often shown as $\Sigma$, rather than a single variance. The value of $\Sigma[i,j]$ indicates the covariance between the $i$th and $j$th variables. Since $Cov(X,X)=Var(X)$, the diagonal elements of covariance matrix shows the variance of each random variable.
Geometrically, It is difficult to imagine the probability distributions over more than two variables. For bivariate normal distributions (distributions over two random variables), if you draw the contours of the distribution, the elements of the covariance matrix determine the shape of the ellipses. For example, the ellipses are more elongated along variables with higher variances. Take a look at this figure for some intuitive examples.


SwiftUI: Admob Interstitial Ad is not being presented on rootViewController

Question: CODED IN SWIFTUI
I have implemented a settings page within my SwiftUI app that is presented upon clicking the button within the view. This view is wrapped within a sheet. You can see the code below:
TabsBar(showOptionsTab: $showOptionsTab)
    .sheet(isPresented: $showOptionsTab)
    {
        OptionsTab(showOptionsTab: self.$showOptionsTab)
    }

I have implemented an interstitial within this "OptionsTab" that is created when the options tab  is loaded within the .onAppear() call and presented when the back button is selected. You can the code from the OptionsTab below:
@State private var interstitial : GADInterstitial!

VStack
{
    ... other code

    Button(action:
    {
        if ( self.interstitial.isReady)
        {
            let root = UIApplication.shared.windows.first?.rootViewController
            self.interstitial.present(fromRootViewController: root!)
        }

        self.showOptionsTab.toggle()
    })
    {
        Image(systemName: "xmark")
            .font(.largeTitle)
    }
}
.onAppear
{
    self.interstitial = GADInterstitial(adUnitID: "addID")
    let req = GADRequest()
    self.interstitial.load(req)
}

I have additional code within the button that logs the status of the interstitial, and it shows it as being READY, and the present code is being hit... but it never presents itself.
I have implemented this exact code in the ContentView, and the interstitial loads perfectly fine. Something about this code being within the sheet is causing the interstitial not to present.
Is the rootViewController the incorrect view to load the interstitial on when in a view that is presented from a sheet? Otherwise, what else am I doing wrong?
Thanks for the help in advance!
Answer: Try this
TabsBar(showOptionsTab: $showOptionsTab)
    .sheet(isPresented: $showOptionsTab)
    {
        OptionsTab(showOptionsTab: self.$showOptionsTab)
            .OnDisapear
            {
                if ( self.interstitial.isReady)
                {
                    let root = UIApplication.shared.windows.first?.rootViewController
                    self.interstitial.present(fromRootViewController: root!)
                }
            }
        }
    }

And then add the state interstitial variable within this view, and onAppear of the ContextView, create the interstitial there.
Answer: Solution 2:
(not tested but should work):
present on the presentingViewController instead of the rootViewController
  if ( self.interstitial.isReady)
        {
            let root = UIApplication.shared.windows.first?.rootViewController?.presentingViewController
            self.interstitial.present(fromRootViewController: root!)
        }

check the reason, at the end of the answer
Solution 1:
it sounds like that there's something that prevents Interstitial ad to be presented when a sheet view is already presented
in my case i wanted to present the ad immediately after the sheet view is presented, which didn't work
what worked is, Presenting the ad, and after it being dismissed, the sheet view will be presented , and it worked!
for the  Interstitial i used this code
import SwiftUI
import GoogleMobileAds
import UIKit

final class Interstitial:NSObject, GADInterstitialDelegate{
  var interstitialID = "ca-app-pub-3940256099942544/4411468910"
  var interstitial:GADInterstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
  var sheet: (() -> Void)? = nil  //this closure will be executed after dismissing the ad

  override init() {
    super.init()
    LoadInterstitial()
  }

  func LoadInterstitial(){
    let req = GADRequest()
    self.interstitial.load(req)
    self.interstitial.delegate = self
  }

  func showAd(then sheet:(() -> Void)?){
    if self.interstitial.isReady{
      let root = UIApplication.shared.windows.first?.rootViewController
      self.interstitial.present(fromRootViewController: root!)
      self.sheet = sheet
    }
    else{
      print("Not Ready")
    }
  }

  func interstitialDidDismissScreen(_ ad: GADInterstitial) {
    self.interstitial = GADInterstitial(adUnitID: interstitialID)
    LoadInterstitial()
    if let presentSheet = sheet {
      presentSheet()
    }
  }
}

here we pass whatever we want to happen to the closure which will be called when interstitialDidDismissScreen is called
now instead of switching the state when button is pressed, it will be switched after the ad is dimissed
at the top of your contentView:
    struct HistoryView: View {
      private var fullScreenAd: Interstitial!
    init() {
fullScreenAd = Interstitial()
}
    }

then in your button:
   Button(action: {
            self.interstitial.showAd {
              self.showOptionsTab.toggle()

            }

        })

Note: i used the code of interstitial Ad from this gist
Also, AFAIK we can't tell if it's an bug in swiftUI, or it's something googleAdmob was supposed to take care of ?, there's no SwiftUI support From google so we can't blame them.

the problem AFAIK, that in iOS 13, grabbing the root ViewController will return the View Controller that presented the sheet, and when trying to present the ad, UIKit will complain that you are trying to present A view controller while a view controller is already present(the sheet),
 Solution ? simple, present the Ad, on the presented view Controller(The sheet)


install opencv2.0 on Ubuntu8.10 missing libunicap, libucil and libv4l1

Question: Basically, I am trying to build opencv 2.0 via CMake on Ubuntu 8.10. It keeps saying libunicap, libucil and libv4l1 are missing on my system. I searched for the packages for these libraries on places like Synaptic Package Manager but found none except that on http://packages.ubuntu.com there are some similar ones like libunicap2 libucil2 , which cannot be installed on my Ubuntu due to "installation error: Dependency is not satisfiable".
Here is the missing library info reported by CMake:
<code>$ cmake -D CMAKE\_BUILD\_TYPE=RELEASE -D CMAKE\_INSTALL\_PREFIX=/usr/local -D BUILD\_PYTHON\_SUPPORT=ON ..
-- Detected version of GNU GCC: 43
-- checking for module 'libunicap'
--   package 'libunicap' not found
-- checking for module 'libucil'
--   package 'libucil' not found
-- checking for module 'libv4l1'
--   package 'libv4l1' not found
-- IPP detected:
-- Parsing 'cvconfig.h.cmake'
running mkdir -p "/home/tim/program_files/tim/OpenCV-2.0.0/release/unix-install/"  2>&1
--
-- General configuration for opencv 2.0.0 =====================================
--
--     Compiler:
--     C++ flags (Release):     -Wall -pthread -ffunction-sections  -O3 -DNDEBUG  -fomit-frame-pointer -O3 -ffast-math -mmmx -DNDEBUG
--     C++ flags (Debug):       -Wall -pthread -ffunction-sections  -g  -O0 -DDEBUG -D_DEBUG
--     Linker flags (Release):
--     Linker flags (Debug):
--
--   GUI:
--     GTK+ 2.x:          1
--     GThread:           1
--
--   Image I/O:
--     JPEG:              TRUE
--     PNG:               TRUE
--     TIFF:              TRUE
--     JASPER:            TRUE
--
--   Video I/O:
--     DC1394 1.x:
--     DC1394 2.x:        1
--     FFMPEG:            1
--       codec:           1
--       format:          1
--       util:            1
--       swscale:         1
--       gentoo-style:
--     GStreamer:         1
--     UniCap:
--     V4L/V4L2:          1/1
--     Xine:              1
--
--   Interfaces:
--     Old Python:        0
--     Python:            ON
--     Use IPP:           NO
--     Build Documentation    0
--
--     Install path:          /usr/local
--
--     cvconfig.h is in:      /home/tim/program_files/tim/OpenCV-2.0.0/release
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generatim done
-- Build files have been written to: /home/tim/program_files/tim/OpenCV-2.0.0/release
</code>
I also tried to install the pre-required libraries specified for earlier version of OpenCV, which I found online, but found they are already installed:
<code>$ sudo apt-get install libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg62-dev libtiff4-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
libgtk2.0-dev is already the newest version.
libavcodec-dev is already the newest version.
libavformat-dev is already the newest version.
libjpeg62-dev is already the newest version.
libtiff4-dev is already the newest version.
The following packages were automatically installed and are no longer required:
  dnsmasq-base ttf-liberation
Use 'apt-get autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 5 not upgraded.
</code>
So I am puzzled. Anyone can give some advice please?
Thanks and regards!
Answer: unfortunately there are no unicap and ucil packages for ubuntu hardy. This does not mean that you can not compile and use openCV-2.0 in your applications but only that you will miss the functionalities offered by these specific libraries.
After running cmake you just have to compile and install OpenCV using:
<code>$ make
$ sudo make install
</code>
from the same directory where you executed cmake.
Then you can compile and link your applications with OpenCV following the infos in the last section of the INSTALL file.


Select2 Search Detect if user is typing

Question: I'm working with select2 4.0.3 and I can't seem to detect keyup events. What is the right way to go about this?
My code:
Thanks!
<code>$('.qty-select').select2({
        tags: true,
    }).change( function(e) {
        checkAmount(e);
    }).on('select2:open', function (e) {
        checkAmount(e);
    }).on('select2:closing', function(e) {
        checkAmount(e);
        //alert($(".select2-search__field").val());
    }).on('select2:select',function(e) {
        alert('sdfsf');
    });

    $('.select2-search__field').on('keyup', function(e) {
        console.log('User is typing');
    });
</code>
Answer: You're forgetting the document ready...
<code>$(document).ready(function() {
    // other code here

    $('.select2-search__field').on('keyup', function(e) {
        console.log('User is typing');
    });
});
</code>
Comment: Then it should work. There's nothing extraordinary going on in what you've posted so the issue must be somewhere else in your code. It's not here in what you've posted.
Comment: I found it in the library, they disable it from working.

Select2 Search Detect if user is typing


Data Pre Processing Regression Analysis

Question: I am preparing a regression analysis of sales data and advertisement data. The sales data is from Monday to Sunday, but Sundays have a value of 0 because the store is closed. The advertisement data from Monday to Sunday has values way greater than 0 on Sunday. It is for a Marketing Mix Modeling project.
How can I deal with that? Is that called noisy data or something else? Do I just remove the Sunday altogether?
Thank you in advance for any hints how to research that further.
Comment: Use a dummy variable with value 1 for sunday and 0 for everything else.
Comment: How is a dummy variable going to help in that case? I don't understand.
Comment: Ok. I found the answer myself. Basically it is a time series analysis and I just need to deseasonalize it.
Comment: No, a dummy variable will tell the model to treat sundays differently than the other days.
Answer: Use 6 dummies to deal with day-of-the-week and delete any of these indicators if they are not significant. Introduce Holiday indicators allowing for lead , contemporaneous and lag effects. Look at Simple method of forecasting number of guests given current and historical data for more model development strategies.

Data Pre Processing Regression Analysis


find partial fraction $(2x^2-1)/((x^2-1)(2 x^2+3))$

Question:
Find partial fraction of $\cfrac{(2x^2-1)}{(x^2-1)(2 x^2+3)}$?

My attempt:
I did google and I tried to solved it as :
Let's first get the general form of the partial fraction decomposition.
$\cfrac{(2x^2-1)}{(x^2-1)(2 x^2+3)}=\cfrac{A}{(x+1)}+\cfrac{B}{(x-1)}+\cfrac{C+Dx}{(2x^2+3)}$
Setting numerators gives,
$(2x^2-1)=A(x-1)(2x^2+3)+B(x+1)(2x^2+3)+C(x^2-1)$
I stuck here, how to proceed next?
Can you explain it, please?
Comment: Put $x=1$ to find $B$. $x= -1$ to find $A$ and proceed likewise.
Comment: @Mithlesh you are mistaken in the second step it should be simplified as  $2x^2-1=A(x-1)(2x^2+3)+B(x+1)(2x^2+3)+(C+Dx)(x^2-1)$
Comment: Thanks for pointing out! Bhaskara.
Comment: see my answer all four values can be determined using four linear equations
Answer: Well, you have there a polynomial equality, thus you can work taking into account the following:
(1) Coefficients of corresponding powers of $\;x\;$ in both sides are equal. For example, lets us compare the coefficients of $\;x^3\;$ in both sides:
$$0=2A+2B\implies A=-B$$
and you have a first linear equation for $\;A,B,C,...\;$
(2) The equality remains true if you susbtitute $\;x\;$ with any value. For example, let us subsitute in both sides $\;x=1\;$ :
$$1=A\cdot0+B(2)(5)+C\cdot0\implies 10B=1$$
and you've already obtained the value of one of your unknowns.
With the above two operations (perhaps first the second one, and then the first one...) you should be able to work out these problems in most cases.
Answer: Multiply out and compare coefficients. You'll find for example that the coefficient of $x^3$ on the right hand side is $2A+2B$.  As in the left hand side there are zero $x^3$ you conclude $2A+2B=0$.
Comment: see OP has mistaken in the second step it should be $2x^2-1=A(x-1)(2x^2+3)+B(x+1)(2x^2+3)+(C+Dx)(x^2-1)$
Answer: you are mistaken in the second step, the expression must be simplified as
$$2x^2-1=A(x-1)(2x^2+3)+B(x+1)(2x^2+3)+(C+Dx)(x^2-1)$$
now, compare powers of $x^3, x^2, x$ & constant terms, you will get
$$2A+2B+D=0\tag 1$$
 $$-2A+2B+C=2\tag 2$$
$$3A+3B-D=0\tag 3$$
$$-3A+3B-C=-1\tag 4$$
solve all four linear equations to get the values of A, B,C & D you will get
$$A=-\frac{1}{10}, B=\frac{1}{10}, C=\frac{8}{5}, D=0$$


Div em cima de imagem

Question: estou a tentar colocar uma div em cima da imagem, essa div vai ser um container branco com uma certa altura e largura, dentro dessa container, vai conter um titulo e um paragrafo.
Abaixo vos deixo a seccao onde quero fazer esse tal container, a div tem o nome de "info-container". Eu consegui colocar o texto em cima da imagem, mas o container branco que estou a tentar criar, não aparece de maneira nenhuma.
HTML:

SEE YOUR TOP ARTISTS

LOGIC

Twitter-API

LOGIC

Twitter-API

LOGIC

Twitter-API

LOGIC

Twitter-API

CSS:
.section-artists {
    padding: 0;
}

.artists-showcase {
    list-style: none;
    display: inline-block; /* Alinhamento centro */
    width: 110%;  /* Alinhamento centro */
    margin-left: -5%;  /* Alinhamento centro e full width */
    height: 100%;
    margin-top: 5%;

}

.artists-showcase li {
    display: block;
    transform: skewX(-10deg);
    float: left;
    width: 25%;
    height: 100%;
}

.artist-photo {
    width: 100%;
    height: 100%;
    margin:0;
    overflow: hidden;
    background-color: #000;

}

.artist-photo img {
    opacity: 0.7;
    width: 150%;
    height: auto;
    -webkit-transform: scale(1.18) skewX(10deg); /* reverte o skew para a imagem ficar reta */
    transform: skewX(10deg);
    -webkit-transition: opacity 0.5s, -webkit-transform 0.5s;
    transition: opacity 0.5s, -webkit-transform 0.5s, filter 0.5s;
    transition: transform 0.5s, opacity 0.5s, filter 0.5s;
    transition: transform 0.5s, opacity 0.5s, -webkit-transform 0.5s, filter 0.5s;
    transition: transform 0.5s, opacity 0.5s, -webkit-transform 0.5s, filter 0.5s;
}

//*.artist-photo img:hover {
//    opacity: 1;
//    -webkit-transform: scale(1.03) skewX(10deg);;
//    transform: scale(1.03) skewX(10deg);
//    filter: hue-rotate(250deg);
/*/

/* Container com texto e titulo */

.info-container {
    background: #fff;
    width: 500px;
    height: auto;
    top: 50%;
    padding: 0;
    margin-bottom: -20%;
    z-index: 1000;
}

.info-container>h4 {
    float: left;
    position: absolute;
    top: 50%;
    left: 10%;
    z-index: 1000;
}

.info-container>p {
    float: left;
    position: absolute;
    top: 55%;
    left: 10%;
    z-index: 1000;
}

Obrigado!
Comment: Tente colocar nela position absolute
Comment: O postion absolute vai permitir que o z-index trabalhe melhor
Comment: O  container branco continua não aparecendo atrás das letras mesmo com o position ablosute..
Comment: Ele não apareceu em momento algum, ou não está aparecendo atrás das letras como você quer? É que antes você disse que ele não estava aparecendo mesmo. Por que se ele estiver aparecendo, é melhor você definir um z-index para cada. Tipo, imagem, z-index 1, container z-index 2, texto z-index 3
Comment: Continua não aparecendo amigo...
Answer: Fiz esse arquivo simplificado aqui e ele pode te ajduar,
Html:

LOGIC

Twitter-API

CSS:
.artist-photo {
    width: 100%;
    height: 100%;
    margin:0;
   overflow: hidden;

}
 .info-container {
   position: absolute;
   background: #bf1e1e;
   width: 500px;
   height: auto;
   top: 50px;
   padding: 0;
   margin-bottom: -20%;
   z-index: 1;
 }

Desta forma deu certo aqui, você pode pegar esse exemplo e ir colocando seus outros CSS's nele e ver o que está dando conflito.
Comment: Hummm, aqui não funciona, não percebo..
Comment: Uai, aqui eu fiz um arquivo separado só com esses códigos que te enviei, pena que não dá para mandar print, pois aqui funcionou normalmente...
Comment: Pois, ai está o problema é o conflito que nao consigo solucionar, mas obrigado!
Comment: Aqui aparece a foto, depois o fundo, depois o texto. o Fundo está na lateral direita da imagem, um pouco acima e ocupa boa parte da imagem

Div em cima de imagem


Solving the Airy Equation using Laplace Transform

Question: I have been trying to read the book Airy Functions and Applications to Physics, Olivier Vallee & Manuel Soares, for research on the Airy Functions, but I am stuck on using the Laplace transform to solve the Airy equation to get the function in the correct form.
The book states (pg 5):

We consider the following homogeneous second order differential equation called the Airy's equation $$y''-xy=0.$$ This differential equation may be solved by the method of Laplace, i.e. in seeking a solution as an integral $$y=\int_C e^{xz}v(z)dz,$$ this is equivalent to solve the first order differential equation $$ v'+z^2v=0.$$ We thus obtain the solution to the Airy's equation, except a normalisation constant, $$y=\int_C e^{xz-z^3/3}dz.$$

Below is my working:
Using the suggestion to find a solution to the Airy Equation $y''-xy=0$ in the form $y=\int_Ce^{xz}v(z)dz$, the first step would be to differentiate the expression for $y$ to find $y'$ & $y''$:
$$\frac{dy}{dx}=\int ze^{xz}v(z)dz,$$
$$\frac{d^2y}{dx^2}=\int z^2e^{xz}v(z)dz.$$
Then,
$$\int z^2e^{xz}v(z)dz-x\int e^{xz}v(z)dz=0,$$ so
$$\int e^{xz}v(z)(z^2-x)dz=0.$$
Then I tried to use integration by parts with $u=(z^2-x)v(z)=z^2v(z)-xv(z)$, so $\frac{du}{dz}=2zv(z)+z^2v'(z)-xv'(z)=2zv(z)+v'(z)(z^2-x)$, and $\frac{dv}{dz}=e^{xz}$, so $v=\frac{1}{z}e^{xz}$.
Following through with this gives:
$$v(z)(z^2-x)\frac{1}{z}e^{xz}-\int(2zv(z)+v'(z)(z^2-x))\frac{1}{z}e^{xz}dz=0.$$
This (sort of) simplified to:
$$v(z)\frac{\left(z^2-x\right)e^{xz}}{z}-\int 2v(z)e^{xz}+v'(z)\frac{\left(z^2-x\right)e^{xz}}{z}dz=0.$$
At this point, I tried to differentiate this expression to reach the form $v'+z^2v=0$:
$$\frac{d}{dz}\left(zv(z)e^{xz}-\frac{xv(z)e^{xz}}{z}-\int 2v(z)e^{xz}dz-\int zv'(z)e^{xz}dz+\int\frac{xv'(z)e^{xz}}{z}dz\right)=0,$$
which gives
$$v(z)e^{xz}+zv'(z)e^{xz}+xzv(z)e^{xz}-\frac{xv(z)e^{xz}}{z^2}-\frac{xv'(x)e^{xz}}{z}-\frac{x^2v(z)e^{xz}}{z}-2v(z)e^{xz}-zv'(z)e^{xz}+\frac{xv'(z)e^{xz}}{z}=0.$$
The $e^{xz}$ terms all cancel through, leaving:
$$v(z)+zv'(z)+xzv(z)-\frac{xv(z)}{z^2}-\frac{xv'(z)}{z}-\frac{x^2v(z)}{z}-2v(z)-zv'(z)+\frac{xv'(z)}{z}=0.$$
From here, I removed the fractions:
$$z^2v(z)+z^3v'(z)+xz^3v(z)-xv(z)-xzv'(z)-x^2zv(z)-2z^2v(z)-z^3v'(z)+xzv'(z)=0,$$
and collected the $v(z)$ and $v'(z)$ terms:
$$v(z)\left(z^2+xz^3-x-x^2z-2z^2\right)+v'(z)\left(z^3-xz-z^3+xz\right)=0,$$
which leaves:
$$\left(xz^3-z^2-x^2z-x\right)v(z)=0.$$
This clearly does not match the form given from the book ($v'+z^2v=0$), but I cannot see where I have made the mistake.
Is my mistake something obvious I am missing, could it be due to the nature of the complex function (and if so, what), or is my error deeper? Any help would be much appreciated.
Answer: You are overthinking it. Starting from the beginning
$$ \int_C z^2 e^{xz} v(z) \ dz - \int_C xe^{xz} v(z)\ dz = 0  $$
Integration by parts gives
$$ \int_C xe^{xz} v(z)\ dz = e^{xz}v(z) \Big \vert_C - \int_C e^{xz} v'(z) dz $$
Here $C$ is a vertical line on the complex plane, such that all singularities of $v(z)$ lies on the left of it.  If we hand-wave away that the first term goes to $0$, we can simplify
$$ \int_C e^{xz}(z^2 v(z) + v'(z)) \ dz = 0 $$
Notice the LHS is a function of $x$ but the RHS is identically $0$, so it must follow that
$$ v'(z) + z^2 v(z) = 0 $$
Which can be solved by separation of variables
$$ v(z) = e^{-z^3/3} $$
up to a multiplicative constant.
This answer doesn't justify everything, but hopefully it can explain some things.

It should also be noted that this text uses a less accessible form of the inverse Laplace transform which uses complex analysis. A more common definition is the forward transform
$$ v(z) = \int_0^{\infty} e^{-zx} y(x)\ dx $$
Applying the forward transform to the original equation, and using integration by parts, we can show that
\begin{align}
\int_0^\infty e^{-zx} y''(x)\ dx &= -y'(0) + \int_0^\infty ze^{-zx} y'(x)\ dx \\
&= -y'(0) - zy(0) + \int_0^\infty z^2e^{-zx}y(x) dx \\ &= -zy(0) - y'(0) + z^2v(z) \\
\int_0^\infty e^{-zx} xy\ dx &= -\int_0^\infty \frac{d}{dz} e^{-zx} y(x)\ dx \\
&= -v'(z)
\end{align}
where the second result is justified by differentiation under the integral. Then
$$ v'(z) + z^2v(z) = zy(0) + y'(0) $$
Letting $y(0) = y'(0) = 0$ leads to the given result.

Edit: Your mistake is in the very first integration by parts:
$$\frac{dv}{dz}=e^{xz} \implies v=\frac{1}{\color{red}{x}}e^{xz}$$
Comment: I knew the main bulk of my error would be something trivial, which I couldn't see, so thank you for pointing that out! And, thank you for the second method with the forward transform - I think it's much easier to follow (and less likely for me to get wrong again).

The one part I am slightly confused about is how I would know the $C$ is a vertical line on the complex plane, as it wasn't stated in the book.
Comment: I'm not entirely sure why they would do this. Maybe physicists do things differently? In every differential equations class, they will generally teach you the forward transform, give a look-up table to go backwards, and not even mention the inverse transform at all.
Comment: Another follow up, how then could I use the forward transform and $v(z)=e^{-z^3/3}$ to find $y(x)$?
Comment: The Airy function is non-elementary, so you'll just have to leave it as an integral.


ColdFusion Access Manager Error when attempting to clear trusted cache

Question: <cfscript>

if (isDefined("url.clearTrustedCache")) {
    clearTrustedCache();
}

function clearTrustedCache() {

    adminObj = createObject("component","cfide.adminapi.administrator");
    adminObj.login("admin");

    runtimeObj = createObject("component","cfide.adminapi.runtime");
    runtimeObj.clearTrustedCache();
}

</cfscript>

I am trying to use the above code to clear the trusted cache via URL param. I am getting the following error message:
The current user is not authorized to invoke this method

The only thing I found online to try was http://helpx.adobe.com/coldfusion/kb/error-current-user-authorized-invoke.html but it didn't work (unless I am doing it incorrectly).
Any thoughts or ideas on how to fix this?
Comment: Re: `adminObj.login("admin");` Is "admin" (or whatever string is there) actually the correct CF Administrator password? Because you would get that error if you supplied the wrong password.
Comment: @Bry4n - you should add an answer and accept it so that it will be easier for others to see when they find this question.
Comment: FWIW, that code works fine for me. Do *any* admin operations work for you using that same login? Also, what does the stacktrace look like?
Comment: Of course it works for you sigh. No other property/operations via the "runtimeObj" works. I dumped the variables and I can see that the properties are present.
Comment: (Edit) Still sounds like a login error to me. You can create the objects without supplying a password. It is not validated until you try and perform a restricted operation.  I tested it on a Dev box with full permissions. Silly question, but are you *sure* you have access to the API? Also, any funky settings in your CF Admin or extra security restrictions on the server?
Comment: I'm fairly certain I have access. We use this script on similar sites that seem to work just fine. What kind of 'funky' settings should I be looking at specifically? Everything looks relatively normal to me.
Comment: Just in general, given that the error *appears* to be a login/permissions related problem. Any security restrictions on the server, like sandbox, etcetera? Also check the logs on the off chance they include more detail.
Comment: I think I figured it out. By default the login function requires a password. So I either have to provide the password or adjust the security settings in my CF admin to not check for a password
Comment: Huh? When I asked, you said you *were* supplying the correct Admin password ;-)  Anyway, if it is just a login error like I thought, that is easy to fix: just supply the correct password. I would **NOT** recommend disabling authentication as it leaves your server totally vulnerable.
Comment: I guess I was confused because other projects we work on here don't have the password field supplied in the function so I was trying to do it that way so the password remained consistent across environments. Anyways thanks for your help!
Answer: The solution was to use a password with the login because it was set up to be required in the Coldfusion Admin. If it's not required in the Coldfusion admin (which I don't recommend then a password may not be necessary.
Example:
adminObj.login("passwordHere","loginHere");
Comment: This works, just don't overlook the unexpected order of the arguments.


The wrong site title is coming up for home page

Question: For some reason, the title of our website in browser windows and tabs is coming up as something else. We aren't even sure where this title came from, as it has nothing to do with our site.
I checked the page source to see what was showing up in the <title> tags, and sure enough, it's the same, incorrect title.
I tried changing the name of the site and the site's slogan, hoping that would help. I've cleared the caches. It's been going on for about 8 months, before we made some upgrades to core and modules.

Other page titles seem to be working correctly. There are no nodes with this title. We are using Drupal Commons. Drupal version 7.50.
Comment: The wrong title has been on the homepage for eight months? Is it hardcoded in metatag global config?
Comment: The value of front page global metatag title is [site:name] but is still coming up wrong even after reverting everything. On local dev, everything is the same but the title is correct or the revert worked. Why not on production?
Comment: Are you running memcache? Did you flush all the caches?
Comment: I did `drush cc all`. I'm not sure how to clear the memcache but I feel like it's  causing my log in issue as well.
Comment: Log in issues? So many problems... if nothing in the code or database mentions Back to School, I can only guess it is cached in memory - any services running on prod that you aren't running locally?
Comment: Are you out of opcache memory?
Comment: How do I check?
Comment: You can see in the php status report via drupal admin - check opcache memory used vs free. If the free value is very very small you may need to increase and reboot the server. Just a wild guess.
Answer: Normally the <title> element is set in template_preprocess_html
  // Construct page title.
  if (drupal_get_title()) {
    $head_title = array(
      'title' => strip_tags(drupal_get_title()),
      'name' => check_plain(variable_get('site_name', 'Drupal')),
    );
  }
  else {
    $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
    if (variable_get('site_slogan', '')) {
      $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
    }
  }
  $variables['head_title_array'] = $head_title;
  $variables['head_title'] = implode(' | ', $head_title);

That is then output in your theme html.tpl.php
You may have some code or configuration overriding the default title there in a module or theme.
I'd suggest searching through the codebase for the title text, or perhaps in a db dump file.
After that, you can either update it, or add some code for your own HTML <title> logic.
Comment: No one could have guessed this, but there was some bad code inserted into a blog post (it was supposed to be the alt-title for an image I think) and even though it was posted almost a year ago, it was causing the issue. I didn't catch it until I migrated that content over to a new website and the same thing happened.

In summary, bad code can cause all kinds of issues. I've since changed all WYSIWYG editors to allow filtered HTML only for all roles except user/1.


Intalando o Visual Studio 2015 Community com SQL Server

Question: Instalei o Visual Studio Community 2015 e queria conectá-lo com o SQL Server, mas pelo que entendi eu não preciso instalar o SQL Server, só preciso baixar o SQL Server Data Tools. É isso mesmo?
Answer: O Visual Studio pode instalar o SQL Server para você. Também pode instalar de forma separada se quiser alguma outra edição que não vem junto com o Visual Studio, que inclusive só pode ser usado para desenvolvimento.
O SQL Server Data Tools é totalmente opcional.
Comment: Vlw, eu não tinha o SQL Server instalado no notebook, então tentei instalar o SQL Server Data Tools e ele inclusive já pergunta se deseja ou não instalar o SQL Server. Fiz um teste no meu Desktop que já tem o SQL Server e na hora da instalação do SQL Server Data Tools o instalador nem pergunta se quero ou não instalar o SQL Server (provavelmente por já identifica-lo na máquina).


Probability of $P(A \cap B)$ in general

Question: We are given events $A$ and $B$, $0 < P(A), P(B) < 1$. Can $P(A|B) > P(A)$ and $P(B|A) > P(B)$ happen?
So I came to this conclusion:
$P(A|B) = \frac{P(A \cap B)}{P(B)} > P(A)$,
$P(B|A) = \frac{P(A \cap B)}{P(A)} > P(B)$,
so we get: $P(A \cap B) > P(A) P(B)$. We know that if A and B are independent $P(A \cap B) = P(A) P(B)$, but I am wondering what holds in general. My gut is saying, that in general $P(A \cap B) \leq P(A) P(B)$ should be true, but I don't know how to prove it. Is my understanding of this correct?
Thank you.
Answer: This is a variation of other questions dealt with in related answers here and here.  To answer this question most clearly, suppose we define the posterior-to-prior probability ratio of two events as:
$$\Delta(A|B) \equiv \frac{\mathbb{P}(A|B)}{\mathbb{P}(A)}.$$
With some simple algebra you can get the following alternative expression for Bayes' theorem:
$$\Delta(A|B) = \frac{\mathbb{P}(A|B)}{\mathbb{P}(A)} = \frac{\mathbb{P}(A \cap B)}{\mathbb{P}(A) \mathbb{P}(B)} = \frac{\mathbb{P}(B|A)}{\mathbb{P}(B)} = \Delta(B|A).$$
Thus, it is a law of probability (essentially a re-expression of Bayes' theorem) that the posterior-to-prior probability ratio of two events is symmetric.  Your question effectively asks whether it is possible to get $\Delta(A|B) > 1$ and $\Delta(B|A) > 1$.  Not only is this outcome possible, but if one of those outcomes hold then the other must also hold, since $\Delta(A|B) = \Delta(B|A)$.  (The more interesting fact is that it is not possible to get $\Delta(A|B) > 1$ and $\Delta(B|A) \leqslant 1$.)
Answer: I don't have enough reputation to make comment so... along with the answer from @MarsPlastic, suppose $A=B$ and $P(A)<1$. Then $P(A|B) = 1 > P(A)$ and $P(B|A) = 1 > P(B)$. Yay!
Answer: Hint: If $P(A\cap B)\le P(A)P(B)$ were true in general, what would that imply for $A=B$?
Answer: You gut is misleading you

in general $P(A \cap B)$ can be greater than or less than or equal to $P(A)P(B)$
depending on which of those three cases you have, you correspondingly get $P(A \mid B)$ is greater than or less than or equal to $P(A)$ assuming $P(B) > 0$, and similarly comparing $P(B\mid A)$ with $P(B)$

Consider throwing two dice, one red and one blue.

If $A$ is the event the red die shows $6$ and $B$ is the event the sum of the two dice is $12$, then $P(A \cap B) =\frac1{36} \gt \frac1{216}=P(A)P(B)$
If $A$ is the event the red die shows $1$ and $B$ is the event the sum of the two dice is $12$, then $P(A \cap B) =0 \lt \frac1{216}=P(A)P(B)$
If $A$ is the event the red die shows $6$ and $B$ is the event the sum of the two dice is $7$, then $P(A \cap B) =\frac1{36} =P(A)P(B)$

Probability of $P(A \cap B)$ in general


Can passing tones have neighbor tones?

Question:
I am asking about the notes colored in red.
Also, the notes colored in green are a bit confusing, is there a special name for this type of figure since it comes back to the same tone before moving on to the next harmony.
Comment: There's a blank for the second part.
Answer: As I analyze it, the notes in red represent a decorated G. It's a mordent (or inverted mordent depending on which author one uses.) The notes in green look like one of the types of turns. (Note, Neighbor, other Neighbor, Note. or Note, Neighbor, Note, other Neighbor, Note.)
Comment: Mordents usually have a shorter decorating notes don't they? In my melody, each note is a 16th note and equal in length so can one say that this ia mordent?
Answer: It's possible to decorate a passing tone, but that's not what's happening here.
Red case
There are several possible interpretations:

The harmony is iio6, the first G is a passing tone, and the F# is an anticipation of the F# in the next measure. The second G is the upper neighbor to the F#. I find this interpretation most convincing. It can be tested by playing the passage as below.

First, demonstrate that the first G is a passing tone — to the next measure.

Then, demonstrate the F# as an anticipation.

The chord is actually iv, rather than iio6. This makes G the primary note — the chord tone — with the A as an accented passing tone and the F# as a lower neighbor.

The chord could actually be viio4-3. To my ear, this interpretation doesn't hold up as well as the others, but the Gs would function as in #1 above — first a passing tone, then a neighbor.

Green case
This is an arpeggiated i6 chord with an A passing tone between the initial G and Bb chord tones.
Comment: Hmmm interesting, so the F# is an anticipation even though it goes to G first? I thought anticipations were notes that arrive early and become consonant once the harmony changes but in this case It goes to another note before going back to F#
Comment: @armani Exactly. The F# does anticipate the F# in the next measure, but that anticipation is also decorated by the upper neighbor.
Comment: I had a fresh listen this morning and I actually played it in my DAW to really try and hear this interpretation of yours that the F# is an anticipation of the F# in the next bar but in all honesty, I hear G as the main note being decorated on its way down to the F# so to me, it really sounds like F# is decorating G.
Comment: @armani That's the interpretive part of music theory. One person will hear it the way you do, another will hear it the way I do.
Comment: ha ha ok... I tried my best to hear it your way, I really did :) Thanks for your help
Comment: @armani Actually, I just took a second look, and my answer is completely wrong. I'm going to rewrite.
Comment: Aaron, when I wrote this progression before decorating it, I had a ii°6 chord there with ^2 in the soprano. Why wouldnt that be a chord tone?
Comment: @armani I see. I'll have to take another look. But I'd say what you've actually done with the F# is turn iio6 into viio43.
Comment: dont you mean ii°6 into ii°? Since that is a 6 - 5 motion in figured bass.
Comment: @armani F#-A-C-Eb is viio7. With C in the bass it's 4-3 position.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/138083/discussion-between-aaron-and-armani).
Comment: Thank you for these Aaron, I like that you posted several interpretations

Can passing tones have neighbor tones?


Use personal SSL Certificate created on my own?

Question: I'm new to SSL Certificates. I've seen some tutorials about creating personal certificates but I didn't go far reading.
It seems that I can create a personal SSL Certificate and use it on my website, but the question is:
Will it do its job nicely?
Will the connection with my customers will be encrypted?
Is it possible to create a personal SSL Extended Validation certificate on my own, or do I need a certificate authority?
My point is I don't need insurance; I just want to add another layer of protection and safety for my customers. They wont actually buy on my wbesite, but from paypal, but a SSL certtificate would increase their trust to my website. I don't care if some company will take responsibility and appear on my certificate info.
Comment: There is a reason there is 3rd party certificates - it's not to ensure encryption. It's to ensure validation. If you are buying a car and you had a choice between one that the seller says is in good working order, or another one that gives you a mechanics report (along with contact info to the mechanic) validating the car was in good working order, which one would you buy?
Comment: try positivessl from namecheap 0.99$ each.
Comment: get one from godaddy or something, costs you $5.99/year
Comment: There are plenty of providers of free SSL certificates. Encryption is almost useless if you don't verify the identity of the party at the other end of the encrypted link. What good is a totally secure link to nobody in particular?
Answer: You are free to generate your own SSL certificate.  Just be aware that your users will get a big scary warning message saying the certificate can't be verified.  This will trouble many users.  Some may just leave, or call your support line, both of which can cost you money.
SSL certificates have two purposes:

To enable encryption
To verify that the person you think you are talking to actually is that person.

A self signed certificate only accomplishes the first purpose, unless you have a way for people verify the certificate, like giving them a copy of the public half in person so they can add it to their trusted certificates store.
The verifying part ensures that, for example, I didn't generate a certificate with your website's name, then hijack your customer's DNS or network connection, and direct them to my server.  In theory, Verisign/Godaddy/Whoever won't give me a certificate for your website.
For internal sites, or small ones where you can easily get your users to install a certificate, a self signed one works fine.  For a public facing site, it's pretty much unacceptable.  Even though it enables encryption, it doesn't prove you are who you say you are.  And it throws up a BIG SCARY error message.  That alone is reason enough to pay the few bucks for a valid trusted certificate.
As for extended validation certificates - there is no way to make your own.  The browsers have a very specific list of which root certificates are allowed to have extended validation, and that usually isn't user configurable.  Short of reprogramming, compiling and distributing your own copy of chrome or firefox, it's not going to be a free option.
Answer:
but a SSL certificate will increase they trust to the site. I don't
  care if some company will take responsibility and appear on my
  certificate info.

This is actually pretty common (unfortunately) within businesses that deploy SSL enabled sites internally to their employees (SSL VPN comes to mind) or externally (extranet).
With a self-signed certificate what you are saying is:
"If you trust me come on in!"
...and most browsers will warn the user to verify the trust.  Some will simply choose to permanently trust the site and the certificate (again common in internal company apps/sites).
With a third-party trusted certificate what you are saying essentially is:
"If you trust insert 3rd party cert provider come on in!"
By default, browsers/OS' have a list (updated from time to time) of trusted providers of certificates.  This list allows the browser (and therefore the user) to trust that a certificate is what it is says it is, and is issued to/for what it says it is.  You can think of it similar to a notary public.  The 3rd party is there simply to say "Yep, I issued them a certificate based on the validity of the info at the time".
So, whether you choose to deploy a self-signed cert or not is really up to you and your case/need.  You'll need to decide whether your customers/users will care or need that "assurance" that a valid 3rd party cert can provide.
Answer: If you want a free SSL certificate, the best place I have found is StartSSL. It is not as user friendly as other places, but it is free for basic SSL certs and low priced one time fee for others, it is worth it. As for extended validation, all of the companies that offer them require proof of legal and physical presence of a business.


Pegar o caminho antes de salvar a imagem CI

Question: Estou usando o seguinte método para salvar uma imagem, está funcionando corretamente:
function do_upload()
{
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload())
    {
        $error = array('error' => $this->upload->display_errors());

        $this->load->view('upload_form', $error);
    }
    else
    {
        $data = array('upload_data' => $this->upload->data());

        $this->load->view('upload_success', $data);
    }
}

Porém eu gostaria de antes de salvar a imagem, passar a rota dela para uma variável, mas está dando erro que devo converte lá, sou novato em CI se pudem me ajudar.
Tentei fazer:
$teste = $this->upload->data();
echo $teste;

Se eu faco um foreach vai mostrar todos os caminhos o que eu precisaria é mostrar apenas aquele especifico.
Comment: A "rota" seria o URL para a imagem gravada?
Answer: $this->upload->data() é um ARRAY associativo. Para atribuir o valor do "caminho" do arquivo a uma variável precisamos especificar qual dos elementos do ARRAY queremos usar, o que, no seu caso, deve ser 'file_path':
$teste = $this->upload->data();
$file_path = $teste['file_path'];
echo $file_path;

Se vc quer uma URL para o arquivo vai ter que criá-la, porque até onde li na documentação, $this->upload->data() não retorna isso.
Isso aqui deve funcionar:
$teste = $this->upload->data();
$file_url = base_url("diretorio_upload/{$teste['file_name']}");
echo $file_url;

Answer: Você vai usar:
$teste = $this->upload->data('file_path'); // Retorna o caminho absoluto do upload, atribuído no $config['file_path'].
$teste = $this->upload->data('full_path'); //Retorna o caminho absoluto do arquivo com o nome do arquivo + extensão.


Count number of operations in algorithm

Question: I have to count exact number of operations that algorithm performs:
count = 0
for( i=0 ; i<=10 ; i++ )
    for( i=0 ; i<=10 ; i++ )
            count += (i + 10) / 2

I understand that its complexity is O(1). Exact number of CPU operations equals to:
10 * 10 (outer and inner cycle)  + 100 (s += i + 10) + 100 (sum/2) + 1 (declaration of count variable)? Or I am wrong?
How can I count them?
Comment: The complexity is O(1). There's no `n` in sight, or any variable for that matter.
Comment: Hard to say without knowing exactly what an "operation" is. Perhaps on systems where registers are zeroed out at the beginning of programs by default, `count = 0` is actually a no-op and doesn't count towards total operations. If this is a homework assignment, ask your teacher for clarification. If it's not a homework assignment, don't worry about it too much -- just knowing the complexity should be a useful enough measurement on its own.
Comment: Why would you want to count the exact number of CPU operations? The complexity of an algorithm is not computed using exact numbers, moreover, there will be more actual CPU operations and the count depends on the compiler used.
Comment: That's why the complexity theory is based on abstract computers, such as Turing's machines, where there is a clear definition of an operation.
Comment: Also, this might be a trick question - notice how the inner loop and outer loop use the same variable. Depending on your language, this may mean that the `count += ` line only executes ten times.
Comment: @Kevin it is, see the answers and comments below..
Comment: Since it is only counting of operations, regardless of the input data, it is not related to the complexity theory at all..
Answer: To count every operation we  count:
count = 0                         // 1
for( i=0 ; i<=10 ; i++ )          // 1 => (i = 0) + 1 => (i <= 10)
    for( i=0 ; i<=10 ; i++ )      // 1 => (i = 0) + 11 => (i <= 11) + 11 => (i++)
        count += (i + 10) / 2     // 11* (1 => (i+10) + 1 => (/2) + 1 => (+=))

Total count of operations = 1 + 1 + 1 + 1 + 11 + 11 + 11*(1 + 1 + 1) = 59
Edit: note that since you're using i in both loops, you will not run the outer loop.
Comment: You're ignoring the fact that the last line will be performed 11 times.
Answer: Um... Did you deliberately use i for both loops?  (making the outer loop pointless)?
Assuming you meant to use different variables:

in the first for() loop, we have one assignment, 11 comparisons and 11 increments (and yes, 0 to 10 is 11)  For a total of 23 "operations".
In the second for() loop, we have the same 23 operation, performed 11 times each, for 253 operations.
in the body, we have two addition, a divison and an assignment, for 4 operation repeated 121 times, for a total of 484.
23 + 253 + 484 = 760 "operations".

UPDATE:
 Now, working with the idea the using the same variable was intentional:

in the first for() loop, we have one assignment, one comparison and one increment, for a total of 3 "operations".
In the second for() loop, we have the same 23 operation (see above), performed once.
in the body, we have two addition, a divison and an assignment, for 4 operation repeated 11 times, for a total of 44.
3 + 23 + 44 = 70

Note, however, all operations are not equal.  A divison will take much longer than an increment.
Comment: This is however only one of possible definitions of an operation. A CPU operations are also jumps from the end of one iteration cycle to the beginning of another, reading of the instructions, allocation of space for storing variables, reading/writing variable values, etc..
Comment: No, I meant to use only one variable - i (yes, i know that inner loop is quite pointless).
Comment: Why the number of operations in inner loop is 44 but to 44 * 11 (number of iterations in outer loop)?
Answer: If you meant to have a different variable for the inner loop, then you are right, the complexity is O(n^2).
What I was thought was to always start with the inner-most loop. How many times would it iterate? In this case, it would perform 10 iterations.
Then focus on the outer loop: how many times does that one iterate? It also performs 10 iterations, and in each iteration the inner loop has 10 iterations.

Count number of operations in algorithm


Are there parallel octaves in L. Couperin's prelude, Suite in A minor?

Question: Are there doublings or parallel octaves, especially with regard to the first several measures, in Louis Couperin's prelude "à l'imitation de Mr. Froberger", from the Suite in A minor?
I would also very much like to know which piece of Froberger Couperin is referring to,  if any. I understand the former only published a couple things in his lifetime, which exceeded that of Couperin.
Answer: There is a difference between

Parallel octaves between two independent melodic lines
Octave doubling of a line as a method of strengthening the orchestration

The first of these is the "bad" version of parallel octaves that we seek to avoid in contrapuntal writing, largely because two independent voices briefly merge into one and lose their independence. The latter type happens, quite frankly, all the time.
Here is a recording of the piece, and a score can be found on page 21 (25 of the PDF) here. I don't see or here any problematic parallel octaves here, but you're welcome to point to a more specific part of the score if you like!
I don't have any firm evidence, but a Froberger piece on page 64 (84 of the PDF) here is vaguely similar (same key, similar opening arpeggiation) to the Couperin; maybe that's a start?
Comment: Yes, thank you! I am convinced this Toccata (as it says, from Book II) is the piece referred to in L. Couperin.
Comment: Sorry, a further question: Would you say the opening of this Froberger toccata is representative of toccatas generally, or an anomaly? Does it contain octave doubling?
Comment: I didn't encounter any octave doublings, but it's possible a particular performer could add them in, I guess. (But I admit this particular era of performance practice is waaaay outside my expertise!) Otherwise, toccatas tend to be very ornamented, often heavy with arpeggiations. Both pieces seem to fit this description as far as I can tell.
Comment: The Froberger is rather typical of the toccata style stemming from Frescobaldi, i.e., sectional works with sections of great rhythmic freedom contrasted by strict imitative sections. However, given Froberger's very large influence on later Baroque keyboard works, the style certainly spread, and Couperin's unmeasured preludes were an outgrowth. I don't think the Couperin was _directly_ influenced by a specific work (the imitative section, for instance, is quite different than anything in the Froberger toccata), but he may have been trying for Froberger's distinctive harmonic style.
Comment: Thank you, Patrx2. Can a line be draw between Froberger's toccatas / keyboard works and organ music? I am curious if, in moving a form to a different instrument, one would ever double the octaves, perhaps in response to the organ's greater breadth or natural reverberation.
Comment: The toccatas were "keyboard-agnostic" - easily as suitable for the organ as the harpsichord. Actually, outside of his suites, "plaintes" and "tombeaus", most of his keyboard works were quite suitable for the organ. However, octave doubling isn't necessary in such a case, because the organ is an "analogue additive synthesiser": you create both tone colour and intensity by adding pipe ranks pitched on the harmonics (fundamental = 8' stops, 1st harmonic = 4' stops, etc.).


running a simple pdblp code to extract BBG data

Question: I am currently logged on to my BBG anywhere (web login) on my Mac. So first question is would I still be able to extract data using tia (as I am not actually on my terminal)
import pdblp
con = pdblp.BCon(debug=True, port=8194, timeout=5000)
con.start()

I got this error
pdblp.pdblp:WARNING:Message Received:
SessionStartupFailure = {
    reason = {
        source = "Session"
        category = "IO_ERROR"
        errorCode = 9
        description = "Connection failed"
    }
}
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Users/prasadkamath/anaconda2/envs/Pk36/lib/python3.6/site-packages/pdblp/pdblp.py", line 147, in start
    raise ConnectionError('Could not start blpapi.Session')
ConnectionError: Could not start blpapi.Session

I am assuming that I need to be on the terminal to be able to extract data, but wanted to confirm that.
Answer: This is a duplicate of this issue here on SO. It is not an issue with pdblp per se, but with blpapi not finding a connection. You mention that you are logged in via the web, which only allows you to use the terminal (or Excel add-in) within the browser, but not outside of it, since this way of accessing Bloomberg lacks a data feed and an API. More details and alternatives can be found here.


Hypothesis testing: difference between proportions

Question: I am investigating staff inequality between genders and ethnicities in an institution. I have data on contract types (permanent or fixed term) and pay grades for almost all employees. I want to test the hypothesis that there is no inequality across genders and ethnicities in contract types or pay grades.
For example, I have that 592/1972 white people are on a fixed term contract, while 57/114 black or minority ethnicity are on a fixed term contract. Which statistical test to use to test the hypothesis that there is no significant difference?
I was thinking of using the t-test, however the dependent variable is not continuous (it is proportions). I then thought about the two-proportion z test but each of my populations are not at least 10 times as big as its sample (at least for the gender case). I don't think categorical data analysis would help either because I still need to incorporate the fact that I have different sizes of populations? Which test then best matches the assumptions?
Moreover, since I am interested in generalising only to the institution itself, I can say I have the whole population in my data (non-responses were minor), how does that help/not help the analysis?
Answer: A 2x2 chi-squared test ought to suffice. When I plug your numbers into a chi-squared calculator I see a statistically significant difference:
http://www.evanmiller.org/ab-testing/chi-squared.html#!592/1972;57/114@95
In the above calculation Sample 2 corresponds to the minority group. I.e. they are on a fixed-term contract more often than the white group.
(Disclosure: that's my web page and I wrote the calculator.)
Answer: If you truly have the whole population of interest, there's no need for a hypothesis test at all. The point of hypothesis tests are to make inferences about populations. If you have the population you don't need to infer its characteristics from a sample ... you simply look at it. The null is either true or false and you can say which is true (for certain).
(If you have a large fraction of the population of interest, for some tests you have to worry about finite sample effects.)
To compare two proportions, some commonly used tests include the two-proportions Z-test, the chi-square test and Fishers exact test.
Fisher's exact test conditions on both margins in the 2x2 table (and for that matter, the chi-square is also useable in that situation). So by conditioning on both margins, the finite sample issue should be a non-issue -- it's taken care of by the conditioning.
Comment: I disagree that "If you truly have the whole population of interest, there's no need for a hypothesis test at all" because question is not if there is the same proportion or black or white people with some kind of contract. The question here is whether white and black people have the same probability of getting that kind of contract, and to know that you do need hypothesis test - the ones you describe in the last paragraphs of your answer.
Comment: @Pere If you have the whole population of interest, the probability of observing a white person with some kind of contract is $\pi_w=\frac{\text{number of white people in that population with that contract}}{\text{Number of white people in that population}}$ and similarly, $\pi_b=\frac{\text{number of black people in that population with that contract}}{\text{Number of black people in that population}}$. If those two ratios are different, the population parameters are different. ... ctd
Comment: ctd... If you think the probability is not that ratio, *you don't have the whole population of interest*.
Comment: I think I haven't properly worded my comment or properly understood the remarks in your answer. I agree that if we have the whole population of interest, we don't need inference since we can get the proportion by just counting. The issue here is that all employees in the institution is not the whole population of interest, because they are instances from a random distribution, and our population of interest consists on all possible instances of such distribution, not all actual employees in the institution. That is, @Keksainis doesn't have the whole population of interest.
Comment: @Pere Yes, it sounds like we agree -- when we say we "have the population" it's important to be clear about whether we simply have "a population" rather than "the population of interest" (the one we want to make the inferences about). That was the reason I specified the first sentence of my answer the way I did. When people claim to have the population of interest -- but are then confronted with the plain fact that  they can just calculate the population parameters -- they often realize the population of interest is not the population they have a census of.


closed form of a simple binomial weighted series

Question: Does it exists a closed form (also approximating) for the following binomial weighted series?
$$
\sum_{k=1}^n {n \choose k} \cdot k
$$
Comment: I just write an extra answer if you want a method without derivatives.
Answer: By the binomial theorem:
$$
(x + 1)^n = \sum_{k=0}^{n} {n \choose k} x^k
$$
Differentiate both sides with respect to $x$:
$$
n (x + 1)^{n-1} = \sum_{k=1}^{n} {n \choose k} k x^{k-1}
$$
Plug in $x = 1$:
$$
n 2^{n-1} = \sum_{k=1}^{n} {n \choose k} k
$$
Comment: Many thanks Ayman.
Answer: Without calculus answer:
Is easy to prove the next Lemma,

Lemma: $\boxed{k\dbinom{n}{k}=n\dbinom{n-1}{k-1}}.$

Therefore by Lemma,
$$\sum_{k=1}^{n}k\dbinom{n}{k}=n\sum_{k=1}^{n}\dbinom{n-1}{k-1}.$$
Then by binomial Newton's expression,
$$\sum_{k=1}^{n}k\dbinom{n}{k}=n\sum_{k=0}^{n-1}\dbinom{n-1}{k}1^k1^{n-1-k}=n2^{n-1}\square$$


Non-linear regression. Need some help implementing a model from a paper

Question: I found this paper very useful for my research, however, I'm not familiar with non-linear regressions and I'm finding it tricky replicating it.
Using the first f=model for example:
HT = 1.3 + a(1-e^-b*DBH)^c

This is what I have through the help of someone
cr.fit = nls(y~a*(1-exp(-b*x))^c,start=list(a=a,b=b,c=c))
summary(cr.fit)

Now when trying to predict I'm doing this:
TH <- 1.3+(a*(1-exp(-b*10.9))^c)

So far, I have been testing the predictions and sometimes it produces spot-on results, other times it doesn't. I believe this has to do with the starting values I'm using. I'm fairly new to this statistical tool as well as also new to forestry research so I neither have technical knowledge nor domain knowledge for this. My question is what is a good empirical way to get starting values for this type of analysis?
With my personal research on this, I understand this may be difficult to answer but if you were in my shoes, how would you go about this?
I'm just building a methodology for my research so I'm just exploring this to see if it works for me, if I get good results, I would of course seek further knowledge on this to be able to determine good starting values for the species and location I'm researching on.
I have sample data for this here. The relevant columns are HT and DIA.
Comment: There's potentially more structure in your data than just the height and diameter-at-breast-height (DBH). [`tree_data.csv`](https://github.com/brian-o-mars/height-diameter-sim/blob/main/tree_data.csv) shows additional variables about where and when the data collection took place which might be explanatory. I would also develop a [non-linear mixed effects model](https://en.wikipedia.org/wiki/Nonlinear_mixed-effects_model) for comparison.
Comment: @Galen Thanks a lot for your comment. You're correct. In fact, the larger dataset contains even more variables that may provide better statistical results. I'm however just trying to validate this methodology first before utilizing it. Most papers I've read on this actually just used Height and diameter but they created models for future predictions. I, on the other hand, need a model for backward predictions rather so I'm not fully confident just using this methodology without first testing it out. I just need to figure out how to really implement this lol.
Answer: Let's look at the data:
library(data.table)
DT <- fread("https://raw.githubusercontent.com/brian-o-mars/height-diameter-sim/main/tree_data.csv")

library(ggplot2)
ggplot(DT, aes(DIA, HT)) +
  geom_point()

Clearly, the variance increases with increasing HT values. This means a log-transformation is a good idea.
The log-transformed model:
$log(y) = log(a) + c \cdot log(1 - exp(-b \cdot x))$
Luckily, this model is linear in log(a) and c, which means we only need a starting parameter for b. Often you can derive that from domain knowledge (e.g., check some publications). I will just guess it.
DT[, y := HT - 1.3]
DT[, logy := log(y)]

fitlog <- nls(logy ~ cbind(1, log(1 - exp(-b*DIA))), data = DT,
              start = list(b = 0.1), algorithm = "plinear")
summary(fitlog)
#Formula: logy ~ cbind(1, log(1 - exp(-b * DIA)))
#
#Parameters:
#      Estimate Std. Error t value Pr(>|t|)
#b      0.14147    0.00790   17.91   <2e-16 ***
#.lin1  4.46843    0.02337  191.24   <2e-16 ***
#.lin2  1.20448    0.03098   38.88   <2e-16 ***
#---
#Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
#Residual standard error: 0.1988 on 1951 degrees of freedom
#
#Number of iterations to convergence: 3
#Achieved convergence tolerance: 1.797e-06

A diagnostic plot shows that we have pretty good homogeneity:
plot(residuals(fitlog) ~ fitted(fitlog))
abline(0, 0)

(You should investigate that one extreme value.)
Let's look at predictions. On the log-scale:
ggplot(DT, aes(DIA, logy)) +
  geom_point() +
  stat_function(fun = \(x) predict(fitlog, newdata = data.frame(DIA = x)),
                color = "red")

And on the original scale:
ggplot(DT, aes(DIA, HT)) +
  geom_point() +
  stat_function(fun = \(x) exp(predict(fitlog, newdata = data.frame(DIA = x))) + 1.3,
                color = "red")

Now, obviously, for large diameters you will have pretty large differences between measured and predicted values as you can see in the plot. If you want to improve predictions you need to include the additional data in your fits. Since you appear to have repeated measures, you should do that in any case. This means, you need to fit a non-linear mixed-effects model (see R package nlme). Since I don't have a full understanding of your dataset, non-linear mixed-effects models are not trivial to fit, and I have already invested enough time, I'll stop here.


How can we get text while user copying message from whats up , Skype and so on like third party app using iOS Swift?

Question: Step 01: I can run my app (APP NAME : TextDetectAPP)
Step 02: User press Home button
Step 03:User open the  Skype or any third party app (APP NAME : TextDetectAPPMove to Background state )
Spep04: User copy text (I need to get copy text from Skype or or any third party app )
Note :

UIpasteboard  is working fine only user developed apps in iOS swift
Shall we have access rights to read text messages from Skype , whats up or any thirds parts apps  in iOS swift?

Thanks in Advance
Comment: Did you try `UIPasteBoard.general()` ? And see if you can get strings from other apps?
Comment: @BadhanGanesh:- yes . UIPasteBoard.general is used only for user developed apps. How about third party apps like skype,whatsup and so on . I want to access third party for copy messages using swift ios . after moves to back ground state  , how our app came to know user current application in ios swift . Even i have tried current applcation, its works in osx only not an ios device .
Answer: If I understand your question right, you want to get texts that were copied in other apps (Skype, FB etc.). You can do this using the UIPasteboard class. Usually texts are copied to the general pasteboard and you can access it without any problems (I've tried with Skype and Message (iOS) applications, it is working). When you open your app back, you can get the copied text from third party apps like this in the applicationDidBecomeActive delegate method:
func applicationDidBecomeActive(_ application: UIApplication) {
    if let clipboardString = UIPasteboard.general.string {
        print(clipboardString)
    }
}

You can also use UIPasteboardChanged notification to listen to changes in pasteboard, however you cannot receive change notifications from other apps. Also your app may not be in background state all the time executing code (unless you enable some specific background modes like Audio, Airplay etc.). So there is no way for you to get the copied texts when you are in background. You either need to use the method above, (or) if your app supports background execution, you can have an NSTimer fire every n seconds that gets the pasteboard content.
Comment: Badhan Ganesh:- Thanks .Doing great.Can I get text while user copy text in Skype , at the time ,shall we get text in Skype itself, not move to user app? Actually app is running in background state , at the how we can get text of Skype & so on third party apps ?
Comment: @suripappuRengan No you cannot achieve that. See edited answer.
Comment: @suripappu Rengan Did the answer work? If yes, mark the answer as accepted. Or if you have fixed with a different solution, pls post it as an answer here so that other people can benefit from it.
Comment: No. It can't be fixed in iOS .


How to list columns of a table in Bigtable?

Question: cbt -instance=INSTANCE ls table lists column families, but I want to list columns themselves.
Answer: Column families are explicitly created at the table level, while columns are dynamic and can be completely different per row. So, a general purpose tool to list columns is not necessarily possible.
You can write something for your particular needs using a client library in your language of choice, or parse the output of cbt read or cbt lookup command which lets you read every column in one or more rows.
The Quickstart Using CBT page has examples of using these commands and the output they create.
Answer: cbt ls will print all the tables in your current project and instance.
cbt ls <table_name> will list all the column families for that particular table.
Make sure that you have set the project and instance in this case by creating the .cbtrc file. You can find how to set that up here


mudar o estilo de uma tag dentro de outra tag

Question: dentro de uma DIV tem três A e um IFRAME, eu quero mudar o estilo do A sem que interfira no IFRAME, mas eu preciso fazer isso em javascript, pois estou desenvolvendo uma api de um único arquivo e não quero que as pessoas baixem um .css, como é o caso do bootstrap.
PS: Não usarei nenhuma api ou dependência como o JQuery, ou outros, pois as pessoas que forem baixar irão precisar de mais um arquivo.
Comment: Pq vc não coloca o estilo direto na tag tipo `` ou então dentro do `` do su documento vc cria uma tag `
Comment: Porque o objeto teria sido criado completamente por javascript, e quando tocasse nele, mudaria de forma
Answer: O css de uma página mãe não é propagado para um iframe filho, então não se preocupe em simplesmente colocar:
document.querySelectorAll('div > a').forEach(function(elm){
    elm.style.color = 'white'
});

Assim, pegamos todos os a dentro de div e iteramos com o forEach, passando por todos os links.
O seletor > faz com que apenas as primeiras ocorrências da tag a sejam afetadas pelo estilo.
Comment: Obrigado, funcionou!


computing the speed of decreasing of the temperature of a function that depends on the position on the space

Question: Let's suppose that the temperature of a particle at a given position $(x,y,z)$ is given by $ T(x,y,z)=e^{-(x^2+2y^2+3z^2)}$ where $x,y,z$ let's consider that $x,y,z$ are given in meters=m$
If the particle moves at a speed of $ 8 m$ per second, compute the velocity of decreasing of the temperature.
I don't understand, since the problem talk about time, then the position is a function of the form $ r(t)= (x(t),y(t),z(t)) $ and the temperature also depends on time. I thought that I would need to use the gradient, but if I derivate with respect to $t$ I can not find the derivative explicitly.
Comment: You need to know not only the speed of the particle, but also the direction of its motion, i.e., its velocity vector. Then the chain rule will appear with the gradient *and* the velocity vector.
Comment: And How can I use it?
Answer: The chain rule says that
$$\frac d{dt} T(r(t)) = \frac d{dt}T(x(t),y(t),z(t)) = \nabla T(r(t))\cdot \frac{dr}{dt} =
\frac{\partial T}{\partial x}\frac{dx}{dt} + \frac{\partial T}{\partial y}\frac{dy}{dt} + \frac{\partial T}{\partial z}\frac{dz}{dt}\,.$$
To complete the problem, we need to know more than the speed (which is the magnitude of the velocity vector). We need to know both the position and the velocity vector at the desired instant $t_0$. Then we can evaluate the gradient vector at the desired point ($r(t_0)$) and dot it with the velocity vector.


Can the scale be determined from only this excerpt?

Question: How can the musical scale be identified from the following excerpt? Is it possible?
Is there any scale to have a formula like 1 - 2 - ♯3 - 4 - ♯5 - 6 - 7? Perhaps a variation of a scale?
The thing is I found a contemporary semi-composotion written atonally and I'm trying to figure out if any corresponding scales could be found. All notes are used with the following accidentals:

I believe it cannot be either B major or B minor.
Please suggest improvements to or directly edit this post for I believe it is flawed.
Answer: First of all, your formula is completely wrong. The pattern for 1 - 2 - ♯3 - 4 - ♯5 - 6 - 7 on B would be B - C♯ - D♯♯ - E - F♯♯ - G♯ - A♯ because those scale degrees are in reference to the major scale. The actual description of this scale using this notation would be 1 - b2 - 3 - 4 - 5 - b6 - b7. A more standard representation of this would be to describe the steps in which would come to H - A - H - W - H - W - W or internals from root which would be m2 - M3 - P4 - P5 - m6 - m7.
There are more scales out there than just major and minor. This scale is the B Phrygian Dominant scale which is a mode of the E harmonic minor scale.
I have a lot of experience with scales so I can identify them on the fly by looking for a few key elements. To be able to do that you need to familiarize yourself with the pattern of the basic scales and modes you come across and recoginze deviations from the typical pattern. For example in this case I noticed it was a Phrygian scale with a major third thus was able to realize what it was.
Comment: @Veo no. There is no defined key signature for this. Most people would just put the B minor key signature for this to signify B as the root and the fact you are in a minor mode though G major/ E minor would be most appropriate and just write in the D# notes when encountered
Comment: Thank you for your answer. What would be the key sign for B Phrygian Dominant scale? Is it allowed to use non-standard key signatures in this case (i.e. F♯ D♯)?
Answer: No. To determine any scale/mode requires two sets of data, only one of which you have provided.
1) The notes of the scale. That is clear. So far, so good.
2) The "key center," meaning the pitch upon which a resolution is made at the end of the phrase.
That second element is unclear. @Dom has assumed that the B is that note, because you placed it first in your example (the traditional place for the key center in a scale example). But I would ask any inquirer specifically if they [you] already know that B is the resolution point for that phrase. And then give the answer accordingly.
I have no doubt that @Dom is correct, given that corroboration. However, the strict answer to the question is "No, a scale cannot be determined from a collection of notes from an excerpt, until the key center is determined."
Comment: A scale is just a set of notes key doesn't come into play, just the root note matters. Even if you can't assume the lowest note is the root, you can still determine that the scale is one of a few modes which is very reasonable in identification of a scale.
Comment: I hope I'm not coming off as awfully pedantic, but he didn't call his collection of notes a "scale," rather he called it an "excerpt." In fact, he states that he doesn't know the scale, so I assume he ***might*** not even know which note is the root. If the "excerpt" is a complete melodic line (minus the rhythmic notation) then it is just as likely that the final A note ***could be*** the key center. This would make it the 4th mode of the E Harmonic Minor (Dorian #4 or something like that) which is - admittedly - not as prevalent as your correct diagnosis of the Phrygian Dominant.