Integrating $\frac{\mathrm d}{\mathrm dx}f(x)$ from $0$ to $t$

Question: I need help for solving the integral $$\int_0^t\left(\frac{\mathrm d}{\mathrm dx}f(x)\right)\mathrm dx.$$ I think that the indefinite integral $$\int\left(\frac{\mathrm d}{\mathrm dx}f(x)\right)\mathrm dx$$ will be equal to $f(x) + C$. Then, when I apply the boundaries to that result, I should get $$\int_0^t\left(\frac{\mathrm d}{\mathrm dx}f(x)\right)\mathrm dx = (f(t) + C) - (f(0) + C) = f(t) -f(0).$$ But I have some doubts if the indefinite integral I found is correct or not. Can you verify my result?
Comment: If $f'(t)$ exists and is continuous on $[0,t]$, then your answer is correct.  It is possible that $f'(t)$ exists on $[0,t]$ but is not integrable (Riemann or Lebesgue senses).
Comment: if you doubt your indefinite integral, can't you check it by differentiating?
Comment: Also, are you assuming that $f$ is suitably differentiable over $[0,t]$?
Comment: My function here was actually $f(x)=ln(g(x))$ for a function $g$ that is differentiable over $[0,t]$. So I think $f$ itself will also be differentiable.
Comment: I think your short proof is essentially correct. You must be careful that you only apply this result to functions with derivatives and antiderivatives defined from $0$ to $t$.  As given by @Randall , test our your result on a few well-known functions
Comment: The reason of my doubt was that I have seen $\frac{d}{dx}$ in an integral for the first time, and wasn't sure if it was supposed to be handled another way. Thanks.
Comment: @zzlawlzz  if $g(x)$ is ever $0$, differentiability will be a problem.
Comment: I think my $g$ will become $0$ as $x$ goes to infinity, so there shouldn't be a problem there too. Thanks again.
Answer: For constant $C$,
$$\frac{\mathrm d}{\mathrm dx}(\color{red}{f(x)+C}) = \color{blue}{\frac{\mathrm d}{\mathrm dx}f(x)}$$
So,
$$\int_a^b\color{blue}{\frac{\mathrm d}{\mathrm dx}f(x)}\,\mathrm dx = (\color{red}{f(x)+C})|_{x=a}^{x=b}=f(b)-f(a)$$
For $f(x)$ differentiable $\forall x \in [a,b]$. So yes, you are correct. In your case, $a=0$.


Spark Count Streak of Column Value

Question: I have a df
id, date, item

1, 20180101, A
1, 20180102, A
1, 20180103, B
1, 20180104, A
2, 20180101, C
2, 20180102, D
2, 20180103, D
2, 20180104, D

and I would like to create a new column streak which contains the number of item streak each user has
id, date, item, streak

1, 20180101, A, 1
1, 20180102, A, 2
1, 20180103, B, 1
1, 20180104, A, 1
2, 20180101, C, 1
2, 20180102, D, 1
2, 20180103, D, 2
2, 20180103, D, 3

I can use the window function row_number and partition by the id and item to cumulatively count the id-item pair but this will not restart the streak of the count after there is a new item.
Answer: Do my best solution is this.
import org.apache.spark.sql.expressions.Window

val w1 = Window.partitionBy("id", "item").orderBy("date")
val w2 = Window.partitionBy("id", "item", "index").orderBy("date")
df.withColumn("lag_date", lag("date", 1, "").over(w1))
  .withColumn("jump", not(col("lag_date") === lit("") || date_add(to_date(col("lag_date"), "yyyyMMdd"), 1) === to_date(col("date"), "yyyyMMdd")).cast("int"))
  .withColumn("index", sum("jump").over(w1))
  .withColumn("streak", row_number.over(w2))
  .orderBy("id", "date")
  .show(false)

The jump column is used to calculate the index where the index means that the index of streak. For example, id = 1 and item = A, there should be 2 indices. The index 0 and 1 indicate the first streak from date = 20180101 to 20180102 and the second streak from date = 20180104, respectively. If there is a record with date = 20180105, it will also have the index = 1 and continued to the streak = 2.
The result is:
+---+--------+----+--------+----+-----+------+
|id |date    |item|lag_date|jump|index|streak|
+---+--------+----+--------+----+-----+------+
|1  |20180101|A   |        |0   |0    |1     |
|1  |20180102|A   |20180101|0   |0    |2     |
|1  |20180103|B   |        |0   |0    |1     |
|1  |20180104|A   |20180102|1   |1    |1     |
|2  |20180101|C   |        |0   |0    |1     |
|2  |20180102|D   |        |0   |0    |1     |
|2  |20180103|D   |20180102|0   |0    |2     |
|2  |20180104|D   |20180103|0   |0    |3     |
+---+--------+----+--------+----+-----+------+

where I haven't deleted the temp columns to show how this code works.
Comment: Great! Works fine.
Comment: you convert it into pysark please? @Lamanus

Spark Count Streak of Column Value


Pegar valor de uma campo na view em uma controller

Question: Pelas respostas aqui, não consegui pegar. Tenho essa view
    @{
    ViewBag.Title = "ExcelFinancing";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title></title>

@ViewBag.TitlePage

    @*
*@

            @Html.Label("De")

            @Html.EditorFor(model => model.datefinancing, new { htmlAttributes = new { @class = "form-control", ID = "dataIni" } })
            @Html.ValidationMessageFor(model => model.datefinancing, "", new { @class = "text-danger" })

            @Html.Label("Até")

            @Html.EditorFor(model => model.datefinancing, new { htmlAttributes = new { @class = "form-control", ID = "dataFim" } })
            @Html.ValidationMessageFor(model => model.datefinancing, "", new { @class = "text-danger" })

                    @{string Todos = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("Todos");}
                    @Html.RadioButtonFor(model => model.statussolicitation, "Todos", new { id = Todos, name = "imp_tx_tipo", value = "Todos", @class = "with-gap" })
                    Todos

                    @{string Ativos = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("Ativos");}
                    @Html.RadioButtonFor(model => model.statussolicitation, "Ativos", new { id = Ativos, name = "imp_tx_tipo", value = "Ativos", @class = "with-gap" })
                    Ativos

                    @{string Inativos = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("Inativos");}
                    @Html.RadioButtonFor(model => model.statussolicitation, "Inativos", new { id = Inativos, name = "imp_tx_tipo", value = "Ativos", @class = "with-gap" })
                    Inativos

                @Html.ValidationMessageFor(model => model.statussolicitation, "", new { @class = "red-text text-darken-2" })

        @using (Html.BeginForm("geraExcel1", "FinancingReport", FormMethod.Post))
        {

                    <input type="submit" value="Gerar Relatório" class="btn btn-primary" />

        }

Essa é minha controller
[HttpPost]
    public ActionResult geraExcel1()
    {
        var context = new SyngentaBenefitsEntities();
        var model = new SolicitationViewModel();

        //var teste = dataFim;

        geraExcel();
        ViewBag.TitlePage = "Relatório de Financiamento";
        return null;
    }

    [HttpPost]
    public ActionResult geraExcel()
    {
        List<vwFinancingReportViewModel> lista = new List<vwFinancingReportViewModel>();
        lista = dadosPlanilha();

        StringBuilder sb = new StringBuilder();
        sb.Append("Status;Nro.Pessoal;Nome Completo;Grade;Nro.Solicitação;Data Financiamento;" +
            "Ano Fabric.;Modelo;Chassi;Valor Bem;Valor Financiado;Status Solicitação;Status Pagamento;" +
            "Valor Parcela;Juros;ReembolsoKM;Reembolso Depreciação\r\n");
        foreach(var item in lista)
        {
            sb.Append(item.employeestatus.ToString() + ";" + item.employeeid.ToString() + ";" + item.fullname.ToString() + ";" +
                      item.grade.ToString() + ";" + item.solicitationid.ToString() + ";" + item.datefinancing.ToString() + ";" +
                      item.manufacturer.ToString() + ";" + item.model.ToString() + ";" + item.chassi.ToString() + ";" +
                      item.valueproperty.ToString() + ";" + item.valuegranted.ToString() + ";" + item.statussolicitation.ToString() + ";" +
                      item.paymentstatus.ToString() + ";" + item.valuepayment.ToString() + ";" +
                      item.valueinterest.ToString() + ";" + item.refundkm.ToString() + ";" +
                      item.refund.ToString() + "\r\n");

        }
        //sb.Append("Eduardo;11111\r\n");
        //sb.Append("Coutinho;22222\r\n");

        HttpContext.Response.Clear();
        HttpContext.Response.AddHeader("content-disposition", string.Format("attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + "ReportFinanciamentoRH.csv"));

        HttpContext.Response.ContentType = "application/CSV";
        HttpContext.Response.ContentEncoding = System.Text.Encoding.Default;

        HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        HttpContext.Response.Write(sb.ToString());

        HttpContext.Response.End();

        return null;
    }

Na view eu tenho um campo DateTime, onde seria um filtro para meu sql, que seria DataInicio e DataFim. Acontece que eu não estou sabendo enviar para a controller esses valores, para que eu possa usá-los na minha query.
Comment: você pode passar o valor pelow ViewBag.NomeDavariavel ou  Pelo Model
Comment: @MarcosBrinner, mas da View para a Controller usando ViewBag? Achei quye só o contrário era possível. Eu tenho um formulário e preciso pegar o valor dele no meu controller
Comment: A sim agora compreendi sua pergunta então, você está usando  POST ou GET para enviar os dados ?:
Comment: Pode passar pela Model quando postar, ou via ajax...
Comment: Só uma dúvida, só preciso dos valores de duas datas para alimentar um método(parametros). Tenho que submeter o formulário? Sei que é básico, mas tenho essa dúvida.
Comment: sim, se  esses valores estiverem vindo do cliente-side você precisa envialos de alguma forma para o servidor, você também pode passar pela url ao que carrega a view
Comment: tipo site.com/controller/action?DataFim=18/06/2069
Comment: Ok, minha action é HttpPost e o botão submit se encarrega de enviar o form. Mas como eu faço agora, tipo, **var teste = ?????** como carrego a var teste? Essa é a dúvida. Dessa forma não vai: **var teste = dataFim.Value;** apenas um exemplo hipotético.
Comment: @MarcosBrinner, como eu passo pela url esses valores ao carregar a view?
Comment: A pergunta não está clara, por favor, dê uma pesquisada melhor sobre o assunto e formate melhor sua dúvida (exemplo: adicione a View para entendermos melhor como está sendo feito o post da página, atualize o código com o HttpPost na Action, etc...) para que possamos ajudá-lo.
Comment: Já tentou colocar tudo dentro de "@using(Html" e passar por parâmetro seu model no método post?
Comment: @LucasRiechelmannRamos, não tentei fazer isso, para dizer a verdade, nem pensei nisso.
Comment: Em nenhuma das actions você está esperando algum valor?
Comment: @LucasRiechelmannRamos, você tinha razão. Renan, valeu pelo "puxão de orelha". Se o Lucas responder, eu marco a resposta.
Comment: @pnet então atualize o código da pergunta para fazer sentido com a resposta
Answer: Coloca todo o seu form dentro de
@using (Html.BeginForm("geraExcel1", "FinancingReport", FormMethod.Post))

e utiliza o model para passar como parâmetro no método post
public ActionResult geraExcel1(Model model)
{
    ....
}


maximising margin in svm

Question: I have been thinking of this case as i was reading other questions and answers about SVM.
A question was raised about an SVM model having 1000 data points and 800 support vectors. The OP used a linear kernel. However, this is something that confuses me. If an SVM is supposed to maximise the margin between the 2 classes. How would the increase in number of support vectors feature in this calculations?
How to ensure that all the vectors are maximimum margin from each other?
Answer: I would suggest you to look at SVM from another point of view: It is minimizing hinge loss with L2 regularization. This interpretation works better than maximize the margin interpretation when data is not linearly separable.
Increasing the regularization will increase number of the support vectors.
<code>library(kernlab)
library(mlbench)
set.seed(0)
d=mlbench.2dnormals(100)
svp1 <- ksvm(d$x,d$classes,type="C-svc",kernel="polydot",C=0.1)
plot(svp1,data=d$x)
svp2 <- ksvm(d$x,d$classes,type="C-svc",kernel="polydot",C=10000)
plot(svp2,data=d$x)
</code>

In above simulation we are changing the regularization parameter $C$ to have different numbers of support vectors (shown in black in the plot) in a toy data set.
Comment: minimizing the hinge loss would require as many data points as needed? Can i have a more detailed explaination
Comment: @aceminer would the example help? [libsvm paper](http://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf) section 2.1 will give you math details.
Comment: So just to confirm is this in high dimensional data? Or data in 2d. Not too good with r
Comment: @aceminer 2D data. 2 classes, ground truth label are circle and triangle.

maximising margin in svm


DOS attack always from a same Domain - Mitigation

Question: I frequently get dos attacked on UDP with length 0 from
p885068-ipngn200609sizuokaden.shizuoka.ocn.ne.jp.51422
I have tried resolving this host to an ip 188.8.131.52 and added the address to iptables to drop it,but iptables doesn't seem to drop it.
Any help? so that i can block this host ,also the length shown is UDP, length 0 ,is there any way to drop such 0 length udp packets
Here are the rules
1        0     0 ACCEPT     all  --  *      *       220.127.116.11        0.0.0.0/0
2     199K   32M ACCEPT     all  --  *      *       220.127.116.11/16       0.0.0.0/0
3        0     0 DROP       all  --  *      *       220.127.116.11        0.0.0.0/0
4        0     0 DROP       all  --  *      *       188.8.131.52       0.0.0.0/0
5        0     0 DROP       all  --  *      *       126.96.36.199/24           0.0.0.0/0
6        0     0 DROP       all  --  *      *       22.214.171.124/24        0.0.0.0/0
7        0     0 DROP       all  --  *      *       184.108.40.206/16       0.0.0.0/0

Comment: Could you post the full output from your iptables?  It's possible you have another rule which is matching before these ones.  Plus it would be useful to know your default policy.
Answer:
Use the iptables-save -c command to list the full rule set.
Order of rules is very important. It means the first matched rule wins.
To check packets by packet length you can use rule like this, where statement 0:28 will match packets with length from 0 to 28 bytes inclusively (20 bytes of IPv4 header + 8 bytes of UDP header).

iptables -A INPUT -p udp -m length --length 0:28 -j DROP

The length match checks the total length field in the IPv4 header, not IPv4 packet payload length.
To match by huge list of addresses better use the ipset. It works faster than list of rules.
The tcpdump captures a traffic before processing in the firewall. It means you will see the packets those will be blocked by rules.
Comment: I already have this rule as 1st rule iptables -A INPUT -p udp -m length --length 0:48-j DROP,stil my system is responding to attack
Comment: Check the rule counter. Is this rule matched against packets? Check the traffic with tcpdump, paste lines with these evil packets into the question (`tcpdump -ni  'udp and ip host X.X.X.X'`).
Answer: If iptables doesn't work, you need to use directly a blackhole route with "ip" command.
For example :
ip route add blackhole 22.214.171.124/32

The only thing is you can't see if you detect this ip is going to enter or not. (But, you pretty sure that this IP can't communicate anymore)
Comment: Cool, il try that


Multiple events in Cox PH with time varying data

Question: I study coups d'etat. I would like to understand the relationship between leader/country characteristics and the likelihood of coup attempts.
I have a leader-country-year dataset with one entry for every year that a given leader in a given country was in power. I also have data on leader and country characteristics. Some of these variables do not vary over time (e.g., was the leader elected) and some do (e.g., whether the country is at war with another country). I've made a mock dataset below to illustrate what my data look like.

leader_id
country_id
years_since_entering
elected
war
coup_attempt

1
1
0
1
0
0

1
1
1
1
1
0

1
1
2
1
1
1

1
1
3
1
1
0

1
1
4
1
1
0

1
1
5
1
1
1

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

2
1
0
0
1
0

2
1
1
0
1
0

2
1
2
0
0
0

2
1
3
0
0
0

I would like to use a Cox PH model to understand the effect that these variables have on a leader's survival time until a coup attempt is made. So, the Cox PH "event" is coup_attempt. The covariates are elected and war.
Some details I want to note:

There can be multiple coup attempts in one leader's tenure. (leader_id == 1 in the mock dataset experiences two coup attempts)
The same country can have multiple leaders, though they are never in the leadership position at the same time. (country_id == 1 in the mock dataset has two leaders)

I'm planning to use the survival package in R and run a model like this:
library(survival)
fit <- coxph(Surv(start, stop, coup_attempt) ~ elected + war +
 strata(country_id) + cluster(country_id), data = df)

Some questions I have: (I will explain the strata and cluster choices in the second question)

I know that I need to reshape my data to have start and stop intervals to use with the coxph function.  Can I make all of the start and stop intervals in my coxph dataset the same length? Specifically, can I make them one year intervals so that they capture all of the changes in the war variable? The dataset would look like this:

leader_id
country_id
years_since_entering
elected
war
coup_attempt
start
stop

1
1
0
1
0
0
0
1

1
1
1
1
1
0
1
2

1
1
2
1
1
1
2
3

1
1
3
1
1
0
3
4

1
1
4
1
1
0
4
5

1
1
5
1
1
1
5
6

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

2
1
0
0
1
0
0
1

2
1
1
0
1
0
1
2

2
1
2
0
0
0
2
3

2
1
3
0
0
0
3
4

I included strata(country_id) + cluster(country_id) in the coxph function to account for the correlation between leaders of the same country. There might be a country specific effect (e.g., Iraq has a higher baseline likelihood of coups than Canada), which I aim to capture with strata(country_id). There may also be correlation in the observations of leaders of the same country (e.g., leaders from Iraq are correlated), which I aim to capture with the cluster(country_id). Does this use of strata and cluster make sense? Or would you recommend another way to address these issues?
A leader can experience multiple coup attempts. How do I account for the fact that a single unit can have multiple "events" in the Cox PH?
What, if anything, should I do about data censoring? My data end in 2019, but that doesn't mean that all leaders leave office or stop experiencing coup attempts in 2019.

Any help with any of these questions would be very much appreciated. Thank you in advance!
Comment: This person-period data set that might be evaluated directly with binomial regression, in a discrete-time survival model. That's particularly the case as you seem already to have time bins of 1 year widths. A complementary log-log link instead of the usual logistic link results in a grouped proportional hazards model; see [this page](https://stats.stackexchange.com/q/429266/28500). You could handle correlations with random effects in the binomial model. Censoring is handled as it would be in a Cox model: an individual is omitted from analysis when no longer known to be at risk.
Comment: Thanks, @EdM! This is really helpful. One question -- how is a discrete-time survival model different from running a logit with coup_attempt as the DV and years_since_entering as an independent variable? Or are they the same? I have actually tried running this logit to predict the probability of a coup attempt in a given year (controlling for a leader's time since entering office), but I was worried that I wasn't capturing the "time until coup attempt" hazard element that I cared about.
Answer: A discrete-time survival model with a single event type (even if repeated) can be modeled as a binomial regression with data as you seem to have already, in a person-period format. That is, you have one row of data for each individual at risk during each time period, with each row indicating the corresponding individual, the time period, the covariate values in effect during the period, and an indicator of whether or not the event happened during that period. In that format, there simply are no data values for an individual after the last observation, handling censoring as in other survival models and posing no problems so long as censoring in uninformative.
Capturing the relationship between years_since_entering and outcome is a matter of how you choose to model that predictor. If there are only a few values of years_since_entering covering all cases, you might treat that as a multi-level categorical predictor and get a separate coefficient for each year. That's analogous to what you would get with a Cox model, in which the baseline hazard over time is zero between event times and can take arbitrary positive values at each event time.
If you have many values of years_since_entering and wish to model it as a numeric predictor, you should use a flexible modeling strategy like a regression spline. If you just include it as a numeric predictor the usual way you are imposing, in a logistic regression model, a strictly linear association between that variable and the log-odds of outcome. That's not likely to hold.
There might be some advantage to using a complementary log-log link in your binomial regression instead of the usual logistic link, as that directly represents what you would get in a proportional-hazards model with times grouped like this.
You can then incorporate the intra-individual and intra-country considerations as random effects, in principle including things like random "slopes" for covariates if there are enough data (probably only on an among-country rather than an among-individual level).
If there was at most one event possible per individual you wouldn't have to include random effects per individual, but in your situation that would be important, presumably as a random intercept. For an individual with more than 1 coup attempt, you also need to think about whether and how to incorporate the prior coup attempt into the model; otherwise, you assume independence among coup attempts on the same individual, which seems unlikely.


Loading a ctools modal on the home page

Question: I have a front page that consists mostly of context rules to load various blocks, and for some users, a requirement to render a Ctools modal with a call to action. We aren't displaying much on the homepage besides a few views, and static blocks. I'm using this guide to build out the actual modal (which itself, will display a view with Contextual rules based on the user's settings) to show content tailored to them. Is there any in-code hooks I can use to activate this modal only on the home page, or should I look into the option of using a custom developed block (using hook_block_info() and hook_block_view()) to activate the modal on that page?
Answer: Using ctools modal framework instead of those [insert-fancy-word-here]box JS library. Kudos.
Ctools module uses js/modal.js inside ctools module folder to attach Drupal Ajax events to links with ctools-use-modal class. That is all.
I can think about a few approaches.
1. Do not make them modal-enabled in first place.
If you are calling the ctools_modal_text_button() or the function that adds modal-compatible markup, you can wrap it with an if statement.
<?php
if (drupal_is_front_page()) {
  print ctools_modal_text_button(t('Open the modal'), 'my/path/nojs', '');
}
else {
  print l(t('Open the modal'), 'my/path/nojs');
}
?>

If you are using a block, cache modes DRUPAL_CACHE_PER_ROLE and DRUPAL_CACHE_GLOBAL won't be compatible with this. DRUPAL_CACHE_PER_PAGE would work, but I doubt caching this block would improve performance. It can rather have a negative effect. DRUPAL_NO_CACHE would be best.
If you are hardcoding block contents, you can create two blocks, with different visibility settings based on the path.
2. Change the JS or CSS.
If you can't change the PHP, you still can change the JS and/or CSS.
A CSS solution would be the easiest. Print both modal and non-modal links, and if the body tag has not-front class, you can hide the modal links.
.not-front .ctools-use-modal {
  display: none;
}

You can un-ajax links as well.
Here is a sample code:
(function($){

    Drupal.behaviors.zzzzzz = {
        attach: function (context) {
           $('.not-front area.ctools-use-modal, .not-front a.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);
        // Create a drupal ajax object
        var element_settings = {};
        if ($this.attr('href')) {
          var base = $this.attr('href');
          Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
          delete Drupal.ajax[base]
        }
      });
    }}
})(jQuery);

There are other questions about Drupal behaviors and using jQuery with Drupal 7. Basically, above code finds modal links from non-front pages, and removes the Ajax properties defined in Drupal.ajax, so clicking the item does not trigger the modal.

Loading a ctools modal on the home page


Accessing Variable in Loop

Question: I'm writing a simple python program using a double loop to print out an html page with a unique set of coordinates. I'm getting an error because it cannot recognize the variable where I have (across + node_counter) in the loop. How do I do this so it gets the variable declared at the top?
game_counter = 0

across0 = '72,70,97,70,97,61,116,71,97,83,97,75,72,75'
across1 = '143,70,168,70,168,61,187,71,168,83,168,75,143,75'
across2 = '212,70,237,70,237,61,256,71,237,83,237,75,212,75'
across3 = '283, 70, 308, 70, 309, 61, 327, 71, 308, 83, 308, 75, 283, 75'

while game_counter <60:
    text_file.write("\n\n")
    node_counter = 0

    while node_counter < 15:
        placeholder_string = ""
        placeholder_string += '<area shape="poly" coords = "' + (across + node_counter) + '" href="#"/>\n'
        text_file.write(placeholder_string)
        node_counter += 1
        if node_counter == 15:
            game_counter += 1

Comment: What's `across` supposed to be in `across + node_counter`? You never defined a variable named `across`.
Comment: You don't need to put a `continue` at the end of a loop to make it go on to the next iteration. That's implicit in the loop itself.
Comment: That's what I'm confused about - I'm trying to access the across0, across1, etc. declared up top.
Comment: Can you give us an example of what `across + node_counter` could be?
Comment: What i mean is, which one do you need? In what order?
Comment: When `node_counter` is 3, are you trying to access `across3`? If so, two things. First, use a list of `across` values instead of numbered variables. Second, declare more than 4 across values for a loop that needs 15 of them.
Answer: It looks like you're trying to iterate over your "across" variables. Maybe you mean something like this instead: across = ['72...', '143...']. Then you can iterate over across with a for loop:
for a in across:
    print(a)

I'm using print as an example for what the for loop would look like. Also, if you're using python 2, you would use print a instead of print(a).
Answer: I think you mean to add across0, across1, across2, and across3, not just plain across
Also, you don't need those continue statements.
Answer: You are trying to add variable across to node_counter, but you've only defined variables across0, across1, ...  That's why you're getting the error.
There are a few other errors too

store the across values in an array of arrays
change 60 in the outer loop to 4 (better would be length of across)
changing the inner loop to use the array length is also wise
change across to be indexed using the game_counter on your trouble line.
the if line will never be executed, so you'll get stuck in an infinite loop.  Move the game_counter increment outside the inner loop.

This gives the following code
across = [[72,70,97,70,97,61,116,71,97,83,97,75,72,75],
    [143,70,168,70,168,61,187,71,168,83,168,75,143,75],
    [212,70,237,70,237,61,256,71,237,83,237,75,212,75],
    [283, 70, 308, 70, 309, 61, 327, 71, 308, 83, 308, 75, 283, 75]]

while game_counter < len(across):
    text_file.write("\n\n")
    node_counter = 0

    while node_counter < len(across[game_counter]):
        placeholder_string = ""
        placeholder_string += '<area shape="poly" coords = "' + (across[game_counter][node_counter] + node_counter) + '" href="#"/>\n'
        text_file.write(placeholder_string)
        node_counter += 1

    game_counter += 1

But you'd probably be better off with for loops, at least for the inner loop:
for item in across[game_counter]:
    ...
    ... (item + node_counter) ...

Comment: Yup - how is it possible to access across0, across1, and across3 based on what the value of the counter is?

Accessing Variable in Loop


UTF-8 decoding doesn't decode special characters in python

Question: Hi I have the following data (abstracted) that comes from an API.
"Product" : "T\u00e1bua 21X40"

I'm using the following code to decode the data byte:
var = json.loads(cleanhtml(str(json.dumps(response.content.decode('utf-8')))))

The cleanhtml is a regex function that I've created to remove html tags from the returned data (It's working correctly). Although, decode(utf-8) is not removing characters like \u00e1. My expected output is:
"Product" : "Tábua 21X40"

I've tried to use replace("\\u00e1", "á") but with no success. How can I replace this type of character and what type of character is this?
Answer: \u00e1 is another way of representing the á character when displaying the contents of a Python string.
If you open a Python interactive session and run print({"Product" : "T\u00e1bua 21X40"}) you'll see output of {'Product': 'Tábua 21X40'}. The \u00e1 doesn't exist in the string as those individual characters.
The \u escape sequence indicates that the following numbers specify a Unicode character.
Attempting to replace \u00e1 with á won't achieve anything because that's what it already is. Additionally, replace("\\u00e1", "á") is attempting to replace the individual characters of a slash, a u, etc and, as mentioned, they don't actually exist in the string in that way.
If you explain the problem you're encountering further then we may be able to help more, but currently it sounds like the string has the correct content but is just being displayed differently than you expect.
Comment: I didn't know that. I found a solution that works that is use \\\\  before the character code, this works with replace, so `replace("\\\\u00e1", "á")` replaces `u00e1`  to `a`. Maybe the post should be closed.
Answer: what type of character is this
Here
"Product" : "T\u00e1bua 21X40"

you might observe \u escape sequence, it is followed by 4 hex digits: 00e1, note that this is different represenation of same character, so
print("\u00e1" == "á")

output
True

Answer: These type of characters are called character entities. There are different types of entities and this is JSON entity. For demonstration, enter your string here and click unescape.
For your question, if you are using python then you can solve the issue by importing json module. Then you have to decode it as follows.
import json

string = json.loads('"T\u00e1bua 21X40"')
print(string)


Prove by induction that $\sum_{k=1}^n \frac 1k \ge \ln (n+1)$ for all $n \ge 1, n \in \Bbb N$

Question: I'm working on the following question:
Prove by induction that $$\sum_{k=1}^n \frac 1k \ge \ln (n+1)$$ for all $n \ge 1,        n \in \Bbb N$
Here's what I managed to achieve so far:
Base case for $n=1$
For n=1, we are left with the inequality $1 \ge \ln (2)$, which is obviously true.
Induction assumption
We assume that $\sum_{k=1}^n \frac 1k \ge \ln (n+1)$ is true for some natural number $n \ge 1$.
Proof
We must now prove the following: $\sum_{k=1}^{n+1} \frac 1k \ge \ln (n+2)$, given the assumption.
Now here's what I managed to do in this part:
$$\sum_{k=1}^{n+1} \frac 1k = \sum_{k=1}^n \frac 1k + \frac 1{n+1}$$
Using the assumption $\sum_{k=1}^n \frac 1k \ge \ln (n+1)$ we may write $$\sum_{k=1}^{n+1} \frac 1k \ge \ln (n+1) + \frac 1{n+1}$$
It is here that I'm stuck. I would greatly appreciate it if anyone could point out the next steps or at least give me a hint as to where to continue.
Thanks a lot in advance!
Comment: $ln(1+x)\le x$ then what about $\ln(n+2)-\ln(n+1)$. Note that induction might not be the easiest way to prove this inequality. Comparing with $\int_k^{k+1}\dfrac {dt}t$ is simpler.
Comment: Just out of curiosity, how does this comparison to $\int_k^{k+1} \frac {dt}t$ work? I'm not familiar with this method.
Answer: You're almost done, it remains to prove that $$\ln (n+1) + \frac 1{n+1}\geq \ln(n+2)$$
This is equivalent to $$\frac 1{n+1}\geq  \ln\left(1+\frac{1}{n+1}\right)$$
which is a consequence of the concavity inequality $\ln(1+x)\leq x$ for $x>-1$.
Answer: it must be $$\frac{1}{n+1}\geq \ln\left(1+\frac{1}{n+1}\right)$$ with $$x=\frac{1}{n+1}$$ you must prove that $$x\geq \ln(1+x)$$ can you finish?
Answer: <code>Just out of curiosity, how does this comparison to ∫dt/t work?
I'm not familiar with this method.
</code>

The curve $y=\dfrac 1x$ in the interval $[k,k+1]$ is stuck between $y=\dfrac 1k$ above and $y=\dfrac 1{k+1}$ below.
You are typically in the case of squeezing the integral of $\frac 1x$ between the upper and lower rectangles area approximation.
On the interval $[k,k+1]\begin{cases}
\color{red}{\mathcal U_k}=((k+1)-k)\times\frac 1k=\frac 1k\\
\color{green}{\mathcal L_k}=((k+1)-k)\times\frac 1{k+1}=\frac 1{k+1}\end{cases}\quad$ and $\quad\displaystyle\color{green}{\mathcal L_k}\le\color{blue}{\int_k^{k+1} \dfrac{\mathop{dt}}t}\le \color{red}{\mathcal U_k}$
Now sum everything to get :
$\displaystyle \sum\limits_{k=1}^{n} \dfrac 1{k+1}\le\int_1^{n+1} \dfrac{\mathop{dt}}t\le \sum\limits_{k=1}^{n} \dfrac 1{k}$
In particular you get the desired inequality :
$\displaystyle \sum\limits_{k=1}^{n} \dfrac 1{k}\ge\int_1^{n+1} \dfrac{\mathop{dt}}t=\ln(n+1)$
Comment: That was interesting, thank you!


Problema Codigo UPDATE MYSQL PHP

Question: Alguem poderia me confirmar se o codigo abaixo está correto, eu não sou bom em php nem em mysql, só faço arranjos e não estou conseguindo o resultado esperado, a conexão com db está correta, não apresenta erros(exite um if para error)...
O resultado esperado é quando preencher no html "name" seja inserido 100000 na columa paymoney WHERE name=name
full code http://pastebin.com/Y65ThtnK
<code><?php
ob_start();
session_start();

include_once 'dbcon.php';

if(isset($_POST['btn-signup'])) {

 $name = trim($_POST['name']);

 $name = strip_tags($name);

 // paymoney encrypt using SHA256();

 // check usuario dup
 $query = "UPDATE player SET paymoney='10000'
           WHERE name ='$name'";

}
?>
</code>
Comment: Poderia dar mais detalhes e mencionar de que tipo é esse valor 100000 pois se ele for do tipo int você não precisa usar aspas simples e a variável nome tente passar assim '".$name."'.
Comment: Só falta executar a consulta no banco.
Answer: Falta executar.
<code>$query = "UPDATE player SET paymoney='10000'
           WHERE name ='$name'";
$suaconexao -> query($query);
</code>
Answer: Coloque a sql assim:
<code>$query = "UPDATE player SET paymoney='10000'
           WHERE name = ".$name;
</code>

Problema Codigo UPDATE MYSQL PHP


how to return a nested promise?

Question: I have a javascript function looks like this:
function foo() {

    var returnPromise;

    $.when(asyncMethod1(), asyncMethod2()).then(
        function() {
            //… process results from method1 and 2
            returnPromise = $.when(asyncMethod3(), asyncMethod4()).then(
                function() {
                    finalMethod();
                }
            );
        });
    return returnPromise;
}

The code above would not work because foo() will exit before returnPromise gets assigned.  asyncMethod3 and 4 can only be executed after asyncMethod1 and 2 are completed.  Any suggestion on how to structure my javascript function?
Comment: Closely related  http://stackoverflow.com/q/22539815/1348195
Answer: You can just chain then calls.
function foo() {
    return $.when(asyncMethod1(), asyncMethod2()).then(function(resultOf1, resultOf2) {
        return $.when(asyncMethod3(), asyncMethod4());
    });
}

foo().then(function finalMethod(resultOf3, resultOf4) {});

Note: You do not have to name the function expression, I did it for clarity.
Comment: @E.A.  This will work if `asyncMethod1()` and `asyncMethod2()` and `asyncMethod3()` and `asyncMethod4()` return promises.  That's what  `$.when()` requires in order to do its job.  So, if you're seeing the behavior you describe, then those asyncMethods must not be returning promises that are resolved when their corresponding async operation is complete.
Comment: For completeness, you may want to show the args in the first `.then()` callback that come from the results of `asyncMethod1()` and `asyncMethod2()` since the OP says they want to use those results in the next two async calls.
Comment: The ans above does not work.  foo() is returned before asyncMethod1 and asyncMethod2 (forget about 3 and 4) are done.  In your code, finalMethod() will be the first method to be executed.
Comment: Thx jfriend, you nailed it!

how to return a nested promise?


Composition and instrumental voices

Question: Can anybody explain to me if modern music follows a similar composition style to four part harmony. What I'm asking is just like in 4-Part Harmony where the bass voice gets the "low-range" or "bass" instruments and the soprano section would go the "higher-range" instruments is it a way of organizing modern-music like this? If so what are the sections name and how are they determined.  Again, to be clear I'm basically asking if modern music is divided up into sections (bass sections or low-end) the same way 4-part Harmony is? When I say "like 4-Part Harmony" I'm knowing that 4-Part Harmony is its own compositional method but 4-part harmony was the only could I could think of. I don't mean follow the same rules as 4-Part Harmony I mean is it organized or divided into sections.
Comment: With deep theory deconstructionism there may be some scholarly terms for various pitch range sections. Someone may have that answer.  In general usage though I'm not aware of any specific terms that work the same way the SATB or 4 part harmony descriptions.  We tend to block off the compositions into three or four ranges of pitch for utility, but ultimately the composer is using whatever range is available with the instruments being used.  Think piccolo quartet, where harmonically all the chordal notes are being represented, but the instruments are all in high treble range.
Answer: Sort of. Maybe. I can think of two possible ways that we practically split up instruments into different categories; role and range. A big part of the SATB delineation is the range of the singers; that's a little less important when talking about instruments like guitars and keyboards, which have quite a wide range.
For some context, this is mostly based around my experience with contemporary church bands. These bands don't usually have fully written out arrangements, but are required to 'arrange on the fly'.

Let's think about the role that instruments play in any given arrangement. I might have a band comprised of bass guitar, drums, acoustic guitar, keys, two vocalists, and two flute players. I'll ask the band to think of the different roles that they can play, in terms of rhythm, harmony and melody. The idea is to ensure that the right people are playing the right roles, and to avoid multiple people playing over the top of each other. Let's break that down:

Our rhythmic foundation is going to come from the drums, and also the bass guitar, and at some level, the acoustic guitar.
Our bass is probably going to come from the bass guitar. This means that the keyboard is not going to play a bass role, and should avoid getting in the way of the bass guitar.
Our harmony is going to come primarily from the keys and guitar, but with some influence from the melodic instruments (flutes/vocals)
Melody (by which I mean the actual tune, as well as riffs and other things) is going to come from the vocals (in harmony), the flutes, and the keys.

Obviously that isn't set in stone, but we are dividing the instruments up in terms of role. This is particularly important if there is no full arrangement with sheet music for everyone. Otherwise individual musicians have a tendency to overplay, and get in the way of each other. Keyboards can be prone to attempting to play all the roles (bass, harmony, melody, and rhythm) by themselves. Acoustic guitars never seem to stop playing. You get the picture.

We do also think in terms of range. Keys and guitar are a good example here. As the keyboard player, I'm going to be listening to the guitarist, and trying to complement what he/she is playing. If the chord voicing used by the guitarist is quite full, and in the midrange, the keys should probably stay away from the octave above/below middle C. Either that, or ask the guitarist to leave a bit of space. Or not play at all. They are all valid options.
We also try and leave space around the vocals themselves. So you could try and categorise the role that each instrument plays in terms of the range in which it operates.

That's a bit of a long answer, but my general point is that we do sometimes split up instruments into different roles. They are not set in stone, and change between different pieces, or even different sections of a piece. It can be based on the range of the instrument (like SATB), but is not necessarily.

Composition and instrumental voices


Using views arguments to highlight/alter corresponding entries instead of filtering

Question: So, I am making a tree based tab style menu for a section of my site.
There are 3 content types with node references going up the tree. They are ordered: Section < Product < Package.
If I am on a package I want to display 3 tiers of tab at the top of the page, filtered by the section/product the package is in and with the section+product+package that the package is a child of highlighted.
eg: If I am looking at "SECTION1 PRODUCT2 PACKAGE3" it should display the tabs like this:
SECTION1 section2 section3
section1product1 SECTION1PRODUCT2 section1product3
section1product2package1 section1product2package2 SECTION1PRODUCT2PACKAGE3
with the capitalisation representing something akin to the "active"class in css
My URL aliases are formatted: example.com/[sectionname]/[productname]/[packagename]
Edit: Many paths have failed me thus far... Any generic advice welcome...
Answer: Ended up just manually making a menu to display the same information... Surely there should be support for one of: node path aliases as arguments OR menu generation from nodereference tree OR menu generation from url aliases (ideally from only selected nodes)
Alas i found none of the above. I feel gross for creating the menu manually but there seemed to be no other way. Thanks for checking this out...


Is this written correctly? Left hand c and right hand c

Question: i bought a beginner piano book for my child and we are playing a piece in which it is written that the middle c is played on the lower staff with left hand on half note followed by middle c on upper staff with right hand on quarter note.
I am wondering is it written correctly and how it can be executed. I feel you need to release the middle c on the left hand after one beat so that the right hand and play the same middle c. If you continue to hold the middle c on the left hand for 2 beats, you won't be able to press the middle with the right hand on the 2nd beat.
So my question here is whether it is written correctly. Should the middle c on the lower staff be a quarter note instead of a half note?

Thanks for your replies.. I understand it's written in a simplified manner and rests are omitted at this early stage of learning.
So my question is if written correctly, how should this part be to played on the piano? Should I teach my child to play the middle C on the left hand as a quarter beat instead. Should it be rewritten as below?
Comment: In practice, yes, that's how you would do it, unless you want to sometimes play it as duet, where one person is playing the right hand and the other is playing the left hand.  It's easier to split something like this up into a duet if you shift the left hand down an octave, so you're not so squished into each other on the bench.  In that case the left hand can play the line as written.
Comment: If it were a quarter note there would have to be a quarter rest after it, and apparently the editor wanted to avoid rests in this very early example. Note that rests are also absent from the first bars of the right hand part.
Answer: It isn't exactly correct, as you point out, that C can't be held on and played again simultaneously. It's a sort of simplification, to avoid messing up beginners, with rests. It sort of works, and most will turn a blind eye to it.
Comment: Just to clarify, the LH half note should not be held two beats so that the C in the melody can be heard. In this situation where a note is held, but another plays "on top of" the same note, the melody note is the one that must be heard.
Answer: This sort of thing happens all the time in 'real music'.  It indicates the musical intention, the player takes care of the mechanics.
It's rather odd to see it in an elementary piano instruction book though.  Perhaps the writer was more interested in the religious lyrics than the piano pedagogy :-)
Answer: Yes, you should have them release the C after one beat and play a quarter rest. A more advanced pianist can use the pedal to make it seem like the C is being held, but this isn't the place to teach such a technique.
I wouldn't call this notation "wrong": Bach and other classical composers use it, although it can be confusing to players. It invites the listener to hear two voices moving at different rates (here a melody in quarter notes and a bass in half notes).
Answer: a playing suggestion might be to double the "E" (in the treble clef) instead.


mount_afp on linux, user rights

Question: I need to mount a remote filesystem on a linux box using the afp protocol. The linux box runs an old Debian 4.
I downloaded the source code of mount_afp, compiled it and installed it with all the required packages.
Then created /etc/fuse with the following command:
  mknod /dev/fuse c 10 229

(according to the instructions here)
I can mount the remote filesystem as root by executing:
 mount_afp afp://USER:PASSWD@REMOTE_SERVER/FOLDER /mnt/MOUNTPOINT/

but the same command fails when run as normal user (of the local machine).
After reading here and there, I created a group fuse, and added my normal user U to the group fuse:
[prompt] groups U
U fuse

Then modified the group of /dev/fuse, that now has the following rights:
 0 crwxrwx--- 1 root fuse 10, 229 Feb  8 15:33 /dev/fuse

However, if the user U tries to mount the remote filesystem by using the same command as above, U gets the following error:
Incorrect permissions on /dev/fuse, mode of device is 20770, uid/gid is 0/1007.  But your effective uid/gid is 1004/1004
But the user U with uid 1004 has also gid 1007 (group fuse).
I might think the problem is related to real/effective/etc. ID, but I do not know how to proceed and could not find any clear instructions. Could you please help me?

There is also another problem. If I mount /mnt/MOUNTPOINT as root and run ls -l /mnt, I get:
  drwxrwxrwx 15 root root 466 Feb  8 16:34 MONTPOINT

If I run ls -l /mnt as normal user U I get:
 ? ?????????? ? ? ? ?            ? MOUNTPOINT

in fact when I try to cd /mnt/MOUNTPOINT I get:
 $-> cd /mnt/MOUNTPOINT
-sh: cd: /mnt/MOUNTPOINT: Not a directory

Then I unmount /mnt/MOUNTPOINT as root and run again ls -l /mnt as normal user U I get:
 0 drwxr-xr-x 2 root root 6 Feb  8 15:32 MOUNTPOINT/

After reading Frank's answer, I killed every shell/process running with privileges of user U. Still U cannot mount the remote filesystem, but the error message has changed. Now it is: "Login error: Authentication failed". The problem is not related to remote login/password since the same command works perfectly when run as root of the local machine.

Since I cannot get mount_afp to work with normal users, I decided to follow mgorven's suggestion. So I run the commands:
 mount_afp -o allow_other afp://USER:PASSWD@REMOTE_SERVER/FOLDER /mnt/MOUNTPOINT/

and
 mount_afp -o user=U afp://USER:PASSWD@REMOTE_SERVER/FOLDER /mnt/MOUNTPOINT/

The mount succeeds but user U cannot access the mount point. If U executes ls -l in /mnt
U@LOCAL_HOST [/mnt]
$-> ls -l
ls: cannot access MOUNT_POINT: Permission denied
total 0
? ?????????? ? ? ? ?            ? MOUNT_POINT

Is it so hard to have this utility working?
Answer: Success for my single user setup came in the form of

creating the group fuse
adding U to the fuse group
mounting with
mount_afp -o user=U,group=fuse afp://USER:PASSWD@REMOTE_SERVER/FOLDER /mnt/MOUNTPOINT

using the uid and guid was not working for me
Unknown user 1000
Unknown group 108
these being the correct uids as retrieved from id U

permissions were then set to 777 for the mounted directory and I was finally able to browse and play.
This doesn't solve the OPs question, but hopefully it's enough confirmation for some.
Comment: Did the `user` and `group` options get removed in newer MacOS versions?
Answer: You probably didn't log out and in again after adding yourself to the fuse group. Group information is cached and so you need to do this after changing group memberships. Run groups after doing so to verify that fuse is listed.
By default FUSE mounts only allow access to the user who mounted them. If you want to allow other users to access them you need to add the allow_other mount option, so try this:
mount_afp -o allow_other

If that doesn't work you can set the ownership of the mount to your own user:
mount_afp -o user=1004,group=1004

Comment: I did log out and back in after adding the user to the `fuse` group. The problem concerns the user U not being able to mount the filesystem.
Comment: I would rather not assign the ownership of the mount point to a specific user since the linux server is used by several people who wish to mount the same remote filesystem.
Comment: Hi, since nothing was working, I tried to follow your suggestion. I modified the question. Do you have any idea why it keeps refusing to work?
Answer: I had the same problem.  Having added the username to the fuse group I logged out and back in (on ssh). But I still had the same problem. Then I rebooted the box.  It then worked fine after creating a mount point the user has access to.  So for me log out via ssh then log back in did not force reload of the groups, I guess you have to reboot or may be log out from all other shells (I am not sure if there were other shells I was log in on).
Comment: After reading your answer, I checked the number of running shells/processes for user `U` and found a plenty of. Killed every single process, now I have a different error: "Login error: Authentication failed". I updated the question.

mount_afp on linux, user rights


How to reduce the width of a staff containing only a rest in LilyPond

Question: Consider this example :
{
#(set-global-staff-size 25)
%\tempo Allegro
\time 4/4
a'4 b' c'' d''
R1
a'4 b' c'' d''
R1
a'4 b' c'' d''
R1
a'4 b' c'' d''
R1
a'4 b' c'' d''
}

Is there a way to impose a smaller width to the bars that only contain a rest, which would give more space to the other bars? (Not best practice but I try to copy a manuscript.)
Knowing that the Lilypond manual states "No workaround exists for decreasing the amount of space."
(Related to this question.)
Answer: In fact there is. MultiMeasureRest use the dummy property springs-and-rods to set the actual spacing, so we can actually get rid of all extra spacing by setting
\override MultiMeasureRest.springs-and-rods = ##f

But more reasonably: ly:multi-measure-rest::set-spacing-rods pads the length by the value of the property bound-padding to both sides, which defaults to 0.5ss (so the total length is padded by 1ss). Adjust this value as you like
\override MultiMeasureRest.bound-padding = #-0.5

to achieve wider or narrower spacing. This padding can also be set to a negative value, but can not lead to negative spacing.


X-editable with .Net and c# web methods

Question: I am using X-Editable Plugin in Asp.net.
I have tried this: Usage with .Net and C# Webmethods
But it gives me error. It is not calling the WebMethod as it should be.
How to solve this problem?
Please help.
Javascript:
 $('#username').editable({
     url: function (params) {
        return $.ajax({
           url: 'Default.aspx/TestMethod',
           data: JSON.stringify(params),
           dataType: 'json',
           async: true,
           cache: false,
           timeout: 10000,
           success: function (response) {
                     alert("Success");
           },
           error: function () {
                     alert("Error in Ajax");
           }
          });
      }
});

HTML:
superuser

WebMethod in Default.aspx:
[System.Web.Services.WebMethod]
public static String TestMethod(String params)
{
    //access params here
}

Answer: If you want to call a page method, first of all you need to make a request of type POST (also having content-type set will not do any harm):
$('#username').editable({
    url: function (params) {
        return $.ajax({
            type: 'POST',
            url: 'Default.aspx/TestMethod',
            data: JSON.stringify(params),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: true,
            cache: false,
            timeout: 10000,
            success: function (response) {
                alert("Success");
            },
            error: function () {
                alert("Error in Ajax");
            }
        });
    }
});

Also the JSON will be auto deserialized on server side, so you should expect the name, pk and value parameters on server side (this is what plugin is sending according to docs)
[System.Web.Services.WebMethod]
public static String TestMethod(string name, string pk, string value)
{
    //access params here
}

In your case the pk will be null as you haven't set one.
Comment: @Roylee I'm afraid that there is no way to change the supported verb on the ASP.NET side, you would have to go for HttpHandler instead.
Comment: thank you tpeczek. I wasnt provided the TYPE for Ajax call. Also thanks for the Signature of WebMehthod.
Comment: +1 Btw can I use PUT ? As PUT is meant to 'update' and POST is for 'add new'. I'm using REST approach here.
Comment: THanks @tpeczek. Yes I managed to get it working with WEB API(REST). Just hack using ajaxOption and you could achieve PUT easily.

X-editable with .Net and c# web methods


How to change or set new activity launcher app? (in Java)

Question: I have a payment activity and splash activity that it shows app of contents after user will buy it. payment activity is default Launcher in Manifest.xml that I want to set launcher Activity to  splash activity and payment activity disabled after payment.
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.exa.iu2">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".PaymentActivity" android:theme="@style/SplashTheme">

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:scheme="return" android:host="zrp"/>
            </intent-filter>
        </activity>
            <activity-alias
                android:name=".PaymentActivity"
                android:icon="@mipmap/ic_launcher"
                android:label="@string/app_name"
                android:roundIcon="@mipmap/ic_launcher_round"
                android:enabled="false"                              android:targetActivity=".SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>
        <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:screenOrientation="portrait"
                android:theme="@style/AppTheme.NoActionBar"/>
    </application>
</manifest>

in Payment Activity and "If payment is success"
public void onCallbackResultVerificationPayment(boolean isPaymentSuccess, String refID, PaymentRequest paymentRequest) {
        if(isPaymentSuccess){
            Toast.makeText(PaymentActivity.this, "Payment Success" + refID, Toast.LENGTH_SHORT).show();
            ComponentName cm = new ComponentName("com.exa.iu2", "com.exa.iu2"+".SplashActivity");
            ComponentName cm2 = new ComponentName("com.exa.iu2", "com.exa.iu2"+".PaymentActivity");
            PackageManager pm = getApplication().getPackageManager();
            pm.setComponentEnabledSetting(cm, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
            pm.setComponentEnabledSetting(cm2, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,0);
        }else {
            Toast.makeText(PaymentActivity.this, "Don't success", Toast.LENGTH_SHORT).show();
        }
        }
    });

Thx
Answer: I suggest you create a Hub or Startup activity in which decide what to display. The new activity has to be set as Main -> Launcher activity, obviously.
Comment: May you give some information about Hub or Startup Activity?
Comment: It is a simple Activity where you can put whatever business logic you need to display the Splash activity or the Payment activity.
Comment: As you say, I dont need  and check  my condition with third activity that it is success to start splash activity otherwise start payment activity
Answer: In AndroidManifest do this
<activity android:name=".SplashActivity"
          android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>

Inside SplashActivity
public class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        // Check condition to open appropriate activity
        // like
        // if(paymentDone) start some activity
        // else start another activity

        finish()

    }
}


Sum-to-product formulas for the Weierstrass elliptic functions ( $\wp$ and $\wp^\prime$)

Question: In the theory of trigonometric functions, the following identity is known
$$ \sin(u) + \sin(v)=2\sin \left( \frac{u+v}{2} \right) \cos \left( \frac{u-v}{2} \right) $$
There are other, similar-looking identities, known as the sum-to-product identities.
Are there similar identities involving the Weierstrass elliptic functions, $\wp$ and $\wp^\prime$? More specifically, are there identities simplifying the expressions below?
$$\wp(u;g_2,g_3) \pm \wp(v;g_2,g_3) \qquad\qquad\wp'(u;g_2,g_3) \pm \wp'(v;g_2,g_3)$$
Thank you!
Comment: What we can do is there https://en.wikipedia.org/wiki/Weierstrass%27s_elliptic_functions#Addition_theorems (this is the group law on the elliptic curve $y^2 = 4x^3-g_2x-g_3$)
Answer: It's easier to work with the equivalent formulae
$$ \sin{(u+v)}+\sin{(u-v)} = 2\sin{u}\cos{v} $$
and so on. We can proceed in a similar way to the trigonometric formulae, using the addition formula
$$ \wp(u \pm v) = \frac{1}{4} \left( \frac{\wp'(u) \mp \wp'(v)}{\wp(u)-\wp(v)} \right)^2 - \wp(u) - \wp(v) $$
(the minus sign follows from the plus sign formula since $\wp$ is even and $\wp'$ odd). Then
$$ \wp(u+v)+\wp(u-v) = \frac{\wp'(u)^2+\wp'(v)^2}{2(\wp(u)-\wp(v))^2} -2\wp(u)-2\wp(v), $$
which can also be written as
$$ \wp(u+v)+\wp(u-v) = \frac{(\wp(u)+\wp(v))(2\wp(u)\wp(v)-g_2/2)-g_3}{2(\wp(u)-\wp(v))^2}  $$
using the differential equation, whereas
$$ \wp(u+v)-\wp(u-v) = -\frac{\wp'(u)\wp'(v)}{(\wp(u)-\wp(v))^2}. $$
(In fact, it's easier to prove these two than the addition formula: see e.g. here for my derivation of the addition formula using these.)
Another example is the formula
$$ \wp(v)-\wp(u) = \frac{\sigma(u+v)\sigma(u-v)}{\sigma(u)^2\sigma(v)^2} $$
(https://dlmf.nist.gov/23.10.E3), which uses the quasi-periodic $\sigma$-functions as well.
Any formula for $\wp'$ can be found by differentiating one for $\wp$, so they are not normally considered separately.
But $\wp$ isn't really much like $\sin$: it's more like $\pi^2/(4\omega_1)^2 ( \csc^2{(\pi z/(2\omega_1))} -1/3 )$, which we probably don't really expect to have a nice addition formula.
$\DeclareMathOperator{\sn}{sn}
\DeclareMathOperator{\cn}{cn}
\DeclareMathOperator{\dn}{dn}
$
A closer equivalent is the Jacobi elliptic function $\sn$, which has the addition formula
$$ \sn(u \pm v) = \frac{ \sn{u}\cn{v}\dn{v} \pm \sn{v}\cn{u}\dn{u} }{1-k^2\sn^2{u}\sn^2{v}}, $$
and hence
$$ \sn{(u+v)} + \sn{(u-v)} = \frac{ 2\sn{u}\cn{v}\dn{v} }{1-k^2\sn^2{u}\sn^2{v}} \\
\sn{(u+v)}-\sn{(u-v)} = \frac{ 2 \sn{v}\cn{u}\dn{u} }{1-k^2\sn^2{u}\sn^2{v}} $$
Since $\sn \to \sin$, $\cn \to \cos$, $\dn \to 1$ as $k \to 0$, these obviously become the trigonometric addition formulae. Similar ones exist for the other Jacobi functions.


Angular 2 Quickstart: wrong encoding of js files

Question: I'm very new to angular 2, so I'm trying to make this work: https://angular.io/guide/quickstart
The problem which I have really confuses me. All JS files, which I get as a response, have strange encoding - basically, I see a bunch of hieroglyphs. Non-js files (html and css) are ok. Please see below, html is ok. Js - totally not.

Do you guys have any idea, what can it be? Computer culture is not Chinese or Japanese, just in case.
Answer: You can use notepad++ or any html editor with encode options available to change the page encoding:

Open your file with Notepad++
Go to "Encoding" menu option in main menu
Select "Convert to UTF-8-BOM"
check if the page display correctly
Comment: Thanks! Strangely enough, some of the files had UTF-16. This solved it!
Answer: This can be related to your js files encoding on your editor.


Father and son who were active players at the same time in NFL/NBA/NHL/MLB?

Question: Has there ever been a father and son in the NFL/NBA/NHL/MLB who were both active players at the same time?
Comment: This is not a bad question, but how can an answer be marked accepted, being so many examples?
Comment: Note, I asked a question on [meta] about this, [here](http://meta.sports.stackexchange.com/questions/548/community-wiki-for-list-type-questions).
Comment: I'm voting to close this as "too broad". The list of answers is just growing and growing, and none of them are really better than any others.
Comment: I think I had this in my cracker in the christmas of 1986 ;-) http://www.espncricinfo.com/pakistan/content/player/40879.html
Comment: I could just edit the question to specify MLB/NFL/NHL/NBA and accept Joe's answer.
Comment: You don't need to edit the question; accepting doesn't mean "single correct answer" but rather "answer that was most helpful".  Though I don't really care if you accept it, it's fine as it is.
Comment: I've rolled this back to revision one, given the [meta question](http://meta.sports.stackexchange.com/questions/550/answer-after-modify-questions) about it and my uncontested suggestion in its answer that it wasn't appropriate to modify this question after receiving answers.
Comment: Some candidates may be found in [List of professional sports families](https://en.wikipedia.org/wiki/List_of_professional_sports_families) on Wikipedia (and some other related Wikipedia lists/articles).
Answer: Absolutely.  Ken Griffey Jr. and Ken Griffey Sr. played together in 1990 for the Seattle Mariners.  They once hit back to back home runs in a game.
https://www.youtube.com/watch?v=_G2AnNdjBu4
http://www.baseball-reference.com/boxes/CAL/CAL199009140.shtml
They played about a month together (8/31 to the end of the season).
In Hockey, Gordie Howe played with his sons Mark and Marty in 1979-80 for the Hartford Whalers.  Wikipedia has a nice page with a list of familial relations in the NHL (they seem to have more than most leagues, probably because the sport is less popular so more likely for familial relations to be successful).  The direct link to the Howes' is at Legends of Hockey.
In the NFL, it doesn't look like anyone really did in the modern era due to the very short career length compared to other sports (except for kickers); in the 1920s, Ted and Charles Nesser played together, Ted as player-coach, and I don't doubt a few more similar occurrences would be found if you looked through the 10s and 20s.
George Wilson coached his son (also George) for the 1966 Miami Dolphins, the only example of that I found.  Ed and Brad Budde were the closest to playing with each other from the list I saw, Ed playing 1963-1976 for the Chiefs and Brad joining the Chiefs in 1980-1986.  This is from a list of father-son relationships from the Pro Football HOF.
From the comments, Leatherwing noted that Wikipedia also has a good NBA Father/Son page; Kobe Bryant nearly overlapped with Bean, his father (1992/1996).
Comment: @Leatherwing With respect to the NBA Draft, a player must have been removed from his high school graduation for at least a year to be eligible to declare. The reason this is the case is due to the "enter straight out of high school" case you state. http://en.wikipedia.org/wiki/Eligibility_for_the_NBA_draft#Automatic_eligibility
Comment: Here is a list of NBA Father son duos. Kobe Bryant started in 96 and his father ended in 92. So close! Basketball players also have short careers, but there are more of them that enter straight out of high school, so there may be an overlap one day. http://en.wikipedia.org/wiki/List_of_second-generation_National_Basketball_Association_players
Comment: @edmastermind29 Good point. I don't follow NBA closely and didn't realize they had made that change for draft eligibility.
Comment: Realistically it would have to be an amazing player, whose son was born when that amazing player was just out of high school (or in it), who was also amazing.  MJ had kids too late, although he did have the length of career and his kids were at least borderline okay (I could've seen the Wizards signing Jeffrey or Marcus if they'd been born five years earlier and eligible for the NBA in 2000 or so, for example, as a publicity stunt if nothing else; it's not like the 12th player on most teams is a useful body.)  But otherwise it seems unlikely; so few play until 40.
Comment: I'm going to go ahead and mark this CW, but I won't add the other answers to it; if those of you who did answer below want to add them in please feel free.  If the meta question ever gets enough attention to come to a clear answer I might do the same, but until then I don't feel comfortable doing that.
Answer: I realise it's not father and son, but Paul Elvstrøm sailed with his daughter Trine. They won the 1983/4 European Tornado Championships, were 4th in the 1984 Los Angeles Olympics, and 15th at the 1988 Seoul Olympics.
Comment: This reply was posted when the answer was not limited to "NFL/NBA/NHL/MLB" tournaments (only to prevent downvoting)
Answer: In Cricket there are several examples of that:
18 times a father and son have played in the same match
In 1851 and 1853 even William Lillywhite has played with his two sons: John and James
Comment: This reply was posted when the answer was not limited to "NFL/NBA/NHL/MLB" tournaments (only to prevent downvoting)
Answer: In (international) football: Eiður and Arnór Gudjohnsen.
On 24 April 1996, he and his father entered football history in an Iceland international friendly in Tallinn. Arnór started the match, and Eiður came on in the second half as a substitute for his father.
Comment: This reply was posted when the answer was not limited to "NFL/NBA/NHL/MLB" tournaments (only to prevent downvoting)
Answer: I don't know if car racing meets the definition of a sport in the OP's question, but there have been some contemporaneous fathers and sons in car racing. Perhaps the most famous is Dale Earnhardt Sr. and Jr. They were in the same race when Earnhardt Sr. died.
Comment: This reply was posted when the answer was not limited to "NFL/NBA/NHL/MLB" tournaments (only to prevent downvoting)
Answer: This weekend 55 year old Dave Beasant was included on the bench for Stevenage FC as a second choice goalkeeper, in place of his injured son Sam who is also a Stevenage goalkeeper. So they will never appear in the same team, or even in the same squad, but are both currently 'active' players for their club.
https://uk.eurosport.yahoo.com/news/football-beasant-named-substitute-174734329--sow.html
Also another recent case in football was Brazilian legend Rivaldo playing for the same team as his son, Rivaldinho. They both played for Brazilian team Mogi Mirim earlier this year.
https://uk.eurosport.yahoo.com/blogs/early-doors/brazilian-legend-rivaldo-fulfils-amazing-ambition-playing-alongside-123845896.html
Comment: This reply was posted when the answer was not limited to "NFL/NBA/NHL/MLB" tournaments (only to prevent downvoting)
Answer: Italian basketball legend Dino Meneghin played against his 16-year-old son Andrea in 1990, in a game of the top professional Italian league. He was 40 at the time.
Source: Dino Meneghin, the eternal champion.
Comment: This reply was posted when the answer was not limited to "NFL/NBA/NHL/MLB" tournaments (only to prevent downvoting)
Comment: (I haven't checked in detail each one of them, but it seems that in most other answers father and son are in the same team; so this could be the only answer with the two playing **against** each other.)
Answer: In ice hockey, Sami and Kasperi Kapanen played last season in the Finnish league.
Comment: This reply was posted when the answer was not limited to "NFL/NBA/NHL/MLB" tournaments (only to prevent downvoting)
Answer: It's actually fairly common in U.S. auto racing; teams in those sports are often family owned and passed down between generations.

Lee Petty raced against two of his sons, Richard and Maurice, in the same NASCAR race in 1960.
Mario Andretti raced alongside his son Michael in the CART Indy Car series for 8 years, from Michael's rookie year in 1984 (Mario having rejoined the Indy Car series from Formula-1 in '82), to 1992 when Mario retired for good (becoming Michael's crew chief). From 1990 to 1992, Mario and Michael were joined on the circuit by Jeff, Mario's son and Michael's brother, who raced in CART until a serious crash in 1994 effectively ended his career. Michael, in turn, practiced alongside his own son Marco before the latter's first Indy 500 in 2006, but the two never competed in a race as Michael had officially retired in 2002.
Al Unser Sr and Jr were both in the American Championship (aka CART) for 11 years before "Big Al"'s retirement in 1994. Al Sr and his brother Bobby Unser also raced together.
Dale Earnhardts Jr and Sr competed together in the Winston Cup Series in 2000 and 2001 before Sr's fatal crash at Daytona.
Answer: In motorsports, Jan Magnussen is still an active competitive driver in Danish touring cars while his son Kevin drives for McLaren in Formula 1. This may not count since they are very different series.
Martin Brundle and his son Alex Brundle competed in the same team, Greaves Motorsport, driving at the 24 hours of Le Mans in 2012:
http://en.wikipedia.org/wiki/Alex_Brundle
Comment: This reply was posted when the answer was not limited to "NFL/NBA/NHL/MLB" tournaments (only to prevent downvoting)
Answer: According to this FIFA article also Carlos Alonso and Juan Carlos Balazar play in the same official match in first division Peruvian football league
Comment: This reply was posted when the answer was not limited to "NFL/NBA/NHL/MLB" tournaments (only to prevent downvoting)
Answer: Gordie Howe came out of retirement to play with his sons, Mark and Marty Howe, when the WHA came into being. After the WHA merged with the NHL, Mark and Gordie played together with the Hartford Whalers for one season.
Sources: Gordie Howe, Mark Howe
Comment: This reply was posted when the answer was not limited to "NFL/NBA/NHL/MLB" tournaments (only to prevent downvoting)
Answer: Also in curling is possible to find some matches where father and son play in the same match:

On this article from Milwakee Journal (date 27 feb 1937!) there is the news where in two matches there where fathers and sons: George La Marre played versus his sons William, Edwards and Charles and on another rink Lachman MacDonald played with his son Bruce
On november 2011, according to this article the famous Glenn Howard played versus his son Scott
Answer: Conrad Harrison and his son Dean Harrison both won TT titles in the same week.
According to Wikipedia:

With his father Conrad Harrison winning the Sidecar Race 1 and Dean Harrison's Lightweight win this was the first occasion of father/son winners in different classes during the same race week.


Eviar parametro de view para action

Question: Tenho uma views que lista meus usuarios, está basicamente no padrão gerado pelo asp.net mvc com entity, os dados estão em uma table, e dentro desta table eu tenho um :
@Html.ActionLink("Aprovar cadastro", "Aprovar")

E tenho dentro do controller a Action:
 [HttpGet]
    public ActionResult Aprovar(int? Id)
    {
        if(Id == null){return new HttpStatusCodeResult(HttpStatusCode.BadRequest);}
        else {
               //A função será implementada aqui
        }
    }

Basicamente eu preciso passar a Id de um usuário especifico para este controller, porém não estou obtendo sucesso.
Segue a minha view:
@model IEnumerable<ApegaPet.Models.ApplicationUser>
@{     Layout = "~/Views/Shared/_SideNavbar.cshtml";  }
@{
    ViewBag.Title = "Avaliar_Ong";
}

Avaliar requisição de cadastro de Ongs

            @Html.DisplayNameFor(model => model.nomerazao)

            @Html.DisplayNameFor(model => model.endereco)

            @Html.DisplayNameFor(model => model.telefone)

            @Html.DisplayNameFor(model => model.Name)

            @Html.DisplayNameFor(model => model.Email)

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.nomerazao)

                @Html.DisplayFor(modelItem => item.endereco)

                @Html.DisplayFor(modelItem => item.telefone)

                @Html.DisplayFor(modelItem => item.Name)

                @Html.DisplayFor(modelItem => item.Email)

                @Html.ActionLink("Aprovar cadastro", "Aprovar")

    }

Answer: Tem que passar o terceiro paramento igual está em sua documentação:
@Html.ActionLink("Aprovar cadastro", "Aprovar", new {Id = item.id})

isso se chama sobrecarga de método (overload)
Lista de Sobrecargas:

ActionLink(HtmlHelper, String, String)
ActionLink(HtmlHelper, String, String, Object)
ActionLink(HtmlHelper, String, String, Object, Object)
ActionLink(HtmlHelper, String, String, RouteValueDictionary)
ActionLink(HtmlHelper, String, String, RouteValueDictionary, IDictionary)
ActionLink(HtmlHelper, String, String, String)
ActionLink(HtmlHelper, String, String, String, Object, Object)
ActionLink(HtmlHelper, String, String, String, RouteValueDictionary, IDictionary)
ActionLink(HtmlHelper, String, String, String, String, String, String, Object, Object)
ActionLink(HtmlHelper, String, String, String, String, String, String, RouteValueDictionary, IDictionary)

Referencia: Overload List

Uma observação sobre o seu código no método do controller é que esse dado pode ou não ser passado (int?), ou seja, não é obrigatório precisa talvez averiguar qual é a melhor opção nesse determinado caso.
Referencias:

Método LinkExtensions.ActionLink
Método LinkExtensions.ActionLink (HtmlHelper, String, String, String, RouteValueDictionary, IDictionary)
Comment: Por exemplo, este item.id ele tem que necessariamente estar sendo exibido na view ?
Comment: Não, @ProstetnicVogonJeltz pode ser um número escolhido mediante sua programação, só precisa seguir a mesma nomenclatura de `new { Id =`  onde o valor deve ser um inteiro. Eu coloquei assim pois imaginei que seria ele, mas, pode ser como já dito da sua programação.
Comment: @ProstetnicVogonJeltz vale lembrar que esse Id não é obrigatório, porque a sua regra permite ele ser `null`, olhando pelo `controller` `int? Id`!

Eviar parametro de view para action


Active Record Query Using Associated Model in Find Clause

Question: I'm having a blonde moment and probably a brain freeze.
In my rails3 app, I have users and tasks. My users have many tasks...
I have due and overdue tasks as follows:
@due = Task.find(:all, :conditions => ["dueddate >= ? AND AND status = ?", Date.today, false], :include => :taskcategories, :order => "dueddate asc")

What I want to do in my tasks view, is list the users with due tasks...
For some reason, I can't get my head around it. I have tried this, but it's not working:
@task = Task.all

@user = User.find(:all, :conditions => ["@task.dueddate <= ? AND
@task.status = ?", Date.today + 7.days, false])

I'm sure this is easy, can anyone help me!!?
Answer: I guess this should work
updated
User.joins(:tasks)
    .where("tasks.dueddate <= ? AND tasks.status = ?", Date.today + 7.days, false).group(:id)

This should work with SQLite and MySQL. However, PostgreSQL requires that you supply all the columns of the table. If it's a small table, you could simply type the names. Or you could add this method to the model:
def self.column_list
  self.column_names.collect { |c| "#{self.to_s.pluralize.downcase}.#{c}"}.join(",")
end

and change .group(:id) to .group(User.column_list)
Comment: That's fantastic! Thought I was being stupid, turns out I hadn't done a join before. How is it possible to only display unique values - I can see some duplicate data in there.


${2000\choose1}+{2000\choose4}+{2000\choose7}+\cdots +{2000\choose1996}+{2000\choose1999}=?$

Question: ${2000\choose1}+{2000\choose4}+{2000\choose7}+\cdots +{2000\choose1996}+{2000\choose1999}=?$
Comment: Welcome to MathSE.  When you pose a question here, it is expeced that you include any work you have done on the problem and indicate where you are stuck so that you receive responses that address the specific difficulties you are encountering.
Comment: Is this a definition? Have you called '?' to this number?
Comment: See [this related question](http://math.stackexchange.com/q/213583/11619). There the upstairs value is constrained to be divisible by three, but the technique is the same. [This](http://math.stackexchange.com/q/228481/11619) is another older question on our site. You need to use different roots of unity as multipliers (all explained by discrete Fourier transforms).
Answer: $$(1+x)^n=\sum_{r=0}^n\binom nr x^r$$ where $3\nmid n$
Set $x=1,w,w^2$ where $w$ is a complex cube root of unity
$$P=(1+1)^n=\sum_{r=0}^n\binom nr 1^r$$
$$Q=(1+w)^n=\sum_{r=0}^n\binom nr w^r$$
$$R=(1+w^2)^n=\sum_{r=0}^n\binom nr w^{2r}$$
Find $P+w^2\cdot Q+w\cdot R$
Use $1+w+w^2=0$ to simplify the calculation
Comment: Shouldn't there be a summation sign in R.H.S of these identities?
Comment: @Sry, Sorry for the mistake, rectified. Thanks for your observation.
Comment: How $P+w^2.Q+w.R$ will give me a solution? Please explain.
Comment: @Sry, Just write the expand form for the right hand sides
Answer: a = ${2000\choose1}+{2000\choose4}+{2000\choose7}+\cdots +{2000\choose1996}+{2000\choose1999}$
b = ${2000\choose0}+{2000\choose3}+{2000\choose6}+\cdots +{2000\choose1995}+{2000\choose1998} = {2000\choose2}+{2000\choose5}+{2000\choose8}+\cdots +{2000\choose1997}+{2000\choose2000}$
and that $b = \dfrac{(1+1)^{2000} + (1+\omega)^{2000} + (1+\omega^2)^{2000}}{3}$. where $\omega$ is the primitive third root of unity.  It can be seen that $1+\omega$ is the primitive sixth root of unity and $(1+\omega^2)$ is its inverse
So $(1+\omega)^{2000} = (1+\omega)^2 = \omega$
Similarly $(1+\omega^2)^{2000} = \omega^2$
Therefore, $b = \frac{2^{2000}-1}{3}$
$a+2b = 2^{2000}$
$a = 2^{2000} - 2b$
$a = 2^{2000} - 2\frac{2^{2000}-1}{3} = \frac{2^{2000}+2}{3} = \frac{2^{2000}+2}{3}$


ASP.NET Core MVC OpenIdConnect how do I check if HttpContext.SignOutAsync is allowed?

Question: I'm using OpenIdConnect with Auth0 (via the Microsoft.Identity.Web package) and the call to HttpContext.SignOutAsync(..) fails with an error

InvalidOperationException: Cannot redirect to the end session endpoint, the configuration may be missing or invalid.

This is expected because Auth0's well known configuration does not publish a signout endpoint (which is a bit funky given how hard they push their book on OAuth).
I'm trying to figure out how, if at all, I can get the current OpenIdConnect configuration settings that were loaded from the well known endpoint. I'd like to check for myself if the signout endpoint exists instead of eating the exception.
Plus from a logging/debugging/supporting a raft of other providers I really would like to get the well known settings currently loaded. For example I'm expecting at some point to have to support Broadcom's SiteMinder... which if past experience has taught me anything is going to involve sufficient logging such that I can pass the problem over to my client's technical folks (to either fix or take up with SiteMinder people).
Thanks
Answer: The most standard option is for the OpenID Connect metadata to include an end_session_endpoint. When that is missing you will get the above .NET error by default.
RP Initiated Logout is a draft specification, and some providers have custom implementations. This post discusses Auth0's behaviour, and you will need to build a custom logout URL.
In .NET you can use Events to resolve your issues, and you will need code similar to the following - from this previous answer.
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
  Authority = ...
  ClientId = ...
  Events = new OpenIdConnectEvents()
  {
    OnRedirectToIdentityProviderForSignOut = context =>
    {
      context.IssuerAddress = myAuth0CustomLogoutUrl;
    }
  }
});

The above context also has an Options object that you can use to get the metadata, via its ConfigurationManager property.
Alternatively you can get metadata like this outside of event handlers. This will allow you to detect if the downloaded metadata contains an end session endpoint.
var url = $"{authorityUrl}/.well-known/openid-configuration";
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(url, new OpenIdConnectConfigurationRetriever());
var config = await configManager.GetConfigurationAsync().ConfigureAwait(false);
if (String.IsNullOrWhiteSpace(config.EndSessionEndpoint))
{
  // Do something
}

A more elegant option might be to register the OpenIdConnectOptions object as a singleton, then inject it into the logout controller. You can then access the exact ConfigurationManager instance that the infrastructure is using:
services.AddSingleton(options);

class LogoutController
{
  public LogoutController(OpenIdConnectOptions options)
  {
  }

  public SomeMethod()
  {
    // Use options
  }
}

You can put any custom logging either in the above handler or in OnMessageReceived, which will also fire whenever an OIDC message is received - eg metadata is downloaded.
Comment: I was aware of the event based approach but I could need to drop the settings into cache so that they would be available on the logout page. I'd really rather be able to get the settings that the infrastructure is using. They're have the authoritative settings, and I'd rather rely on them (if you see what I mean). Thanks though.
Comment: Ok - I updated the answer above - see if these suggestions help


PyAudio 'utf8' error when listing devices

Question: When using PyAudio (Portaudio binding) with ASIO+DirectSound support, this code :
import pyaudio

p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
    print p.get_device_info_by_index(i)

... produces this error :
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 1: invalid continuation byte

How can we solve this problem ?

The problem may come from "pyaudio.py", line 990, because of an unsucessful utf8 decoding :
           return {'index' : index,
                    'structVersion' : device_info.structVersion,
                    'name' : device_info.name,

This answer here Special characters in audio devices name : Pyaudio ("don't use PyAudio") is not satisfactory.

Traceback
...
{'defaultSampleRate': 44100.0, 'defaultLowOutputLatency': 0.0, 'defaultLowInputLatency': 0.12, 'maxInputChannels': 2L, 'structVersion': 2L, 'hostApi': 1L, 'index': 8, 'defaultHighOutputLatency': 0.0, 'maxOutputChannels': 0L, 'name': u'Microphone interne (Conexant 20672 SmartAudio HD)', 'defaultHighInputLatency': 0.24}
Traceback (most recent call last):
  File "D:\test\test.py", line 5, in <module>
    print p.get_device_info_by_index(i)
  File "C:\ProgramData\Anaconda\lib\site-packages\pyaudio.py", line 977, in get_device_info_by_index
    pa.get_device_info(device_index)
  File "C:\ProgramData\Anaconda\lib\site-packages\pyaudio.py", line 990, in _make_device_info_dictionary
    'name' : device_info.name,
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 1: invalid continuation byte

Comment: Some patches were posted to the PortAudio mailing list last year which fix some UTF8 device name issues on Windows. (search for "Unicode problems with Windows-build.") They are in the queue to be merged.
Comment: Show the full traceback...
Comment: I added the Traceback @Wooble
Comment: The traceback doesn't match your code, but the error does look internal to pyaudio. Have you tried filing a bug report with them?
Comment: Sorry, I pasted a traceback coming from another file where I had the same problem; now I replaced with the Traceback from the code that I gave here in my question.
Comment: Yes the error is internal to PyAudio, the goal is here to find where the bug is.
Comment: Two things:  1. I cannot reproduce this error on Linux, but of course I also do not have the specific sound card (ASIO).  2. The code in the line of the trace does not contain any hint on why a decoding is attempted.  It is only building a dict there.  That's strange.
Comment: `device_info.name` is a property. `PyUnicode_FromString(PaDeviceInfo.name)` is called when accessing the property. `PaDeviceInfo.name` is supposed to be UTF8 but apparently in this case it is not.
Comment: @RossBencina do you have an idea of how I can solve this for PyAudio as well? I'm a bit new to this (I'm sill unable to compile Portaudio+PyAudio with ASIO+DS at the same time, there are too many steps, and I got too many things to troubleshoot ;) )
Comment: `UnicodeDecodeError` is sadly quite common in Python. Following answer may apply to your specific case:  http://stackoverflow.com/a/19706723/2419207
Comment: Also I'd suggest to tag your post with [`python-2.x`](https://stackoverflow.com/tags/python-2.x) or [`python3.x`](https://stackoverflow.com/tags/python-3.x) depending on what version you are using. As handling encodings has changed a lot in Python 3: http://docs.python.org/3/howto/pyporting.html#str-unicode and http://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit
Answer: The error 'invalid continuation byte' makes me think that the text is corrupt for that particular index.
If you're able to modify the pyaudio.py file (or get the pyaudio.py file to return just the name), you might be able to try handle the UTF-8 decoding yourself by using 'Unicode Dammit'.  It pretty much takes a best guess at what the encoding can be.  Here's a link to their tutorial (http://www.crummy.com/software/BeautifulSoup/bs4/doc/#unicode-dammit)
I think the code would look just like the tutorial:
from bs4 import UnicodeDammit

dammit = UnicodeDammit(audiodevicename)
print(dammit.unicode_markup) ## Wéird Device Name!

Comment: Hell I have no idea if that answer is going to help OP, but +1 for mentioning this library I had no idea about. Nice!
Answer: I've forked pyAudio and modified https://github.com/joelewis/PyAudio/blob/master/src/_portaudiomodule.c code to use
PyUnicode_DecodeFSDefault

instead of
 PyUnicode_FromString

which likely might solve the unicode issue.
See if you could find it helpful.
fork:
https://github.com/joelewis/PyAudio/
Answer: The only successful solution found is :

apply Tobias Erichsen'patch to PortAudio (as mentioned in @RossBencina's comment) that can be found here : https://www.assembla.com/spaces/portaudio/support/tickets/224-patch-for-windows-directsound-and-wmme-utf-8-device-names#/activity/ticket
rebuild the whole thing

Many thanks to @cgohlke for having built new ready-to-use installers :
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio
Answer: I think the clue here is
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 1: invalid continuation byte
For whatever reason something returned by get_device_info_by_index()  (probably the name field) contains the byte 0xe9 which, if you are interpreting the string of bytes as UTF8, signifies a "continuation byte". This means that it expects some valid bytes to follow the 0xe9. valid bytes means some sequence of bytes that constitutes a legitimate UTF8 character. E.g.
http://hexutf8.com/?q=e981a8
uses 0xe9 with some valid continuation bytes.


Diagonalization problems (eigenvalues and vectors)

Question: I am trying to diagonalize the following matrices:
$$A = \begin{pmatrix}0 & 1\\-1 & 2\end{pmatrix}\qquad B = \begin{pmatrix}1 & 2\\-1&-1\end{pmatrix}$$
For matrix $A$, I find an eigenvalue of $1$ with algebraic multiplicity of $2$. I find, though, that the dimension of its eigenspace consists of $1$ vector? Can I still construct a matrix to diagonalize with somehow?
For matrix B, I get the same scenario for eigenvalues (value of $1$ repeated twice), but am unsure if my eigenspace, consisting of $(1,0)$, is correct? Then again, I am left in the same situation.
Are those matrices un-diagonalizable? (spelling?) Can someone help me out?
Thank you.
Comment: But the characteristic polynomial of $B$ is $x^2+1,$ why do you say that $B$ has $1$ as an eigenvalue?
Comment: Calculation: $$char(B)=\det\begin{pmatrix}1-x & 2\\-1&-1-x\end{pmatrix}=x^2-1+2=x^2+1.$$
Comment: No, the second has eigenvalues $\pm i$ and is diagonalizable as my answer shows.
Comment: The characteristic polynomial I got for B is (1-x)^2..
Comment: Yeah you are right, I always have trouble with dealing with factorizing the polynomial to find the eigenvalues. Thank you.
Comment: No problem. And the pleasure is mine.
Comment: On a last note, does B still have only one eigenvalue, which would now be -1? Therefore it wouldn't be diagonalizable, even though it appears to be given the other answers. I think something is going over my head here haha..
Answer: Hints:
The first is not diagonalizable, but we can use the Jordan Normal Form. We get:
$$A = PJP^{-1} =\left(
\begin{array}{cc}
 1 & -1 \\
 1 & 0 \\
\end{array}
\right) \left(
\begin{array}{cc}
 1 & 1 \\
 0 & 1 \\
\end{array}
\right) \left(
\begin{array}{cc}
 0 & 1 \\
 -1 & 1 \\
\end{array}
\right)$$
The second is diagonalizable and we get:
$$A = PJP^{-1} = \left(
\begin{array}{cc}
 i-1 & -i-1 \\
 1 & 1 \\
\end{array}
\right) \left(
\begin{array}{cc}
 -i & 0 \\
 0 & i \\
\end{array}
\right) \left(
\begin{array}{cc}
 \frac{1}{2 i} & \frac{i+1}{2 i} \\
 -\frac{1}{2 i} & \frac{i-1}{2 i} \\
\end{array}
\right)$$
Comment: Here is a nice write-up for the 2x2 case: http://math.berkeley.edu/~ogus/old/Math_54-05/webfoils/jordan.pdf
Comment: When you say "you can use Jordan Normal Form," that means that the matrix is not diagonalizable, right?
Comment: Ok.  (My LA class did not cover Jordan normal form, so I didn't know if that could be considered a special case of diagonal, or not...)
Answer: If you have an eigenvalue with multiplicity n, then you must have n linearly independent eigenvectors from that eigenvalue in order for the matrix to be diagonalizable.


Prove that either $f(x) = ax + b$ for all $x \in [0,1]$ for some constants $a,b \in \mathbb{R}$ or $t \in (0,1)$ such that $|f(1) - f(0)| < |f'(t)|$

Question:
Let $f \colon [0,1] \to \mathbb{R}$ be a continuous function which is differentiable on $(0,1)$. Prove that either $f(x) = ax + b$ for all $x \in [0,1]$ for some constants $a,b \in \mathbb{R}$ or there exists $t \in (0,1)$ such that $|f(1) - f(0)| < |f'(t)|$.

I have found a solution of this problem here:

If $f(0)=f(1)$, we are done by Rolle's Theorem, hence assume $f(0)\neq f(1)$ and consider $g(x)=\frac{f(x)-f(0)}{f(1)-f(0)}$, which is continuous, differentiable and satisfies $g(0)=0$, $g(1)=1$ and $g'(x)=\frac{f'(x)}{f(1)-f(0)}$. Therefore we may assume $f(0)=0$ and $f(1)=1$, and we wish to prove that there exists $t\in (0,1)$ such that $|f'(t)|>1$. If $f(t)>t$ or $f(t)<t$ for some $t\in (0,1)$, we are done by MVT on $(0,t)$ or $(t,1)$, respectively. Else $f(x)=x$ for all $x\in (0,1)$, so $f$ is linear.

Here they took the function $g(x)=\frac{f(x)-f(0)}{f(1)-f(0)}$ into consideration. What might have been the motivation behind it?
How did they assume $f(0)=0$ and $f(1)=1$?
Comment: I think it is just a trick. You can assume it, because if you prove the result for $g$ you would have the result for $f$. So, I does not matter if you assume it or not. If you don't have those equalities, than you prove the result for $g$ and then you have for $f$.
Comment: @YgorArthur are you talking about 2?
Comment: both haha First "I think it is just a trick" was for 1.
Answer: The idea, with both of your questions, is to reduce the general case for $f$ (where we assume $f$ is continuous on $[0, 1]$ and differentiable on $(0, 1)$) to a more specific case (where we assume all of the above and $f(0) = 0$ and $f(1) = 1$).
The first part of the proof is about taking a general $f$ satisfying these conditions, and constructing a $g$ that also satisfies the conditions, as well as $g(0) = 0$ and $g(1) = 1$. Moreover, we want it to be clear that, if the conclusion holds for $g$, then the conclusion holds for $f$. So, if we can prove the specific case (i.e. where $f(0) = 0$ and $f(1) = 1$), then we can apply it to $g$, and that should make the result hold for $f$.
What's a little lacking from this proof is the crucial step where the property holding for $g$ implies the property holds for $f$. So, let's assume the second part of the proof holds true, and we now know that $g(x) = ax + b$ for some $a, b$ (indeed, the proof says $g(x) = x$ specifically) or some $t \in [0, 1]$ exists such that $|g'(t)| > |g(1) - g(0)| = 1$. If it's the former, then
$$f(x) = (f(1) - f(0))g(t) + f(0) = (f(1) - f(0))x + f(0),$$
i.e. of the form $ax + b$, as required. Otherwise, assuming the latter, then using the same $t$,
$$|f'(t)| = |f(1) - f(0)| \cdot \left|\frac{f'(t)}{f(1) - f(0)}\right| = |f(1) - f(0)| \cdot |g'(t)| > |f(1) - f(0)|,$$
since $f(1) - f(0) \neq 0$. Thus, if the property holds for $g$, it holds for $f$. So, proving the result for functions like $g$, that are continuous on $[0, 1]$ and differentiable on $(0, 1)$, but also have $g(0) = 0$ and $g(1) = 1$, will prove the same result for the more general functions.
Hopefully this answers your second question: we might as well make the new assumption that $f(0) = 0$ and $g(1) = 1$, because proving for this special case is actually a proof for the general case.
As for your first question, the function $g(x) = \frac{f(x) - f(0)}{f(1) - f(0)}$ is the result of normalising the graph of $f$ so that it begins at $(0, 0)$ and ends at $(1, 1)$ (so if the function is a line, it would have to be $x$, as used in the proof). If we first subtract $f(0)$ from $f(x)$, i.e. let $h(x) = f(x) - f(0)$, this produces the same graph as $f$, but shifted vertically so that it begins at $(0, 0)$ - note that $h(0) = f(0) - f(0) = 0$.
Then dividing by letting $g(x) = \frac{f(x) - f(0)}{f(1) - f(0)} = \frac{h(x)}{h(1)}$, we are then taking the graph of $h$, and scaling it vertically so that $g(1) = 1$ (while still having $g(0) = h(0)/h(1) = 0$).
Note that neither adding a constant or scaling vertically will affect the result. Adding a constant will be eliminated from differentiation, will be cancelled when taking $f(1) - f(0)$, and won't interfere with the $ax + b$ form (it will just change the constant $b$). Scaling vertically will introduce a scalar that will cancel from both sides of $|f'(t)| > |f(1) - f(0)|$, and will simply modify the $a$ in $ax + b$. Since both of these operations are "free" for us to do, in a sense, we might as well use them to make the problem more simple.