Semi direct product of two normal subgroups

Question: Let $H\trianglelefteq G$, $N\trianglelefteq G$ such that $N\cap H=\{e\}$ and $HN=G$. Then obviously $G=N\rtimes H$, but also $G=N\ltimes H$. This implies $G=N\times H$.
How do I obtain this last implication? At first I have tried constructing an isomorphism $\phi: N\rtimes H\to N\times H, (h,n)\mapsto (h,n)$ but I failed. Then I have tried to construct an isomorphism $\psi: HN\to H\times N, hn\mapsto (h,n)$ but I have faild at that too. For example, I don't see how $\psi(g_1g_2)=\psi(g_1)\psi(g_2)$ unless I know that $G$ is abelian when having the listed properties.
Comment: Hint: Calculate $xyx^{-1}y^{-1}$ for $x\in H$ and $y\in N$.
Comment: Ah, I see! Thanks! So G is abelian.
Comment: You can find there more detail:https://math.stackexchange.com/questions/106028/semi-direct-v-s-direct-products
Comment: @Buh No, its not. It only means that $H$ commutes with $N$.
Comment: Yes, I forgot the word *not*.
Answer: Consider
$$f:N\times H\to G$$
$$f(h, n)=hn$$

Since $G=HN$ then $f$ is "onto".
Since $H\cap N=\{e\}$ then $f$ is "1-1".
$f$ is a homomorphism.

Proof of 3. For that realize that if $h\in H$ and $n\in N$ then
$$hnh^{-1}n^{-1}\in H$$
$$hnh^{-1}n^{-1}\in N$$
Both follow from the fact that $H$ and $N$ are normal. Thus
$$hnh^{-1}n^{-1}\in H\cap N=\{e\}$$
and thus
$$hn=nh$$
Note that it doesn't mean that $G$ is abelian (and indeed it isn't if one of $H$, $N$ isn't). It only means that elements from $H$ commute with elements from $N$.
Anyway this will be enough to show that $f$ is a homomorphism:
$$f\big((h,n)(h',n')\big)=f(hh', nn')=hh'nn'=hnh'n'=f(h,n)f(h',n')$$


Variable Separable Form for $\frac{dR}{dt}=\frac{t^3+r^3}{t^2r+tr^2}$

Question: I just need a hint or a method on how to separate the equation
$$\frac{dR}{dt}=\frac{t^3+R^3}{t^2R+tR^2}$$
so I can integrate it and get a general solution in terms of $R(t)$
Comment: $t$ cannot be constant. You're taking a derivative with respect to it..
Comment: Is $r$ a constant?
Comment: all r's were supposed to be uppercase in the right hand side my bad
Comment: R and t are variables****
Answer: $$\frac{dR}{dt}=\frac{t^3+R^3}{t^2R+tR^2}$$
$$\frac{dR}{dt}=\frac{(t^2-tR+R^2)}{tR}$$
$$\frac{dR}{dt}=\dfrac tR-1+\dfrac Rt$$
It's homogeneous. $R=ut \implies R'=u't+u$
$$u't+u=\dfrac 1u-1+u$$
$$u't=\dfrac 1u-1$$
It's separable.
Answer: Let $v=\frac{R}{t}\Rightarrow R=vt$ . Then, differentiating both sides of this equation w.r.t. t, we get, $$\frac{dR}{dt}=v+t\frac{dv}{dt}$$ Now, dividing the numerator and denominator of the right hand side of the given differential equation, we get,
$$\frac{dR}{dt}=\frac{1+\displaystyle{\frac{R^3}{t^3}}}{\displaystyle{\frac{R}{t}+\frac{R^2}{t^2}}}=\frac{1+v^3}{v+v^2}\Rightarrow v+t\frac{dv}{dt}=\frac{1+v^3}{v+v^2}$$
$$\Rightarrow t\frac{dv}{dt}=\frac{1+v^3}{v+v^2}-v=\frac{1-v^2}{v+v^2}$$
$$\Rightarrow \frac{v+v^2}{1-v^2}dv=\frac{dt}{t}$$ And so the equation becomes separable in $v$ and $x$.
Comment: I was stuck with this questions for hours my maths is trash and needed help thank you so much
Comment: Such equations are homogeneous equations. Whenever you encounter a homogeneous differential equation use the above substitution to make it separable.


É correto chamar um método, e passar seus parametros null?

Question: Por exemplo, tenho o evento de click de um botão chamando o método abaixo:
 //Evento
 this.serviçoToolStripMenuItem1.Click += new System.EventHandler(this.Nivel_Serv_Click);

 //Metodo
 private void Nivel_Serv_Click(object sender, EventArgs e) //tipo 3 serviço
 {
    //faz alguma coisa....
 }

Em outro método, realizei a chamada do método acima assim:
 Nivel_Serv_Click(null, null);

É certo, fazer isso? ou seria uma gambiarra?
Comment: muito pertinente a sua dúvida.
Answer: Sim, já que não há uma sobrecarga que saiba lidar com sua chamada sem argumentos. Mas pode não ser o mais adequado.
Eu só questionaria se é o que deseja, em geral quando recebe uma notificação de que o objeto teve um evento é provável que queira saber ou fazer algo com este objeto e descartá-lo parece estranho, mas tem casos para isso.
Eu diria que é gambiarra, mas o mecanismo de eventos do C# é uma gambiarra. Evitar gambiarras nem sempre é pragmático, existe a gambiarra boa.
Mas esse método não é chamado por você, então ele não terá argumentos nulos. Se quer chamar um método de evento diretamente, aí talvez seja uma gambiarra maior.
Se quer ter um método que não precisa desses parâmetros, crie um método assim e chame-o, ou use um pronto (veja a resposta do LINQ). Se quer que ele seja executado dentro do método de evento, chame-o dentro do método de evento.
A forma idiomática moderna de C# é evitar o nulo tanto quanto pode. Antes eles faziam parte da filosofia da linguagem, agora só se o domínio exigir isso mesmo.
Coloquei no GitHub para referência futura.
Comment: Só acho que seu ... Sim, deveria já ser transparente, ou seja, "Sim, é uma gambiarra", só depois de ler o texto todo percebi isso. Pois na pergunta ta um pouco obscura para sua resposta ( É certo, fazer isso? ou seria uma gambiarra?)
Comment: @MarconcilioSouza pronto, melhorei
Answer: Se quer executar o código {faz alguma coisa} tanto quando a opção do menu é clicada pelo usuário ou directamente por uma chamada do seu código, o "mais correcto" será criar um método com esse código:
//Evento
 this.serviçoToolStripMenuItem1.Click += new System.EventHandler(this.Nivel_Serv_Click);

 //Método
 private void Nivel_Serv_Click(object sender, EventArgs e) //tipo 3 serviço
 {
    FazAlgumaCoisa();
 }

private void FazAlgumaCoisa()
{
    //faz alguma coisa....
}

Quando o item do menu é clicado o sistema chama Nivel_Serv_Click() que por sua fez chama FazAlgumaCoisa().
Quando o quiser chamar via código chame-o assim:
FazAlgumaCoisa();

Answer: Outro ponto importante é que todos os controles que são botões têm um método chamado PerformClick, ele dispara o evento de click do botão.
Perceba que não há erro em chamar o método do evento passando os dois argumentos como null se você não usar os parâmetros dentro de Nivel_Serv_Click.
Geralmente se usa o sender, já que ele identifica qual foi o controle que disparou o evento. Neste caso, é melhor usar o PerformClick().
Comment: Bem observado..


How to list all url of contents?

Question: I have so many content type like article, contribution, event, c_program etc.
For all content url alias is,
[site_name]/[content type name]/title
But we have some url alias that are like this,
[site name]/title
So, I want to list all url of,
[site name]/title format
How I can I list them out?
Comment: Just wondering, why do you want to list them out?
Comment: I guess the OP needs to correct the latter type of path aliases.
Comment: You could query the url_alias table.
Answer: Use Drupal Pathauto
After enabling it go to admin/config/search/path/patterns and under Default path pattern (applies to all content types with blank patterns below) fieldset you'll get what you want.
Add your desired format there:
[site:name]/[node:title]

Once the configuration is done, click on admin/config/search/path/update_bulk and select Content paths from the given options.
Answer: You can use Views Excel Export. And export all URL's and filter them in Microsoft excel

Simple module that allows to export Views data to Excel (xls).
Uses php-excel class with UTF8 support.
Comment: In that case, the OP should first create a view showing all the path aliases, should not he?

How to list all url of contents?


How can set DirectoryIndex only for one directory in apache?

Question: I tried this:
<Directory path>
DirectoryIndex a/b
</Directory>

But in this way, the DirectoryIndex rule will be aplied all of the subdirectories of path. I want it to work only in the top level.
How can I do this?
Answer: If you have Apache version 2.3.9 or greater, you can use DirectoryMatch with the end-of-line match ("$").
<DirectoryMatch "^/var/www/html/path/$" >
    DirectoryIndex a/b
</DirectoryMatch>

Comment: I'm using version 2.4.38, but it doesn't work to me.
Comment: I've tested it with that version.  Perhaps you have more in your Apache configuration.   BTW, what is "a/b" ???
Comment: It works for me if I remove $ from the beginning. "b" is a file under "a" folder.
Comment: OMG, I'm so sorry!   The first "$" has to be a "^" !!


Fitting/Inference for Dirichlet Process/CRP for clustering

Question: Please excuse my ignorance on this topic, I don't have much experience in nonparametric Bayes. I read about Dirichlet process clustering and the Chinese Restaurant Process analogies. I think I understand the model, and how one can generate clustered data points from it.
But how does one fit this given data for inference? Its greatest utility seems to be inferring an ideal cluster count without prespecification, but every source I've read about the topic seems to be more about the model rather than how it is applied and doesn't really give examples with data.
Answer: The most intuitive way for inference is based on the CRP generative process.
Given some data $X$ of length $N$ and labels $Z$, you would like to know if some sample belong to table $t_k$, in this analogy, each table is associated with a mixture component $\theta_k$, we denote $|t_k^{-1}|$ as the number of customers siting at table $k$, minus the $i^{th}$ customer if he is sitting there:
$$
\Pr(z_i = k|x,Z^{-i},(\theta_k)_1^\infty )\propto \frac{|t_k^{-1}|}{N-1+\alpha}\cdot f_\theta(x_i|\theta_k)
$$
In words: The probability of sample $x_i$ sitting at table $t_k$ (or belonging to mixture component $\theta_k$) is proportional to the number of customers siting at the table, and the likelihood of $x_i$ beloning to componenet $\theta_k$ (which is the likelihood function, and depends on the component type).
In addition, there is always the chance of opening a new table:
$$
\Pr(z_i = k_{new}|x,Z^{-i},(\theta_k)_1^\infty )\propto \frac{\alpha}{N-1+\alpha}\cdot f_\theta(x_i|\theta_{new})
$$
Where in this case $\theta_{new}$ is a sample from your base measure $H$.
You update the component parameters according to the samples belonging to each component. This process is very slow, as each label depends on the rest of the entire model, but in my opinion, it is intuitive.
There are other methods for inference, either by sampling or by variational inference, which can be very fast.
Answer: (I think Dinari's answer is correct, but I want to try to target the difficulty faced by OP a bit more.)

every source I've read about the topic seems to be more about the model rather than how it is applied and doesn't really give examples with data.

The Dirichlet process (DP) or CRP is only the prior in a Dirichlet process mixture model. It is not a clustering algorithm as you seem to think. Therefore, if you search for DP or CRP, you might only get details about the process itself, but not on how to use it in mixture models.
More precisely, in a mixture model, the cluster assignment variables are latent variables and each cluster is characterised by a set of parameter (for example, mean and variance if your base distribution is a Gaussian). The DP is used as a prior over cluster assignments. It is easy to use with Gibbs sampling because the posterior of a single assignment variable given the other assignments is very easy to compute. (See Dinari's formulas.)
If you are using a Gaussian, you will have a mean and variance parameter for each cluster (and in our case, the number of clusters is sampled and can vary, thanks to the CRP). You would take the mean parameter for the cluster $i$ to be simply the mean of the datapoints which are assigned to this cluster $i$.
I am not sure about the following, please correct me if I'm wrong / approve if I'm right: You can fit finite mixture models with EM. In the E-step, you compute the expectation of each cluster assignment and from there find the parameters that maximize it. Here, you cannot computing the expectation under the posterior, so instead, you sample from it and maximize. So maybe it is a variant of EM with sampling at the E-step.
Comment: Regarding the last part of your answer - You are correct, the process is very similar to the Bayesian formulation of mixture models, where you assume some prior (say, NIW for Gaussians) over the component parameters, and sample the $\mu,\Sigma$ from the posterior, given the data assignments, re-sample the assignments, repeat.


Customização Carousel

Question: Olá a todos sou iniciante em Bootstrap, e estou desenvolvendo um carousel no boostrap, só que ao invés de mostrar apenas uma imagem gostaria que mostrasse 3, como na imagem abaixo. Como que eu poderia estar fazendo isso

Código

                Anterior

                Próximo

Comment: Sei que não tem a ver com a pergunta, mas eu iria fazer com o [owlcarousel](https://owlcarousel2.github.io/OwlCarousel2/demos/basic.html). É responsivo, altamente customizável, pode aplicar efeitos de transição, editar e colocar quantos itens deseja, definir tamanho...
Comment: Aqui tem um exemplo usando *Bootstrap 3*, https://www.bootply.com/94444
Answer: Vc pode colocar 3 imagens no container e usar classes do Bootstrap como d-none d-flex para ir fazendo a responsividade. No desktop vc mostra 3, no tablet 2 e no smartphone 1 por vez?
Segue um exemplo simples que fiz seguindo esse conceito. As vezes pode ser útil para vc.

.carousel-item-next, .carousel-item-prev, .carousel-item.active {
    display: flex !important;
}
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

                Anterior

                Próximo

Customização Carousel


How to read multiple properties with same prefix in java spring?

Question: I am having the property file with the following values. I want to read all the properties with same prefix excluding others using spring mvc.
test.cat=cat
test.dog=dog
test.cow=cow
birds=eagle
Environment.getProperty("test.cat");

This will return only 'cat' .
In the above property file, I want to get all the properties starting(prefix) with test excluding birds. In spring boot we can achieve this with @ConfigurationProperties(prefix="test"), but how to achieve the same in spring mvc.
Answer: See this Jira ticket from Spring project for explanation why you don't see a method doing what you want. The snippet at the above link can be modified like this with an if statement in innermost loop doing the filtering. I assume you have a Environment env variable and looking for String prefix:
Map<String, String> properties = new HashMap<>();
if (env instanceof ConfigurableEnvironment) {
    for (PropertySource<?> propertySource : ((ConfigurableEnvironment) env).getPropertySources()) {
        if (propertySource instanceof EnumerablePropertySource) {
            for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
                if (key.startsWith(prefix)) {
                    properties.put(key, propertySource.getProperty(key));
                }
            }
        }
    }
}

Answer: I walked into a similar problem and solved it using the following code:
final var keyPrefix = "test";
final var map = new HashMap<String, Object>();
final var propertySources = ((AbstractEnvironment) environment).getPropertySources().stream().collect(Collectors.toList());
Collections.reverse(propertySources);
for (PropertySource<?> source : propertySources) {
    if (source instanceof MapPropertySource) {
        final var mapProperties = ((MapPropertySource) source).getSource();
        mapProperties.forEach((key, value) -> {
            if (key.startsWith(keyPrefix)) {
                map.put(key, value instanceof OriginTrackedValue ? ((OriginTrackedValue) value).getValue() : value);
            }
        });
    }
}
return map;

Difference with other solutions (like seen in Jira ticket) is that I reverse sort the property sources to ensure that the appropriate overriding of properties is happening. By default the property-sources are sorted from most important to least important (also see this article). So if you would not reverse the list before iterating you will always end up with the least important property values.
Answer: Try this method. In your example, calling getAllPropWithPrefix("test") will return a Map containing {test.cat=cat,test.dog=dog,test.cow=cow}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class SpringPropertiesUtil {

    @Autowired
    private ConfigurableApplicationContext applicationContext;

    /**
     * Get all properties with specific prefix.
     */
    public Map<String,String> getAllPropWithPrefix(String prefix) {
        BindResult<Map<String, String>> result = Binder.get(applicationContext.getEnvironment())
                .bind(prefix, Bindable.mapOf(String.class, String.class));
        if (!result.isBound() || result.get()==null) {
            return Collections.emptyMap();
        }
        return result.get().entrySet().stream().collect(Collectors.toMap(x->prefix+"."+x.getKey(),x->x.getValue()));
    }
}

Answer: There is more eloquent solution using existing API:
Given the following simple object:
internal class AboutApi {
    lateinit var purpose: String
    lateinit var version: String
    lateinit var copyright: String
    lateinit var notice: String
    lateinit var contact: String
    lateinit var description: String
}

And an instance of Spring environment (org.springframework.core.env.Environment), it becomes as easy as 1-2-3 to extract a value of AboutApi from the environment:
private fun about() : AboutApi {
    val binder = Binder.get(env)                   // Step - 1
    val target = Bindable.ofInstance(AboutApi())   // Step - 2
    binder.bind("api.about", target)               // Step - 3
    return target.value.get()                      // Finally!
}

Get a binder which source values from the environment.
Declare a target you want to bind to.
Bind all keys from the environment which starts with api.about to our target.

Finally --
Retrieve the value!
Comment: The question is tagged Java.
Answer: I use this approach to load properties with a certain prefix in Spring (Assuming that you have injected Configuration in your component):
Properties properties = new Properties();
configuration.getKeys("test.")
   .forEachRemainingKey(key -> properties.setProperty(key, configuration.getString(key));

Answer: The answers from Manos and Yoran are helpful. I found a small change to Manos' code would be able to address Yoran's concern. Basically, the same propertity may come multiple times, from environment variable and application.yml for example, in the order of importance descending. Thus we can just get the first instance by checking that the key is not in properties already, as in the improved code below:
Map<String, String> properties = new HashMap<>();
if (env instanceof ConfigurableEnvironment) {
    for (PropertySource<?> propertySource : ((ConfigurableEnvironment) env).getPropertySources()) {
        if (propertySource instanceof EnumerablePropertySource) {
            for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
                if (key.startsWith(prefix) && !properties.containsKey(key)) {
                    properties.put(key, propertySource.getProperty(key));
                }
            }
        }
    }
}


New User Registration Sequence for Services 3.4?

Question: This comment outlines a working way to login with the new CSRF token:

POST to /rest/user/login (nothing in headers). Construct the $cookie from session name + id
GET to /services/session/token (include $cookie in the headers). Save the $token returned.
Include $cookie and $token in the headers of subsequent requests of a logged in user.

That sequence works even though the first POST happens without sending the token. (The documentation suggests that the token should be used for any POST requests, which does not work in this case.)
What is a working sequence of HTTP requests to register a new user account? I'm looking for what requests to make in what order - not implementation code.
UPDATE: To be clear, I'm not looking for the login sequence. I need a sequence of requests (similar to login example above) that allow a new user to *register* their account.
Failed Attempt with system/connect:

1. GET:services/session/token

2. POST:system/connect
      Content-Type: application/json
      Accepts: application/json

3. POST:user/register
      Content-Type: application/json
      Accepts: application/json
      X-CSRF-Token: [token]
      Cookie: [session_name]=[sessid]
      Body: {
               "name":"drupalspec0rVzsWAU",
               "pass":"PYKSItFK",
               "mail":"email@example.com"
      }

The Drupal user is created correctly, but the request in step 3. times out.
Answer: Edit: to address the change in the question

I'm looking for what requests to make in what order - not implementation code

You can safely ignore the actual code implementation below - the order of the requests remains the same. In fact, exactly the same as in your original question.
If you're already making requests in the order that you've outlined, you needn't do anything more except provide an actual implementation. I'll leave the code in as an example, and so you can see exactly what order the requests need to be made in. I've stuck some numbering in to make it more obvious; the requests are denoted by 1, 2 & 3.

This is a basic PHP (i.e. non-Drupal) example...
First off make a generic function for sending your requests:
function send_request($url, array $post_array = array(), $cookie = NULL, $token = NULL) {
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, 'googlebot');
  //curl_setopt($ch, CURLOPT_VERBOSE, $post_array);

  if (!empty($post_array)) {
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array);
  }

  if ($cookie) {
    curl_setopt($ch, CURLOPT_COOKIE, $cookie);
  }

  if ($token) {
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-CSRF-Token: ' . $token));
  }

  $result = curl_exec($ch);
  curl_close($ch);

  return $result;
}

1. Then make your first call to log the user in:
// Login.
$data = array(
  'username' => 'user',
  'password' => 'password',
);

$result = send_request("http://server/endpoint/user/login.json", $data);

try {
  $result = json_decode($result);
}
catch (Exception $e) {
  die('Login failed: ' . $e->getMessage());
}

Next get the session name and ID, creating your cookie string to send with subsequent requests:
$session_id = $result->sessid;
$session_name = $result->session_name;
$cookie = $session_name . '=' . $session_id;

2. Then get a CSRF token, making sure to pass the cookie along:
$token = send_request("http://server/services/session/token", array(), $cookie);

3. Finally you can perform your request to the endpoint you're actually interested in. The cookie and token are injected by the send_request() function.
$user = array(
  'mail' => 'firstname.lastname@example.com',
  'name' => 'name',
  // Other relevant properties/fields.
);

$result = send_request('http://server/endpoint/user', $user, $cookie, $token);

I haven't tested the user creation endpoint so that might not be the exact structure it needs, but checking the responses for errors should let you know exactly what it's after quite quickly. I get the impression from your question that you're mainly interested in the steps leading up to that last request anyway.
The above is adapted from a basic test script I use, for a production environment you'll want to add more error/sanity checking in there. And the functionality is crying out to be wrapped in a class, and be extended to support PUT/DELETE, but I'll leave that to you :)
Comment: Ahh ok, sorry I didn't get that. You probably need to replace the call to login with system/connect, I think that'll get you the session info without logging in. Then proceed as normal with steps 2/3 above. Just on mobile so can't check it out at the mo, will take a proper look later on
Comment: Thanks for the PHP login example, @Clive. I'm actually trying to figure out `user/register` in particular. I'll be working in another language so I'm just looking for the HTTP requests.
Comment: @JoeBeuckman OK...that would be a naked `POST` to the login URL, followed by a `GET` to the token URL with the cookie string as part of the request, followed by a `POST` to the user endpoint containing the cookie, the `X-CSRF-Token` header, and the account data. There's not really anything more that I can say, that workflow just needs to be implemented in the language of your choice. The above PHP should make porting it pretty easy (if you're familiary with php, of course). BTW `user/register` is a synonym for `user/create` so you can use them interchangably
Comment: Actually, I'm not really sure how this doesn't answer your question, could you explain why the implicit order described above is insufficient for your needs? Are you looking for extra info that isn't listed in the question?
Comment: The sequence you provided is for `login` and my question asks about `register`. Good to know that `user/register` is a synonym for `user/create` although they seem like they should be different to me. I'm looking for a way a new user can create their account. They aren't logged in and can't log in until they have an account. I assumed that was `user/register` and I don't understand how to create an account while not logged in.
Comment: Thanks! I'll try that ASAP. Is that the primary function of `system/connect`?
Comment: Hm, I've been trying various permutations with system.connect and it seems like the problem might be the same timeout issue as in this question: http://drupal.stackexchange.com/questions/79448/240sec-registering-new-account-with-services
Comment: Sorry this got away from me - yes, the primary function of system.connect is to return the current user object/session id. The timeout issue is a strange one, not one I've come across before
Comment: Looks like timeout is a configuration issue on one of my servers. Registration is working with GET token + POST system/connect + POST user/register. Could you copy your suggestion about system/connect to a new answer so it's clear?
Comment: This works really well. Although I'm trying to build a javascript-based client, it's good to test the service against something reliable.
Comment: Thanks again Clive - I just voted this up again. The order of 1. and 2. is key.


How to configure slur with tie when writing choral music?

Question: I'm writing a choral piece in 12/8 where the basses have a dotted quarter C, tied to a dotted half, tied to a dotted quarter, and then slurred to a C# - all while on the same syllable. How should I configure the slurs and ties to best show this:
Like this?

Or like this?

Thanks!
Comment: I think the clearest option would be a combination of phoog's and Albrecht's answers: slur starting on the first note, but not on the same side as the ties (so if you maintain the downwards ties, the slur should go above the system). This way the semantically different arcs are visually separated as well. (Not posting an answer since all this is already present in the existing answers.) The combination of multiple slurs or ties too close to each other with interference from the staff lines gets very hard to read very quickly. (For example, how many Ls are this: lllll?)
Comment: As the lyric is ye-ni I doubt that solution above the staff is correct. The phrasing in the middle of a word doesn't seem good to me, not logically.
Comment: 1. From which text is this syllable  ye  - - . I'm asking because I don't understand why the slur ends om C#.  2. Why don't you place the slur above the system? 3. Why writing in 12/8? 4/4 with some triplets would be much easier to read for all voices.
Comment: The full word is "yeni," it continues onto the next page. It's from Tolkien's Namarie. The piece is full of triplets, so going into 4/4 isn't an option unfortunately. [Here's a link to a version with the slur above the staff,](https://i.imgur.com/BMUMhJh.png) this way's not too bad either.
Comment: An other point I'd like to know: is this your own melody composition or an arrangement of an existing tune? As I've been looking for the song I've found different composer's sets to music of these  lyrics https://www.outono.net/elentir/2018/02/19/namarie-the-most-spectacular-version-of-the-farewell-song-written-by-tolkien/ but  any available song was in 12/8 time  except one was in 6/8 https://musescore.com/user/9400101/scores/2171681.   So I think 6/8 might  also solve the problem of readability.
Answer: The first solution is correct.  The slur should start at the beginning of the first note under the slur.
The second solution is difficult to sight read.  It seems ambiguous at first glance, and it is only with careful analysis that one realizes that it isn't.
I'll try to remember to edit this answer to cite some examples of this notation sometime in the next couple of days.
Answer: In such a situation you should  set the slur above the system to make it better readable.
But there are other alternatives:

The slur could end on an other syllable in the next bar.
The time could be notated in 4/4 and with triplets: in this bar you'd have just a dotted half-note.

Edit:

As you say below your question the slur is underlying the word ye-ni, what means long year. So I wouldn't interrupt the phrasing of this word, as it would be 2 short years. (S. my comment above). The slur must end at the last note of the 2nd syllable of ye-ni to make sense.
Comment: My understanding was that I needed a slur there since there will be multiple notes sung under 1 syllable (like a melisma only just two notes). [Here's an image that shows an example of this.](https://houstonsymphony.files.wordpress.com/2010/12/melismas.jpg) It is an original composition, so going into 6/8 is an option. I kinda like the 12/8 style though - in most of the piece readability isn't an issue.
Comment: I thought this is like a melisma, Thanks to you I've found the lyrics. Can we here your composition? By the way what we do in brass bands when the bass has a long phrase is assigning different points of phrasing for breathing. So you could as alternative of a slur set a breath comma to avoid this collision of ties/slur.
Comment: Well, I'm in the middle of writing it right now. I usually compose directly in Musescore, that way I can hear the midi playback as I go. Us singers will stagger breathe in long phrases as well, although it's not usually written in the score (since each individual singer will try to breathe a different place from those around them). The dotted quarter in this piece is about 50 bpm, so it's not quite long enough to need that though.
Answer: A tie simply gives the opportunity to make longer notes than are available, or need to go across a bar line.
A slur 'joins together' a series of notes, (which are usually not the same pitch), that would then be played 'all in one breath'.
Since what you show isn't even the full word, it might be better still to make the slur curve between the beginning and end syllables. However, if you only want the first part to be slurred, you're joining all the notes from the first utterance of 'y', not the end of it, so the second example isn't good anyway. The first is fine for as far as we can see, but bear in mind my earlier thought.
Answer: Certainly not the second example.  The first is correct.  Maybe putting the melisma (one syllable, several notes) slur on top would be clearer.
Answer: The first solution is most correct, although the slur could be placed above the note stems instead.
The second solution may appear to performers to be a typo, and interpretation of the composer's intent may be debated.
That aside, I'm wondering why you need to slur a note that's held across a single syllable. If a breath should be taken in the middle of the syllable after the C#, perhaps a breath mark would suffice better than ending a slur (assuming the note after the C# holds the same syllable). The end of a slur in the middle of a held syllable across notes may also be open up to interpretation by the performers as they won't know whether to take a breath or keep the syllable held as they normally would have. So for this instance I'd say don't use a slur or if anything use a breath mark where intended.
Answer: If more than two notes are tied together, there should be a separate tie connecting every note but the last to its successor.  If more than two notes are slurred together, however, they should generally all use one slur unless layout considerations force them to be placed separately (e.g. if a slurred passage doesn't fit on one line).
Although not all engravers are consistent with this, it is useful to place ties between the notes being connected, while slurs should extend between points that are above and below the notes in question.  If one makes ties and slurs visually distint in that manner, there will be no confusion about whether something is a tie or a slur.
Otherwise, if has a curved mark which connects a point above or below a note that has an accidental with a note on the same staff position in the next measure, it may be unclear whether it's a tie that extends the duration of a note that sustains the altered pitch, or a slur which connects an altered note in one measure with an unaltered note in the next.  If ties are placed horizontally between notes, then ties and slurs would be recognizable as different.


Delete IIS log files

Question: I do not find a way to disable and delete log file at C:\inetpub\logs\LogFiles\W3SVC2\u_extend1.log
The file is extremely large about 50gb, I have tried to delete it as administrator, but got an error that the file is used by System.
I thought that this file is generated by IIS7, disabled IIS7 and logging, restarted Windows but still file is use. Please help?!
Comment: Have you tried to set maximum log file size in Logging section of IIS  console? Is logging configured per site/per server?
Answer:
Stop the IIS Admin and World Wide Web Publishing services either via the command line or the services.msc console to unlock the file (obviously this will stop IIS, so if you are hosting production sites do this in a maintenance window).
Delete the file.
Configure logging options as documented by Microsoft.

If for some reason you still show it as in use, use Process Explorer to find the process using it.  Select Find->File Handle or DLL and enter the file name.
Answer: If you want to optimize the HDD space required to host IIS log files without resorting to delete them, I suggest you to implement the following best practices:

Open the IIS Manager > Logging and change the Log File generation frequency to Daily, so you will have 1 logfile for each day.
Activate the "compress file and folders" feature on that LogFile folder.
Setup a cleanup of files older than N days (30, 90 or 180 depending on your scenario) by using a batch file or a Powershell script (and a Scheduled Task to run it on daily basis).

See this other answer and/or read this post for more details regarding how to do these steps.

Delete IIS log files


Move Windows 10 Enterprise KMS to Enterprise Subscription Activation

Question: Recently, I moved a Windows 10 Home machine from factory to a Windows 10 Enterprise by using a KMS product key. It was an emergency situation as the employee was remote and we could not procure a Windows 10 Pro machine in a reasonable amount of time.
The thought process was, convert that Windows 10 Home to Enterprise using the KMS generic key, reset Windows, and let it join the domain (before the reset I added the machine to Windows Autopilot getting the hardware ID from the Get-AutoPilot PowerShell), join the Azure AD domain, auto-provision, and then use the Windows 10 Enterprise subscription license assigned to the authenticated user.
All of this happened successfully, except for the last bit. The machine is correctly joined in the Azure AD domain, I have all policies deployed to the machine, everything as expected in an Autopilot/Intune OOBE model.
However, I cannot figure out a way to remove the KMS key and let it use the Subscription Activation feature. It always fails with the error 0x8007232B (for when it cannot find a KMS server, which we don't have, I just wanted a quick way to allow the machine to have the ability to join an Azure AD domain and use our licenses).
I have tried using the command below to remove the product key and force an activation, but it failed it with another error code, and then the KMS key showed up back in the Activation settings:
slmgr.vbs /upk

Currently, Windows is sitting on an Enterprise license with a KMS key in not activate state.
How can I force this now Windows 10 Enterprise with a generic KMS key to consider the Subscription one for activation?
Answer: According to the offical documentation, the process should be completely automatic if the user has been assigned a proper license.
Quoting from "Scenarios":

devices that are already running Windows 10 Enterprise will migrate
from KMS or MAK activated Enterprise edition to Subscription activated
Enterprise edition when a Subscription Activation-enabled user signs
in to the device.

What you did (changing the Windows license to Enterprise KMS and then moving to subscription activation) is also explicitly supported:

To change all of your Windows 10 Pro devices to Windows 10 Enterprise,
run the following command on each computer:
cscript.exe c:\windows\system32\slmgr.vbs /ipk NPPR9-FWDCX-D2C8J-H872K-2YT43

The command causes the OS to change to
Windows 10 Enterprise and then seek out the KMS server to reactivate.

So it looks like your approach is viable: but the subscription activation itself is not working.
I suggest you review and confirm the requirements:

Windows 10 (Pro or Enterprise) version 1703 or later installed on the
devices to be upgraded.
Azure Active Directory (Azure AD) available for identity management.
Devices must be Azure AD-joined or Hybrid Azure AD joined.

Also make sure that the computer account of the device in your AD domain is correctly synced to Azure AD by ADConnect.
If it still doesn't work, the article contains detailed instructions for various scenarios; if all else fails, you'll need to open a support ticket with Microsoft.
Comment: If I read correctly, he changed from Home to Enterprise. I didn't know that was possible. Maybe that has something to do with it?
Comment: Regardless of the starting state, he now has an Enterprise KMS machine which *should* be able to use subscription activation.
Comment: The thing is, I don't have a KMS server for it go look for activation, and that's what I think it's screwing up here. I did see the documentation you mentioned, and that's also the key I'm using, but it just doesn't transition from KMS to Subscription.
Comment: The documentation doesn't mention actually *having* a KMS. It only states that an Enterprise KMS edition should accept subscription activation.
Comment: @Massimo it's explicitly saying that it does "The command causes the OS to change to Windows 10 Enterprise and **then seek out the KMS server to reactivate.**" - so I think that's what happens and the limitation of this scenario.
Comment: I am starting to believe I need to activate a retail Windows 10 Pro key on that machine downgrading it from Enterprise to Pro and then it will upgrade to Enterprise as it rejoins the domain and checks for the license assigned to the user.
Comment: This does indeed seem not quite clear; I'd ask Microsoft.


How to parse a syslog message with pyparsing

Question: I have syslog that like below.
date=2015-10-08 time=16:03:26 devname=D1_FIG device_id=ID300B3908601UID log_id=0021000002 type=traffic subtype=allowed pri=notice vd=root src=188.8.131.52 src_port=3584 src_int="port4" dst=220.127.116.11 dst_port=80 dst_int="WLN_200" SN=2775431942 status=accept policyid=430 dst_country="United Kingdom, Great Britain" src_country="United Kingdom, Great Britain" dir_disp=org tran_disp=dnat tran_ip=126.96.36.199 tran_port=80 service=HTTP proto=6 duration=120 sent=132 rcvd=92 sent_pkt=3 rcvd_pkt=2
I want to parse this log using pyparsing like this.
{"date", "2015-10-08"}
{"time", "16:03:26"}
{"devname", "D1_FIG"}
{"device_id", "ID300B3908601UID"}
....
{"src", "126.96.36.199"}
....
{"dst_country", "United Kingdom, Great Britain"}
....

source code is like this.
from pyparsing import *

origin_str = "date=2015-10-08 time=16:03:26 devname=D1_FIG device_id=ID300B3908601UID log_id=0021000002 type=traffic subtype=allowed pri=notice vd=root src=126.96.36.199 src_port=3584 src_int=\"port4\" dst=220.127.116.11 dst_port=80 dst_int=\"WLN_200\" SN=2775431942 status=accept policyid=430 dst_country=\"United Kingdom, Great Britain\" src_country=\"United Kingdom, Great Britain\" dir_disp=org tran_disp=dnat tran_ip=184.108.40.206 tran_port=80 service=HTTP proto=6 duration=120 sent=132 rcvd=92 sent_pkt=3 rcvd_pkt=2"

date_s = Word(nums, nums+'-')
time_s = Word(nums, nums+':')
identifier = Word(alphas, alphanums+'_') | date_s | time_s
equal = Literal("=").suppress()
KeyNValue = identifier.setResultsName("lhs") + equal + identifier.setResultsName("rhs")

for srvrtokens,startloc,endloc in KeyNValue.scanString(origin_str):
    print srvrtokens

This is what I have so far:
['date', '2015-10-08']
['time', '16']
['devname', 'FW_IDC1']
['device_id', 'FG300B3908601477']
['log_id', '0021000002']
['type', 'traffic']
['subtype', 'allowed']
['pri', 'notice']
['vd', 'root']
['src', '147']
['src_port', '58979']
['dst', '210']
['dst_port', '80']
['SN', '2770251942']
['status', 'accept']
['policyid', '430']
['dir_disp', 'org']
['tran_disp', 'dnat']
['tran_ip', '172']
['tran_port', '80']
['service', 'HTTP']
['proto', '6']
['duration', '120']
['sent', '132']
['rcvd', '92']
['sent_pkt', '3']
['rcvd_pkt', '2']

But I don't know how to parse "time" and "dst_country" string.
Comment: Your desired output isn't quite a `dict` or `list`.  What exactly is the form of your desired result?
Comment: It does not matter either. My problem is parsing. And your answer is solve my problem!
Answer: This program produces a dict of the data in the log string.
from pyparsing import *
from pprint import pprint

origin_str = "date=2015-10-08 time=16:03:26 devname=D1_FIG device_id=ID300B3908601UID log_id=0021000002 type=traffic subtype=allowed pri=notice vd=root src=188.8.131.52 src_port=3584 src_int=\"port4\" dst=22.214.171.124 dst_port=80 dst_int=\"WLN_200\" SN=2775431942 status=accept policyid=430 dst_country=\"United Kingdom, Great Britain\" src_country=\"United Kingdom, Great Britain\" dir_disp=org tran_disp=dnat tran_ip=18.104.22.168 tran_port=80 service=HTTP proto=6 duration=120 sent=132 rcvd=92 sent_pkt=3 rcvd_pkt=2"

key = Word(alphas, alphanums+'_')
value = quotedString | Word(printables)
equal = Literal("=").suppress()
KeyNValue = key + equal + value

result = dict(srvtokens for srvtokens,_,_ in KeyNValue.scanString(origin_str))
assert len(result) == origin_str.count('=')

pprint(result)

result:
{'SN': '2775431942',
 'date': '2015-10-08',
 'device_id': 'ID300B3908601UID',
 'devname': 'D1_FIG',
 'dir_disp': 'org',
 'dst': '220.127.116.11',
 'dst_country': '"United Kingdom, Great Britain"',
 'dst_int': '"WLN_200"',
 'dst_port': '80',
 'duration': '120',
 'log_id': '0021000002',
 'policyid': '430',
 'pri': 'notice',
 'proto': '6',
 'rcvd': '92',
 'rcvd_pkt': '2',
 'sent': '132',
 'sent_pkt': '3',
 'service': 'HTTP',
 'src': '220.127.116.11',
 'src_country': '"United Kingdom, Great Britain"',
 'src_int': '"port4"',
 'src_port': '3584',
 'status': 'accept',
 'subtype': 'allowed',
 'time': '16:03:26',
 'tran_disp': 'dnat',
 'tran_ip': '220.127.116.11',
 'tran_port': '80',
 'type': 'traffic',
 'vd': 'root'}

Comment: Sometimes the disconnect between the parsed structure and the desired one forces this kind of post-parse structure building.  But in this case, you can have pyparsing build the dict for you at parse time using the Dict class: `result = Dict(OneOrMore(Group(KeyNValue))).parseString(origin_str).asDict()` .  The OP can also make the value more discriminating with type-specific formats and parse-time converters added as parse actions to give actual ints, floats, datetimes, etc. instead of just strings. But those are all good follow-up exercises for the reader. Nice answer!
Comment: Perfect answer. Robᵩ. Would you explain " srvtokens for srvtokens,_,_ in KeyNValue.scanString(origin_str)" to me? and Paul's answer is nice too!.


Qual a forma mais adequada de armazenar uma referência em um objeto?

Question: Suponhamos que eu queira criar uma biblioteca, onde um objeto deve receber outro objeto adicionado pelo usuário e armazenar para uso posterior.
Ex:
//header.h
class Caixa{
private:
   Botao botoes[5];
public:
   void addBotao(Botao botao){
      int i;
      while(botoes[i]!=NULL)
         i++;
      botoes[i] = botao;
   }
   Botao getBotao(int i){
      return botoes[i];
   }
}

class Botao{
private:
   char nome[10];
public:
   void Botao(char texto[10]){
      nome = texto;
   }
}

//main.cpp
void main(){
   Caixa caixa1 = Caixa();
   Botao botao1 = Botao("clique");
   caixa1.addBotao(botao1);
}

Por questões de economia de memória seria interessante passar esse objeto por referência. Mas, considerando que referências devem ser referenciadas na inicialização, me parece que não seria possível armazenar a referência no objeto, certo ?
Usando ponteiros para fazer a passagem, eu não teria segurança de que a variável ainda estaria ali quando eu fosse usar. Podem me dizer qual a forma mais adequada de resolver esse problema ?
Answer: Você quer aprender do jeito certo ou do jeito gambiarra? Vou pelo certo.
Então modernizei seu código usando C++11/14. Não misture C com C++. E se vai usar C++, use o recursos mais modernos a não ser que tenha uma restrição no projeto que está trabalhando (o que não parece ser o caso).
Algumas coisas podem ser um pouco diferentes dependendo da intenção. Provavelmente eu evitaria o shared_ptr e tentaria usar o unique_ptr ou reference_wrapper. E provavelmente eu usaria o emplace_back() no lugar do push_back, assim não precisaria criar o objeto separadamente, mas depende do que quer.
É possível armazenar a referência, mas provavelmente seria um erro. Com ponteiros brutos é um problema, mas com ponteiros gerenciados dá para ter "segurança".
#include <string>
#include <vector>
#include <memory>
using namespace std;

class Botao {
private:
   string nome;
public:
   Botao(string texto) {
      nome = texto;
   }
};

class Caixa {
private:
   vector<shared_ptr<Botao>> botoes;
public:
   void addBotao(shared_ptr<Botao> botao) {
      botoes.push_back(botao);
   }
   shared_ptr<Botao> getBotao(int i) {
      return botoes[i];
   }
};

int main() {
   auto caixa1 = Caixa();
   auto botao1 = make_shared<Botao>("clique");
   caixa1.addBotao(botao1);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


How can the two basic binary operations (addition and subtraction) be defined in set-theoretical terms?

Question: I recently stumbled upon this interesting definition of mathematics:

Math is the study of things that can be described as sets.

I am aware that the integers and the real numbers can be defined in terms of sets, but how can we define the operations of addition and subtraction?
Comment: http://math.stackexchange.com/a/1009721/119110
Comment: https://archive.org/details/settheorystruct00hami
Comment: Addition and subtraction where?
Comment: Natural numbers are finite ordinals and for all ordinals we define addition as the order type of the set that we  get when we take the disjoint union of the sets and order all elements in each component by the old order and everything in the left summand is less than anything in the right summand. This gives the usual addition on the natural numbers. To give but one example.
Comment: @GitGud: Well, since I mentioned them, addition and subtraction in the real and integer number systems.
Comment: @GeorgeChen Thanks, ur answer to that question in the link is relevant and helpful
Answer: You can use cardinals of sets to construct the natural numbers and prove the Peano axioms. Also you can use the ordinals defining $0:=\emptyset$ and $n^+:=n\cup \{n\}$, and so prove the Peano axioms again.
To construct the integers from natural numbers, you can use the cartesian product to define integers $(a,b)$ and $(c,d)$ such that two integers are equal if $a+d=c+b$.
The topic is technical so you need to read a book about set theory abd foundations. The Wikipedia has good references.
Answer: Just to give an idea ( but I'm far from being an authority).
You may have a look at Peterseon, Theory Of Arithmetic.

One may say that : $0$ is ( by definition) the same object as $\emptyset$.

Define $S(n)$ ( the successor of number $n$) as the set : $n \cup \{n\}$.

So, for example, $S(0) = S(\emptyset)= \emptyset\cup\{\emptyset\}=\{\emptyset\}$.
Call this number: " number 1". Hence : $1 =\{\emptyset\} =\{0\}$ by definition.
Note : continuing the process , you will get this ( at first sight)  " strange" result that every natural number is the set of all its predecessors.

Then state two rules in order to define addition as a function taking as input any couple of natural numbers ( that is, any element of the cartesian product $N\times N$ ) and sending back as output an element of $N$ (meaning that addition is an operation on $N$):

(1) $n+O=n$ ( $n$ being any natural number)
(2) $n+ S(m) = S (n+m)$ ( $n$ and $m$ being any natural numbers).
Note : the rules mean that, $a+b= a$ if $a = O$ and that $a+b= S(a+ $ predecessor of $b$) if $b\neq 0$.

So for axample:

$3+2 = 3+S(1) = S(3+1) = S (3+S(0))= S S( 3+0) = SS(3) =S(4)= 5$.
( 5 being " the successor of 4" by definition).

As to substraction, onece you have defined the integers ( using an equivalence relation on the set of couples of natural numbers) , you can say that :

$n-m = n+(-m)$.


quebra linha dentro da string

Question: Como inserir quebra de linha em uma string, sem aumentar o número de caracteres?
    <?php

        $str = "Vou para Manaus";
        echo(strlen($str)); //exibe 15

        $str = "Vou para
        Manaus";
        echo(strlen($str)); //exibe 18

    ?>

Comment: Acredito que não seja possivel pois o espaço e contato como caractere, qual e o seu objetivo com isto ?
Comment: @Gabriel, é comum ter esse tipo de regra num modelo de negócio. Exemplo, contar quantos caracteres foram digitados num texto, porém ignorar contagem de espaçamentos, quebras de linha, e pontuações. Num exemplo prático, um serviço de tradução de textos onde o preço da tradução é baseado na quantidade de caracteres. Seria injusto cobrar por espaços e quebras de linha.
Answer: Primeiramente, esteja ciente da diferença entre caracteres e bytes.
A função strlen() retorna quantidade em bytes.
CAso queira contar a quantidade de caracteres, utilize a função mb_strlen()
$str = "Vou para Maranhão";
echo strlen($str); //exibe 18
echo mb_strlen($str); //exibe 17

Vamos ao ponto principal?
contar a quantidade de caracteres ignorando as quebras de linha:
$str = "Vou para
Maranhão";

$l = mb_strlen( str_replace("
",'',$str) );
echo PHP_EOL . $l; //exibe 17

A ideia é simples. Apenas remova os caracteres indesejados antes da contagem.
Brincando um pouco mais, podemos criar uma função:
$str = "Vou para
Maranhão";

/**
No segundo parâmetro, indique os caracteres que dseja ignorar. O argumento recebe `string` ou `array`
*/
function mb_strlen2( $str, $ignore = null )
{
    return mb_strlen( str_replace($ignore,'',$str) );
}

/*
 Ignora quebras de linha
*/
echo PHP_EOL . '
' . mb_strlen2( $str, PHP_EOL );

/*
 Ignora quebras de linha e espaçamentos
*/
echo PHP_EOL . '
' . mb_strlen2( $str, [ PHP_EOL, ' ' ] );

Answer: Tente
    <?php

    $str = "Vou para Manaus";
    echo(strlen($str)); //exibe 15

    $str = "Vou para \n Manaus";
    echo(strlen($str)); //exibe 18

?>

Answer: Já testou assim:
<?php
        $str = "Vou para Manaus";
        echo(strlen($str)); //exibe 15
        $str = "Vou para" . PHP_EOL . "Manaus";
        echo(strlen($str)); //exibe 18
?>

Uma constante PHP de quebra de linha que se ajusta de acordo o sistema operacional.
Answer: tente assim
$str = "Vou para "\n" Manaus";
echo(strlen($str)); //exibe 18

Comment: Você não está concatenando

quebra linha dentro da string


Differential Equation Mass Damped Spring

Question: I have already attempted to find the natural frequency by taking the root of $k/\mu$ where $\mu = 2m$. I then divided that by $2\pi$ to get $6.74\cdot 10^{13}$, not sure how to answer the second question though.

The $\mu$ for the Oxygen molecule (O2) is $1.33\cdot 10^{-26}$kg and $k =1195$N/m. What is the natural frequency of O2?
What will happen to the molecule if it is forced by an external source to vibrate with a
frequency equal to its natural frequency? Explain in detail.
Comment: The question should be left up so others can see it.
Answer: In particular, if $y$ is the distance from the equilibrium position, the equation (in the linear realm) for $y$ if the forcing has the same frequency as the natural frequency is
$$
\frac{d^2y}{dt^2} + \frac{k}{\mu}y -a\cos \left( \sqrt{\frac{k}{\mu}} t\right) = 0
$$
and this is solved (starting at rest at $y=0$ by
$$
y = \frac{a}{2}\sqrt{\frac{\mu}{k}} t \sin  \left( \sqrt{\frac{k}{\mu}} t\right)
$$
so the amplitude of vibration grows linearly with time.
Of course, in a real molecule the restoring force becomes non-linear way before the molecule dissociates, but you can get a good estimate of the time to dissociation by seeing when the energy given by that formula exceeds the molecular binding energy.
Answer: If you force a spring using its natural frequency the amplitude will get larger and larger. Obviously the linear spring model will break down at some point, in particular, the $O_2$ molecule will dissociate into two oxygen atoms.
BY the way, you might want to check your math for part 1.  Did you use the reduced mass $\mu$ or the mass of one oxygen atom?
Comment: Yes we fixed the math for part 1 after realizing that we needed to use the reduced mass  μ. The amplitude getting larger makes sense however I am not sure how to find the exact amplitude. Also can we then conclude that the natural frequency of heavier diatomic molecules is lower than that of the lighter molecule?
Answer: If the molecule is being forced to vibrate at its natural frequency, my guess is that the molecule would break apart. I am not a chemist so I am not entirely certain. I am saying based on what happens to structures that are forced to vibrate at their natural frequency. For instance, take the Tacoma National Bridge which you can watch here on Youtube.
Tacoma Bridge


error java.lang.RuntimeException: Unable to start activity java.lang.NullPointerException

Question: I am having this errors while login in the app when HomeClient.java class is called....I am developing the Taxy calling App and i have used Sliding drawer and Map too....
02-02 14:26:40.378: E/AndroidRuntime(1634): FATAL EXCEPTION: main
02-02 14:26:40.378: E/AndroidRuntime(1634): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fenixcar/com.example.fenixcar.HomeClient}: java.lang.NullPointerException
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.os.Looper.loop(Looper.java:137)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.ActivityThread.main(ActivityThread.java:5041)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at java.lang.reflect.Method.invokeNative(Native Method)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at java.lang.reflect.Method.invoke(Method.java:511)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at dalvik.system.NativeStart.main(Native Method)
02-02 14:26:40.378: E/AndroidRuntime(1634): Caused by: java.lang.NullPointerException
02-02 14:26:40.378: E/AndroidRuntime(1634):     at com.example.fenixcar.HomeFragment.onCreateView(HomeFragment.java:61)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.Fragment.performCreateView(Fragment.java:1695)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.BackStackRecord.run(BackStackRecord.java:682)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.Activity.performStart(Activity.java:5113)
02-02 14:26:40.378: E/AndroidRuntime(1634):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
02-02 14:26:40.378: E/AndroidRuntime(1634):     ... 11 more
02-02 14:26:40.627: W/ActivityManager(293):   Force finishing activity com.example.fenixcar/.HomeClient
02-02 14:26:40.637: W/ActivityManager(293):   Force finishing activity com.example.fenixcar/.Login
02-02 14:26:41.147: W/ActivityManager(293): Activity pause timeout for ActivityRecord{415c5030 u0 com.example.fenixcar/.HomeClient}
02-02 14:26:41.168: I/Choreographer(293): Skipped 127 frames!  The application may be doing too much work on its main thread.
02-02 14:26:41.197: E/SurfaceFlinger(36): ro.sf.lcd_density must be defined as a build property
02-02 14:26:41.378: D/dalvikvm(293): GC_CONCURRENT freed 452K, 62% free 5039K/13004K, paused 143ms+58ms, total 855ms
02-02 14:26:41.438: I/Choreographer(538): Skipped 119 frames!  The application may be doing too much work on its main thread.
02-02 14:26:41.598: E/SurfaceFlinger(36): ro.sf.lcd_density must be defined as a build property
02-02 14:26:41.708: I/Choreographer(538): Skipped 56 frames!  The application may be doing too much work on its main thread.
02-02 14:26:41.948: I/Choreographer(293): Skipped 72 frames!  The application may be doing too much work on its main thread.
02-02 14:26:41.998: I/Choreographer(293): Skipped 107 frames!  The application may be doing too much work on its main thread.
02-02 14:26:52.076: W/ActivityManager(293): Activity destroy timeout for ActivityRecord{40d257a8 u0 com.example.fenixcar/.Login}
02-02 14:26:52.078: W/ActivityManager(293): Activity destroy timeout for ActivityRecord{415c5030 u0 com.example.fenixcar/.HomeClient}
02-02 14:26:56.236: D/ExchangeService(756): Received deviceId from Email app: null
02-02 14:26:56.237: D/ExchangeService(756): !!! deviceId unknown; stopping self and retrying
02-02 14:27:01.318: D/ExchangeService(756): !!! EAS ExchangeService, onCreate
02-02 14:27:01.328: D/ExchangeService(756): !!! EAS ExchangeService, onStartCommand, startingUp = false, running = false
02-02 14:27:01.338: D/ExchangeService(756): !!! EAS ExchangeService, onStartCommand, startingUp = true, running = false
02-02 14:27:01.348: W/ActivityManager(293): Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
02-02 14:27:01.348: D/ExchangeService(756): !!! Email application not found; stopping self
02-02 14:27:01.358: W/ActivityManager(293): Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
02-02 14:27:01.378: E/ActivityThread(756): Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d40878 that was originally bound here
02-02 14:27:01.378: E/ActivityThread(756): android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d40878 that was originally bound here
02-02 14:27:01.378: E/ActivityThread(756):  at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
02-02 14:27:01.378: E/ActivityThread(756):  at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
02-02 14:27:01.378: E/ActivityThread(756):  at android.app.ContextImpl.bindService(ContextImpl.java:1418)
02-02 14:27:01.378: E/ActivityThread(756):  at android.app.ContextImpl.bindService(ContextImpl.java:1407)
02-02 14:27:01.378: E/ActivityThread(756):  at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
02-02 14:27:01.378: E/ActivityThread(756):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
02-02 14:27:01.378: E/ActivityThread(756):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
02-02 14:27:01.378: E/ActivityThread(756):  at com.android.emailcommon.service.AccountServiceProxy.getDeviceId(AccountServiceProxy.java:116)
02-02 14:27:01.378: E/ActivityThread(756):  at com.android.exchange.ExchangeService.getDeviceId(ExchangeService.java:1249)
02-02 14:27:01.378: E/ActivityThread(756):  at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1856)
02-02 14:27:01.378: E/ActivityThread(756):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
02-02 14:27:01.378: E/ActivityThread(756):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
02-02 14:27:01.378: E/ActivityThread(756):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-02 14:27:01.378: E/ActivityThread(756):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-02 14:27:01.378: E/ActivityThread(756):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-02 14:27:01.378: E/ActivityThread(756):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-02 14:27:01.378: E/ActivityThread(756):  at java.lang.Thread.run(Thread.java:856)
02-02 14:27:01.468: E/StrictMode(756): null
02-02 14:27:01.468: E/StrictMode(756): android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d40878 that was originally bound here
02-02 14:27:01.468: E/StrictMode(756):  at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
02-02 14:27:01.468: E/StrictMode(756):  at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
02-02 14:27:01.468: E/StrictMode(756):  at android.app.ContextImpl.bindService(ContextImpl.java:1418)
02-02 14:27:01.468: E/StrictMode(756):  at android.app.ContextImpl.bindService(ContextImpl.java:1407)
02-02 14:27:01.468: E/StrictMode(756):  at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
02-02 14:27:01.468: E/StrictMode(756):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
02-02 14:27:01.468: E/StrictMode(756):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
02-02 14:27:01.468: E/StrictMode(756):  at com.android.emailcommon.service.AccountServiceProxy.getDeviceId(AccountServiceProxy.java:116)
02-02 14:27:01.468: E/StrictMode(756):  at com.android.exchange.ExchangeService.getDeviceId(ExchangeService.java:1249)
02-02 14:27:01.468: E/StrictMode(756):  at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1856)
02-02 14:27:01.468: E/StrictMode(756):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
02-02 14:27:01.468: E/StrictMode(756):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
02-02 14:27:01.468: E/StrictMode(756):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-02 14:27:01.468: E/StrictMode(756):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-02 14:27:01.468: E/StrictMode(756):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-02 14:27:01.468: E/StrictMode(756):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-02 14:27:01.468: E/StrictMode(756):  at java.lang.Thread.run(Thread.java:856)
02-02 14:27:01.478: W/ActivityManager(293): Unbind failed: could not find connection for android.os.BinderProxy@40f905a0
02-02 14:27:01.478: E/ActivityThread(756): Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d404d0 that was originally bound here
02-02 14:27:01.478: E/ActivityThread(756): android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d404d0 that was originally bound here
02-02 14:27:01.478: E/ActivityThread(756):  at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
02-02 14:27:01.478: E/ActivityThread(756):  at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
02-02 14:27:01.478: E/ActivityThread(756):  at android.app.ContextImpl.bindService(ContextImpl.java:1418)
02-02 14:27:01.478: E/ActivityThread(756):  at android.app.ContextImpl.bindService(ContextImpl.java:1407)
02-02 14:27:01.478: E/ActivityThread(756):  at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
02-02 14:27:01.478: E/ActivityThread(756):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
02-02 14:27:01.478: E/ActivityThread(756):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
02-02 14:27:01.478: E/ActivityThread(756):  at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:191)
02-02 14:27:01.478: E/ActivityThread(756):  at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1850)
02-02 14:27:01.478: E/ActivityThread(756):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
02-02 14:27:01.478: E/ActivityThread(756):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
02-02 14:27:01.478: E/ActivityThread(756):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-02 14:27:01.478: E/ActivityThread(756):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-02 14:27:01.478: E/ActivityThread(756):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-02 14:27:01.478: E/ActivityThread(756):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-02 14:27:01.478: E/ActivityThread(756):  at java.lang.Thread.run(Thread.java:856)
02-02 14:27:01.498: E/StrictMode(756): null
02-02 14:27:01.498: E/StrictMode(756): android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d404d0 that was originally bound here
02-02 14:27:01.498: E/StrictMode(756):  at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
02-02 14:27:01.498: E/StrictMode(756):  at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
02-02 14:27:01.498: E/StrictMode(756):  at android.app.ContextImpl.bindService(ContextImpl.java:1418)
02-02 14:27:01.498: E/StrictMode(756):  at android.app.ContextImpl.bindService(ContextImpl.java:1407)
02-02 14:27:01.498: E/StrictMode(756):  at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
02-02 14:27:01.498: E/StrictMode(756):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
02-02 14:27:01.498: E/StrictMode(756):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
02-02 14:27:01.498: E/StrictMode(756):  at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:191)
02-02 14:27:01.498: E/StrictMode(756):  at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1850)
02-02 14:27:01.498: E/StrictMode(756):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
02-02 14:27:01.498: E/StrictMode(756):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
02-02 14:27:01.498: E/StrictMode(756):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-02 14:27:01.498: E/StrictMode(756):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-02 14:27:01.498: E/StrictMode(756):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-02 14:27:01.498: E/StrictMode(756):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-02 14:27:01.498: E/StrictMode(756):  at java.lang.Thread.run(Thread.java:856)

My HomeClient.java file is
import java.util.ArrayList;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;

import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class HomeClient extends Activity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homeclient);

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // What's hot, We  will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));

        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        //getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new HomeFragment();

            break;
        case 1:
            fragment = new FindPeopleFragment();

            break;
        case 2:
            fragment = new PhotosFragment();
            break;
        case 3:
            fragment = new CommunityFragment();
            break;
        case 4:
            fragment = new PagesFragment();
            break;
        case 5:
            fragment = new WhatsHotFragment();
            break;

        default:
            break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

My Xml file attatched to HomeClient.class is here
<android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector"
        android:background="@color/list_background"/>
    </android.support.v4.widget.DrawerLayout>

My HomeFragment is
package com.example.fenixcar;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class HomeFragment extends Fragment{
    GoogleMap mMap;
    Fragment f;
    TextView t;
    String address,country,postalcode,city;
    public HomeFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

            //Toast.makeText(getApplicationContext(), "Cant connect to google play service", 10).show();

        GPSTRacker gps = new GPSTRacker(getActivity());

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        t = (TextView)rootView.findViewById(R.id.text);

        MapFragment m = (MapFragment)getActivity().getFragmentManager().findFragmentById(R.id.fragment1);
        mMap = m.getMap();
        if (gps.canGetLocation()){
            double lati = gps.latitude;
            double longi = gps.longitude;
            address=gps.getAddressLine(getActivity());
            country=gps.getCountryName(getActivity());
            postalcode=gps.getPostalCode(getActivity());
            city=gps.getLocality(getActivity());
            MarkerOptions marker = new MarkerOptions().position(new LatLng(lati, longi)).title("You Are Here!/n"+address+" "+city+" "+postalcode+" "+country);
            CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(lati, longi)).zoom(6).build();

            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

         // adding marker
            mMap.addMarker(marker);

            t.setText(" "+address+" "+city+" "+country);

            /*city=gps.locality;
            country=gps.countryName;
            postalcode=gps.postalCode;

            ed.setText(""+address+" "+city+" "+postalcode+" "+country);*/

        }
        else{
            gps.showSettingsAlert();
        }

        return rootView;
    }

    @Override
    public void onDestroyView()
    {
        try{
          MapFragment fragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fragment1);
          FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
          ft.remove(fragment);
          ft.commit();
        }catch(Exception e){
        }
      super.onDestroyView();
  }

}

Comment: Stacktrace clearly points to exact line of your code: `HomeFragment.onCreateView(HomeFragment.java:61` - what is your problem to check and fix yourself?
Comment: paste code for HomeFragment
Comment: Please show the code of HomeFragment as that is where the error originates from.
Comment: i am posting HomeFragment please check
Answer: You have a NullPointerException at line 61 of your java (you can check you code) within your onCreateView.
Caused by: java.lang.NullPointerException
02-02 14:26:40.378: E/AndroidRuntime(1634):
at com.example.fenixcar.HomeFragment.onCreateView(HomeFragment.java:61)

I suspect here:
mTitle = mDrawerTitle = getTitle();

I also suspect you check your getActionBar, if you test with an if, it will tell you:
say:
if(getActionBar()!=null) {
    getActionBar().setDisplayHomeAsUpEnabled(true);
}
else{
    Toast.makeText(this, "NO ACTIONBAR!!!!!!!!!!!!!!!!!!", Toast.LENGTH_SHORT).show();
}

Comment: Why all the extra code?  Just put a breakpoint on that line and debug.  This is a lousy way to debug.


The 2nd card is red - intuitive understanding of probability

Question: I have trouble understanding intuitively this problem (taken from the book by Blitzstein and Hwang):
A standard deck is shuffled and 2 cards are dealt.
Event $B$ - the 2nd card is red.
It turns out that $P(B)=0.5$ and algebraicly I understand why it is so (that's why I omit the calculation here).
Here's the quote from the book I struggle to understand: "There are 26 favorable possibilities for the second [italicized by the authors of the book] card, and for each of those the first card can be any other card."
How can we say that there are 26 favorable possibilities for the second card? Suppose we know nothing about the first card. If I wanted to find $P(B)$, I would apply the LOTP and considered two events: the first card is red and the first card is black. Which means that we can say that there are 26 favorable possibilities for the second card only if the first card is black.
What does the book mean?
Comment: is there any given reason as to why there is an event B but not an event A?
Comment: In this context (calculating $P(B)$) I see no reason to even mind about the first card. There are just exactly $26$ red cards that can turn out to be the second card with equal probability. Yes, the first card will not be the second card, but that is also true for the cards that are not dealt at all.
Comment: P(B|A) doesn't make sense, as if A happens, it happens before B
Comment: @Cursed1701 Sure it makes sense. There is no essential difference between placing 2 cards one by one or simultaniously followed by giving them the labels 1 and 2.
Comment: @Cursed1701 Yes, event A - the first card is a heart. I got the title of the question wrong (( The problem deals with computing $P(A|B)$ and $P(B|A)$ and I seem to understand everything but the phrase that I asked about in the question, that's why I didn't copy the entire problem.
Comment: @drhab >>I see no reason to even mind about the first card
The reason is because B is the second card and we do not replace the first card after we have drawn it.
Comment: @alekscooper So what? You might as well touch a card blindly and whisper: "you are the first card" and then place one of the other cards. The probability that the placed card is red will not be affected by that.
Answer: You seem to intuitively accept that the first card of a shuffled deck has $0.5$ chance to be red, regardless of any worry about what the second card is.  Consider shuffling a deck then swapping the first and second cards.  Doesn't the chance that the second card is red have to be $0.5$ if we don't worry about the first card?  You are worried that if we know the first card is red it decreases the probability that the second card is red, which is true.  If we know the first card is black it raises the probability that the second card is red.  The calculation, which you accept, shows these balance out nicely.
Comment: Another way to say the same thing is to ask yourself: Which of the 52 cards is more or less likely to end up as the second card? Answer: none, all are equally likely to end up as the second card. So, 26/52.
Comment: Cool explanation, thank you! I wonder why they don't write books in that way...


A nifty way of finding starting location for all occurances of a sub string or a Regexp in Ruby

Question: Let us say that I have this string:
bar="hello kohello hello"

I would like a function foo that I give it
foo(bar,"hello")

And get:
[0,8,14]

Now, I could just do (1 of many options):
def foo(str1,substr)
  i= -1
  substr_length = substr.length()
  str1.chars.map{ | char |
    i+=1
    str1(i,substr_length) == substr ? i : nil
  }.select{ |x| x }
end

Is there something more "Ruby like"? Also with Regexp, rather than strings.
Thanks.
Answer: In irb
arr = []
bar.scan("hello"){arr.push($~.offset(0)[0])}

now check arr
[0,8,14]
Adding my consoles' code for clarity
1.9.3-p362 :008 > arr = []
 => []
1.9.3-p362 :009 > bar.scan("hello"){arr.push($~.offset(0)[0])}
 => "hello kohello hello"
1.9.3-p362 :010 > arr
 => [0, 8, 14]

for those who dont know this cryptic ruby global variable.
$~ contains the MatchData from the previous successful pattern match.
so it is similar to Regexp.last_match
for finding the index, we can find the Regexp.last_match.offset(0)[0]
Comment: Though what? What is the gotacha?
Comment: that was just left from the last edit ..sorry'
Comment: @user1134991 is the solution working for you ?
Comment: @user1134991 ah dont forget to upvote, help me complete my 1k ;)
Comment: It is working. Very well.


Como criar um webhook no Gitlab para atualizar um repositório espelho no Github?

Question: Eu gostaria de criar um webhook no Gitlab para atualizar um repositório espelho no Github sempre que houver um push. Eu consultei esta página de demonstração, mas não entendi muito bem como fazer.
Minha versão do Gitlab é a 6.5. Aqui está a página de configuração:

Em URL, devo colocar o repositório GitHub que gostaria de atualizar? Ou seria o arquivo JSON com as modificações geradas pelo push? Está bem difícil encontrar uma documentação sobre como fazer.
Comment: Por que os downvotes?
Answer: Entendendo Web Hooks
Web Hook é um método de receber notificações de eventos ocorridos em aplicações web. Quando algo acontece numa aplicação que suporta Web Hooks, ela faz uma requisição para a URL configurada enviando detalhes do que ocorreu.
Essa técnica permite realizar integrações da aplicação com outras ou até estender as funcionalidades da mesma de forma totalmente desacoplada, sem que seja necessário modificar a aplicação, injetar algum tipo de código ou script, etc.
Portanto, isso não vai enviar o repositório diretamente para o GitHub ou qualquer outro site. Cabe a você deve construir uma aplicação que escute aos eventos e tome a ação desejada, no caso, clonar o repositório.
Verificando qual evento usar
A documentação atual mostra quais são os eventos gerados e que conteúdo a URL configurada receberá.
Por exemplo, o primeiro caso é quando alguém atualiza o repositório fazendo um push. A URL configurada vai receber uma requisição HTTP com o cabeçalho (header) X-Gitlab-Event com valor Push Hook. O corpo da requisição conterá detalhes sobre as alterações, como o usuário que fez o push e quais commits foram enviados.
Implementando sua aplicação
Ao final da documentação há um exemplo de como implementar uma aplicação que escuta aos eventos. Você deve fazer algo parecido.
Pode ser em qualquer linguagem com qualquer framework, mas você será responsável pelo sistema que escuta os eventos na URL especificada.
Ao receber uma requisição originada por um evento push, sua aplicação deve então clonar o repositório de origem (GitLab) e  fazer o push no de destino (GitHub).


why T-alg is terminal in T-adj

Question: In the following $(\mathscr D,T, \eta,\mu)$ is a monad

QUESTION:  Why is K unique?
Let $K'$ be another such. Since $G^T$ is faithful it suffices to prove $K=K'$ on objects.  But $G^T$ isn't injective on objects and F isn't surjective on objects…
Answer: Suppose $K$ has this property, and fix $c$ an object of $\mathcal{C}$.  Then the underlying object of $K c$ is $G^T(K c) = G(c)$.  Moreover, if we let $\varepsilon$ be the counit of the adjunction between $F$ and $G$, then we know that $K(\varepsilon_c)$ is a morphism of $T$-algebras.  However, the domain of $K(\varepsilon_c)$ is $K(FG(c)) = F^T(Gc) = (T(Gc), \mu_{Gc})$; and the comain is $K(c)$.  I will leave it as an exercise to show that more generally, if $\beta : (TX, \mu_X) \to (X, \alpha)$ is a morphism of $T$-algebras, and if $\beta \circ \eta_X = \operatorname{id}_X$, then $\alpha = \beta$.  In our case, we have $G^T (K \varepsilon_c) \circ \eta = G \varepsilon_c \circ \eta = \operatorname{id}$ since by assumption, the unit of the adjunction between $F$ and $G$ gives rise to the unit of the monad $T$.  Thus, we conclude that $Kc$ as a $T$-algebra must be equal to $(Gc, G^T(K \varepsilon_c)) = (Gc, G \varepsilon_c)$.  Since, as you observed, $G^T$ is faithful, this suffices to show that $K$ is uniquely determined.
Comment: thanks! you'd think the textbook would at least say "(exercise)"!
Answer: $G^TK=G$ tells you that $K$ should take an object $c$ to a $T-$algebra structure on $Gc$.
The second fact is that the $T$ algebra structure ($Td\to d $) on an object of $T-Alg$ is given by the (bottom arrow in the commuting square )of the component of the counit of the adjunction between $D,D^T$(this is just checking the definitions ).
The third fact is that $K$ commutes with the counits of the adjunctions owing to the fact they induce the same monad on $D$(this is a diagram chase).
For the above reasons the action of $K$ on objects is forced. (Note that,the action on morphisms is straightforward, you need that as well($G^TK=G$)).

why T-alg is terminal in T-adj