Enviar um array em JSON com aspas simples

Question: Estou fazendo integração de uma api em Laravel, tenho que enviar um POST segundo a documentação da api com o seguinte body
<code>{
      "token": "TOKEN DA APLICACAO",
      "email": "firstname.lastname@example.com",
      "frete": "0",
      "carrinho": '[{
                  "produto":"Produto 1",
                  "quantidade":"1",
                  "preco":"10.92",
                  "imagem":"http://site.com.br/foto.jpg",
                  "url":"http://site.com.br/produto"
                  }]'
  }
</code>
porem,o body que estou enviando é assim
<code>{"token":"xxxxxxx","email":"firstname.lastname@example.com","frete":"0","carrinho":[{"produto":"computador","quantidade":"1","preco":"3000.00","imagem":"http:site.com.br/foto.jpg","url":"http//loja.dooca.local/computador"}]}
</code>
eu estou populando esse array da seguinte forma:
<code> $checkouts = [
                'token' => 'xxxxxx'),
                'email' => $checkout->getCustomer()->getEmail(),
                'frete' => '0',
                'carrinho' => [],
            ];

            foreach ($checkout->getItems() as $item) {
                $checkouts['carrinho'][] = [
                    'produto' => $item->getName(),
                    'quantidade' => strval($item->getQuantity()),
                    'preco' => $item->getPrice(),
                    'imagem' => 'http://site.com.br/foto.jpg',
                    'url' => $item->getUrl(),

               ];
</code>
O problema é que essa api só aceita se na parte do carrinho tiver aspas simples antes dos colchetes e não consigo botar de jeito nenhum...
como por exemplo assim  "carrinho": '[{
Comment: Não tem sentido, como já "diziam", **algo de errado não está certo**, se `carrinho:` precisa receber uma "STRING" com um formato de JSON ou é porque o autor da API fez algo gravíssimo. Como você não apresentou a parte do envio e nem como usou o json_encode então não tem como ninguém lhe responder de forma razoavel, e não posso chutar uma resposta, afinal o site não é para isto. Dê mais detalhes.
Comment: Exatamente, na documentação só é aceito o envio do body nesse molde:
  {
      "token": "TOKEN DA APLICACAO",
      "email": "email@example.com",
      "frete": "0",
      "carrinho": '[{
                  "produto":"Produto 1",
                  "quantidade":"1",
                  "preco":"10.92",
                  "imagem":"http://site.com.br/foto.jpg",
                  "url":"http://site.com.br/produto"
                  }]'
  }

O envio esta assim:

Api::enviou()->checkout()->post($checkouts);
estou mandando aquele array acima..que seria o certo..
Comment: Eu não tenho acesso a tal documentação para saber se é isto ou se você entendeu algo errado, e não adicione códigos no campo de "comentários", olha na pergunta, tem um link chamado "editar", corrija a pergunta com os detalhes minimos que faltam para podermos entender o problema, não vai adiantar eu ficar chutando respostas igual a quem já respondeu, pra se ter uma resposta você tem que "nos ajudar" a ajuda-lo, mostra o que fez de forma compreensivel, pedaços soltos de códigos que não fazem nada não ajudarão.
Answer: Olá, tudo bem?
Veja se isso ajuda você.
<code>$array = [];

for($i = 0; $i < 10; $i++){
    $array[] = [
        'produto' => 'nome item',
        'quantidade' => 12,
        'preco' => 12.12,
        'imagem' => 'http://site.com.br/foto.jpg',
        'url' => 'http://site.com.br/',
    ];
}

$carrinho = json_encode($array);

$checkouts = [
    'token' => 'xxx',
    'email' => 'email@example.com',
    'frete' => '0',
    'carrinho' => "$carrinho"
];
</code>
Saída
<code>array(4) {
  ["token"]=>
  string(3) "xxx"
  ["email"]=>
  string(21) "firstname.lastname@example.com"
  ["frete"]=>
  string(1) "0"
  ["carrinho"]=>
  string(1271) "[{"produto":"nome item","quantidade":12,"preco":12.12,"imagem":"http:\/\/site.com.br\/foto.jpg","url":"http:\/\/site.com.br\/"},{"produto":"nome item","quantidade":12,"preco":12.12,"imagem":"http:\/\/site.com.br\/foto.jpg","url":"http:\/\/site.com.br\/"},{"produto":"nome item","quantidade":12,"preco":12.12,"imagem":"http:\/\/site.com.br\/foto.jpg","url":"http:\/\/site.com.br\/"},{"produto":"nome item","quantidade":12,"preco":12.12,"imagem":"http:\/\/site.com.br\/foto.jpg","url":"http:\/\/site.com.br\/"},{"produto":"nome item","quantidade":12,"preco":12.12,"imagem":"http:\/\/site.com.br\/foto.jpg","url":"http:\/\/site.com.br\/"},{"produto":"nome item","quantidade":12,"preco":12.12,"imagem":"http:\/\/site.com.br\/foto.jpg","url":"http:\/\/site.com.br\/"},{"produto":"nome item","quantidade":12,"preco":12.12,"imagem":"http:\/\/site.com.br\/foto.jpg","url":"http:\/\/site.com.br\/"},{"produto":"nome item","quantidade":12,"preco":12.12,"imagem":"http:\/\/site.com.br\/foto.jpg","url":"http:\/\/site.com.br\/"},{"produto":"nome item","quantidade":12,"preco":12.12,"imagem":"http:\/\/site.com.br\/foto.jpg","url":"http:\/\/site.com.br\/"},{"produto":"nome item","quantidade":12,"preco":12.12,"imagem":"http:\/\/site.com.br\/foto.jpg","url":"http:\/\/site.com.br\/"}]"
}
</code>
Comment: Boa noite, ajudou em partes... consegui deixar o ["carrinho"] como eu gostaria... porem ele fica exatamente como vc postou, mas a API que estou integrando, o cara fez totalmente errado e antes do colchete nessa parte aqui `"[{"produto" :` ele não aceita essas aspas duplas... e nisso que estou com dificuldade
Comment: Coloque assim, 'carrinho' => "'$carrinho'"
Comment: O pessoal da API arrumou o jeito de receber as informações, e apenas com a sua primeira resposta solucionou meu caso, obrigado
Comment: Que bom ter ajudado.


Adding node labels to bokeh network plots

Question: I am using the following code to produce an interactive bokeh network graph. How do I add the name of the nodes to the nodes in the bokeh plot?
from bokeh.io import show, output_notebook
from bokeh.models import Plot, Range1d, MultiLine, Circle, HoverTool, TapTool, BoxSelectTool
from bokeh.models.graphs import from_networkx, NodesAndLinkedEdges, EdgesAndLinkedNodes
from bokeh.palettes import Spectral4
from bokeh.models import LabelSet

plot = Plot(plot_width=900, plot_height=500,
            x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
plot.title.text = "Graph Interaction Demonstration"

plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())

graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0,0))

graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])
graph_renderer.node_renderer.glyph.properties_with_values()
graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = EdgesAndLinkedNodes()

plot.renderers.append(graph_renderer)

show(plot)

resulting bokeh networkx graph:
Answer: I guess you mean interactive labels for the nodes, something I also wanted to do. To achieve this, you need to modify a couple of lines:
hover = HoverTool(tooltips=[("Name:", "@name")])
plot.add_tools(hover, TapTool(), BoxSelectTool(), WheelZoomTool())
...
graph_renderer.inspection_policy = NodesAndLinkedEdges()

Then modify the data source for the nodes:
graph_renderer.node_renderer.data_source.data['name'] = [name1, ... ,nameN]

(the data source already exists; it's a dictionary for which the only key is 'index', a numbered list of nodes. Thus you can add more keys that reference lists of the same length - such as a list of names - and these lists can be accessed via '@key')
Comment: @PaulBrown When I give `graph_renderer.inspection_policy = NodesAndLinkedEdges()`, I lose the ability to hover over an edge to highlight it. To have this functionality, I need to set  `graph_renderer.inspection_policy = EdgesAndLinkedNodes()`; but if I do so, I lose the info that appears on hovering over the nodes - they appear as "`???`". How do I fix this?
Comment: I discovered that graph_renderer.node_renderer.data_source.data is a dict with and entry "index" whose value was a list of nodenames from when I created the network.  Thus hover = HoverTool(tooltips=[('','@index')]) was all I needed.
Answer: I found @SergioLucero's answer too incomplete to answer the question, the code sample is not working.
However, with code and answer created by @ifearthenight (from this question: Lining up labels with the nodes on a Bokeh figure generated from a NetworkX graph) I was able to produce a working example.
from bokeh.io import show, output_notebook
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, LabelSet
from bokeh.models.graphs import from_networkx
output_notebook()

G = nx.karate_club_graph()

plot = figure(title="Karate Club Graph", tools="", x_range=(-1.5, 1.5),
          y_range=(-1.5, 1.5), toolbar_location=None)
graph = from_networkx(G, nx.spring_layout)
plot.renderers.append(graph)

x, y = zip(*graph.layout_provider.graph_layout.values())
node_labels = nx.get_node_attributes(G, 'club')
source = ColumnDataSource({'x': x, 'y': y,
                           'club': [node_labels[i] for i in range(len(x))]})
labels = LabelSet(x='x', y='y', text='club', source=source,
                  background_fill_color='white')

plot.renderers.append(labels)
show(plot)

Comment: Replace `range(len(x))` with `graph.layout_provider.graph_layout` (`.keys()`) if your graph keys is not ordered consecutive numeric starting from 0.
Answer: Hot topic!! I think I just got it. They may be more pythonic ways, but what I did was

Create a DataSource with the relevant labels
Retrieve positions from the graph using pos = nx.circular_layout(G)
add these positions to my Datasource
Create a LabelSet from the positions and the source

Leonardo, you are missing the line where G gets created. I took the karate_club_graph and this works for me:
from bokeh.models import ColumnDataSource
pos = nx.circular_layout(G)
x,y=zip(*pos.values())

source = ColumnDataSource({'x':x,'y':y,'kid':['Joe %d' %ix for ix in range(len(x))]})
labels = LabelSet(x='x', y='y', text='kid', source=source)

plot.renderers.append(labels)

Comment: While this question is pretty old, I found it still helpful. However, in order to get the actual values one needs to query them from the layout provider. This answer calls the provider again, which can result in a different layout calculated with different positions.
To get the values used, this snippet works:
`x, y = zip(*graph.layout_provider.graph_layout.values())`


Addressing multicollinearity when removing or imputing is not an option

Question: I'm working on a project where the goal is to predict sales of certain generic products. There are many features, but social media metrics are causing me currently some headache. Social media metrics are a decent indicator of success. I have data related to Twitter and Facebook. The count of 'likes' seems to be a quite simple but effective feature in this context. However, not all products are marketed on both platforms. ~50% of observations are present on both platforms. ~80% in Facebook and ~60% in Twitter. ~10% are not present on either platform.
The VIF for both variables is <2. The pearson correlation coefficient is 0.68. If I put them into the same OLS regression model, Twitter has negative coefficient, while Facebook remains positive. In separate models both are positive and significant.
What I have tried:

If I remove the NaN rows the model will work only on 50% of cases.
If I filled the NaN values with 0 it creates a huge penalty for the products that are only present in Twitter, as the coefficient is negative if both variables are present in model.
Summing the values is not a solution either, because the Twitter follower numbers tend to be about twice bigger.

What I have not tried:

Use standard scaler and then sum the values?

Current solution:
What I have done so far is creating a new variables social_media_audience_size which is a a linear combination of the two features based on the univariate beta coefficients as multipliers. y = ax_1  + bx_2 a and b are the coefficient of Facebook likes and Twitter followers. However, I'm not sure if this is an appropriate solution to my problem.
Questions:
What could be a generally accepted way to address the specified issue?
Also, does this problem have a name? I'm having hard time finding any sources dealing with this issue, but I don't see why this would be very unique problem. I would also be interested in any of academic references where this problem is addressed!
Finally, I'm not entirely sure if my variables even are multicollinear, considering that the VIF is small? How should I analyze and report multicollinearity in case there is small VIF?
Answer: First of all, if the VIF for both variables is under 2, then this is not a problem of multicolinearity. Neither is this an issue of "missing data" due to item nonresponse or anything like that. Instead, it sounds like your "problem" is just that the world works in a particular way: you are trying to predict success as a function of "likes" on various social media platforms, but if a product wasn't promoted on (say) twitter than the "likes" variable is (understandably) undefined. This is a not a statistical problem that you can solve with statistical tests but THEORIETICAL problem that you need to solve by thinking about what you are trying to do. Different approaches to this issue reflect different research questions and ways of thinking about what you are trying to do.
If you don't do anything to the missing values but run a model with both "facebook likes" and "twitter likes" in it, then the model will only contain products that were marketed on BOTH platforms, and it will tell you the impact of twitter likes CONTROLING for facebook likes (in other words, what would be the impact of having one more twitter like, holding facebook likes constant). If what you are trying to do is predict the relative importance of twitter or facebook likes, then this actually seems like a good model, because it limits the sample to products that were advertised on both (making it a "fair" comparison) and tries to find the effect of each kind of like, net of the other.
On the other hand if you replace the "NaN" on likes with zero for a product that wasn't marketed on a platform then, this reflects a view that "if you don't market a product on twitter then by definition the numbers of likes you get on it it zero." So yes it "penalizes" companies that don't market on twitter (or facebook) but maybe it should: in real life it is TRUE that you can't get likes on a platform if you don't promote on it right? So if you just want to know the extent to which "likes" predict success, and you want to acknowledge the real world fact that likes require promotion in the first place, then this might actually be a fine model.
In short: what you describe isn't really a "problem" but just the general issue of "how do I set up my data to make sure I'm answering the right research question." And there is no one answer: it depends on what research question you are trying to answer, and your background "theories" about how you are thinking about the various issues. So the solution here is to just think hard about the substantive implications of making different choices here, and choose the approach that most reflects the assumptions you want to make and the question you are trying to answer. I know that's unsatisfying but that's how stats works in practice.
Comment: About the first point, I've understood that regardless of low VIF, there can be multicollinearity. "The lower precision, switched signs, and a lack of statistical significance are typical problems associated with multicollinearity.". In the OLS model, if both variables are included Twitter follower coefficient turns negative and becomes insignificant. Can I really trust that there is no multicollinearity?
Comment: I think you are confusing multicolinearity with just "correlation." We expect that independent variables in a regression will be correlated with one another to some extent - that's why we need regression in the first place. Multicolinearity is just what happens when that correlation becomes SO high that it becomes meaningless to try and talk about the effect of one variable "controlling" for the other, because both are functionally measuring the same thing. That's clearly not the case here, either according to the VIF or conceptually.
Comment: Thank you again. Would the correct interpretation be that multicollinearity == high VIF? That variance of one variable is excessively explained by another one? The r2 for a model only (tw_likes ~ fb_likes) including those variables is 0.467, which then simply means that there is no multicollinearity issue, end of story.

About the rest of the comment, I agree with the sentiment. My goal is to predict and I struggle with making a model which works with "missing data". I guess this is also something I should reconsider?
Comment: A high VIF (like higher than 5 or 10) is a measure of multicolinearity yes. There isn't any simple relationship between R2 and multicolineairty one way or the other. But I really don't think multicolinearity is what you should be worried about in this problem. Your problem is missing data, and you have to decide conceptually what that missing data means....
Comment: ...sometimes missing data means "zero" (if people are missing values for "how many years of college did you attend" because earlier in the survey they said didn't go to college), and sometimes missing data means "not applicable" ("what color is you cat?" if you don't have a cat") and sometimes it means "value unknown" (if you ask someone their income and they just refuse to answer). Each of those kinds of data needs to be dealt with in a different way. You just need to decide whether to treat "missing twitter likes because wasn't promoted on twitter"  as "zero" or "not applicable."
Answer: This is not necessarily a complex problem, but unfortunately there are no specific solutions as well. There are many different approaches that you can take which depend on your dataset and your aims.
If you intend to create a composite index to address your problem (which is my preferred method in your problem as well), this can be a valid method but certain assumptions need to be met. First of all, I suggest you check out the "Handbook on Constructing Composite Indicators" by the OECD: https://www.oecd.org/sdd/42495745.pdf . There must be a theoratical basis for how you create your composite index which depends on your planned analysis and your aims.
What I can suggest, is creating a new composite index based on the guidelines provided in the above link. Also, I suggest you create a weight variable and weight your new index based on the number of available social media data (1,2,3 or none).
Check other solutions for addressing high multicollinearity as well. This blog has a good summary: link
Response to edit:
When including both variables causes a reversal of signs, which is the case here, multicollinearity is causing significant influence on the coefficients. Depending on what you want to do with your model, this can be an indicator that you need to deal with it.
Comment: Thank you for the answer! I will check out the proposed links.

I just wanted to notify that I modified the question slightly before I saw your response. I found out that I had calculated the VIF using statsmodels without constant, which resulted in high VIF. After adding the constant the VIF is small. I'm slightly perplexed about the multicollinearity now. Anyways, I will probably find an answer to this also from the links.
Comment: I updated my answer regarding your edit.


Chrome :-internal-autofill-selected overwrite

Question: How can I (with css) overwrite Chrome's default class for input:-internal-autofill-selected ?
Using body input:-internal-autofill-selected does display as being used, but the <input is still actually white instead of pink...
body input:-internal-autofill-selected {
    background-color: pink !important;
}

This is how it looks in chrome, but as stated the background-color is still white
Answer: from your question i'm not 100% sure what you're trying to achieve, set the color to the one you prefer or to get rid of the default blue background perhaps?
if you're trying to change the color to custom one you can add this declaration to your CSS rule:
box-shadow: 0 0 0 1000px pink inset;

the solution below worked for me to get rid of default blue background instead of trying to overwrite it to white using background color property.
-webkit-background-clip: text;
background-clip: text;

Comment: Overwrite the default (internal) chrome class that is: **body input:-internal-autofill-selected** and set it to pink


How to change the switch statement below to polymorphism in javascript and also how to access the different classes

Question: let type = document.querySelector('#productType');
type.addEventListener('change', function() {

  switch (type.value) {
    case 'DVD':
      document.querySelector('.DVD').classList.add('visible');
      document.querySelector('.Furniture').classList.remove('visible');
      document.querySelector('.Book').classList.remove('visible');
      break;

    case 'Furniture':
      document.querySelector('.Furniture').classList.add('visible');
      document.querySelector('.DVD').classList.remove('visible');
      document.querySelector('.Book').classList.remove('visible');

      break;

    case 'Book':
      document.querySelector('.Book').classList.add('visible');
      document.querySelector('.Furniture').classList.remove('visible');
      document.querySelector('.DVD').classList.remove('visible');
      break;

  }
})

Answer: You could take an array of ids and update the wanted value with a single loop
ids = ['DVD', 'Furniture', 'Book'];

// update
ids.forEach(id => document.querySelector(id).classList[id === value
    ? 'add'
    : 'remove'
]('visible'));

Comment: I would like to avoid any form of conditional statement by using polymorphism


How to construct non-copyable object in vector of tuples?

Question: I have a non-copyable class A that I want to move into a vector of tuples (see code below). I understand why the code below is not working, but I'm wondering if there is a clever way to make it work without changing the implementation of my class. Any help is greatly appreciated. Thanks :)
#include <iostream>
#include <vector>
#include <tuple>

class A {
    public:
    int val1;
    int val2;

    A(int v1, int v2): val1(v1), val2(v2) {}

    // make non-copyable
    A(const A &other) = delete;
    A &operator=(const A &other) = delete;
};

int main() {
    std::vector<std::tuple<int, int, A>> my_as;

    my_as.emplace_back(4, 3, A(4, 2)); // Error, how to fix this?

    return 0;
}

Comment: I take it you are against or can't make `A` moveable?
Answer: One possible way to solve this may be to use unique pointers like this.

#include <iostream>
#include <vector>
#include <tuple>
#include <memory>

class A {
    public:
    int val1;
    int val2;

    A(int v1, int v2): val1(v1), val2(v2) {}

    // make non-copyable
    A(const A &other) = delete;
    A &operator=(const A &other) = delete;
};

int main() {
    std::vector<std::tuple<int, int, std::unique_ptr>> my_as;

    my_as.emplace_back(4, 3, std::make_unique(4, 2));
    return 0;
}

Comment: This also allows the vector to grow, which is a nice feature.


Recreating a media_gallery using a view?

Question: I have a site that includes a photo gallery, using the Media Gallery module. I am now trying to create a mobile site, and the media gallery page, and all of the galleries look horrible on mobile (I'm using the Mobile Jquery theme.) I am trying to create my own view displaying all of the galleries, and a view displaying each image (depending on the photo gallery) I have seen tutorials on how to create a photo gallery from scratch using content, but the media gallery doesn't seem to create individual nodes for each image. How do I make a view for the media galleries, and out of curiosity, how does the media_gallery module its self work?
Answer: I haven't used Media Gallery, but have used a few others - they all do similar things though often in quite different ways.
First off, it's not really necessary to create a new node for each image - Image Field can contain multiple images, depending on its configuration.
I recently created a Gallery content type with two image fields - one for the gallery "cover" with a single image and one with unlimited images allowed, for the gallery contents. I then used Views to create a View with several Page displays (one to display a list of galleries, another to display each gallery's contents), along with the Colorbox module for image display in a lightbox, and the Plup module (and plupload jquery plugin) to do drag and drop all-at-once uploads into the gallery. Works like a champ and very easy for site maintainers to deal with - all they have to do is upload a "cover" image, drag the whole mess o' images into the plupload area, give it a title, and save it.
Doing it this way lets you leverage image styles in several places - the cover image, the gallery page images, and the colorbox display images - plus Colorbox makes it possible to set up the gallery slideshow as automatic or manual advance. Pretty cool, and no custom code to write. You can fiddle with the View's output options as needed and, should you need more styling action, you have the option of writing theme templates to get the output looking the way you need it.
You can see it at work at http://betheldrupal.m-so.com/galleries - not in production yet but working well so far...
Let me know if you want details - I can export the views and stuff if need be.
Answer: In Views, choose to display Fields. And under Fields, add the media_gallery_media, uncheck "multiple...", because each media_gallery_media field contains many images.


Symmetric and Idempotent matrices multiplication

Question: Let $Q$ be a projection matrix, thus symmetric and idempotent, and $W$ symmetric semidefinite positive matrix.
Prove:
$Q^{T}WQ = WQ$
If the product $WQ$ commutes, the proof is straightforward, because $Q$ is idempotent, but I do not know how to prove it.
Comment: A projection matrix need not be symmetric, e.g. let $Q=\begin{pmatrix}0 & 1 \\ 0 & 1\end{pmatrix}$. If not, the equality does not hold (take the $Q$ above and $W$ the identity matrix).
Answer: Even if $Q=Q^T$, which may not hold (see my comment above), this does not hold in general. Take for instance
$$Q=\begin{pmatrix} 1 & 1\\ 1 & 1 \end{pmatrix}, \; W=\begin{pmatrix} 1 & 0\\ 0 & 2 \end{pmatrix}.$$
Then $Q^T W Q = 3 Q$, while $WQ = \begin{pmatrix} 1 & 1\\ 2 & 2 \end{pmatrix}$.
On the other hand, as noted, it holds if we also assume that $W$ and $Q$ commute.


Best test to use

Question: Suppose a group of people are exposed to some chemical for $20$ minutes. Their heart rate is measured before being exposed. The exposure to the chemical seems to cause their heart rate to speed up. What test can be used to precisely find the point where the heart rate differs significantly from baseline? A paired t-test?
Comment: I figured it out: A changepoint analysis would be good.
Answer: Depending on what you want to know, a paired $t$-test may or may not be a reasonable choice.
Suppose your experiment works like this:

Measure subjects' heart rates.
Expose them to substance X for 20 minutes.
Measure their heart rates again.

A paired $t$-test would be an ideal choice for asking whether subjects' heart rates differed between Steps 1 and 3. This is a simple within-subjects design and using a paired $t$-test allows you to control for fact that subjects may have very different resting heart rates, depending on age, sex, fitness, etc.
On the other hand, suppose you running a slightly different experiment, like this:

Hook subjects up to a heart-rate monitor
Expose them to substance X for up to 20 minutes.
Continuously monitor their heart rates.

and you are asking whether substance X has an effect at all, and, if so, the effect's latency (i.e., how long it takes). This is a somewhat thornier problem. The naive solution might be to bin your data into, say,  1 minute intervals and then whether the heart rate at time=1 minute is different from baseline, time=2 minutes vs. baseline, and so on, each of these via a paired $t$-test.
That's not totally unreasonable, but you need to control for multiple comparisons; if you perform 20 $t$-tests with a threshold of $p<0.05$, you should expect to see one significant difference by chance alone. There are various ways of doing this (search for "multiple comparisons correction") depending on exactly what you want to control. I have seen people argue for accepting two successive time points, each of which is individually significant at $p<0.05$, as indicating a significant deviation. The logic here is that, assuming the observations are independent, the chance of seeing two consecutive significant-but-spurious results is (0.05)^2, which is probably acceptably small. Seems reasonable enough, but I'd love others' opinions on that.
Another alternative would be to fit a model to your data. If you know that the drug leads to a 20% increase vs. baseline, maybe you could fit a sigmoid with a delay parameter to each of your observations.
There are lots of other approaches--this has been extensively studied under the name "change-point analysis", and many of the popular tests are available in an R package. However, be careful and read the documentation carefully; as someone else said here recently "The large print giveth and the small print taketh away" and the devil really is in the details here, so be careful.
Comment: Great answer! I suspect the multiple comparison issue is going to be a problem, depending on how many time points you're looking at, but I bet fitting a model would give you some interesting results!

Best test to use


EXEC MASTER.DBO.XP_CMDSHELL MOVE

Question: I am working on a FILE that I need to move from one loacation to another, but when I run the code below I keep getting an error that it has the incorrect syntax. When I print the @Move statement I get this: (Which is what I think I should get)
MOVE \appdev1\sqltest\RedFlag\RedFlag Address Change New Debit Issued.pdf \appdev1\sqltest\RedFlag\2013-10-24_REDFLAG_.pdf
I am trying to run it like this:
EXEC MASTER.DBO.XP_CMDSHELL @MOVE

Any suggestions on what I am doing wrong? Do I need to add the ' in front of the Move statement?
Answer: You have spaces in your paths/filenames, so you need to surround with double quotes.
SET @MOVE = 'MOVE "\\appdev1\... Issued.pdf" "\\appdev1\..._.pdf"';

If you are constructing a path from variables, this doesn't change anything. Staying in T-SQL, you would have parameters like this I presume:
SET @MOVE = 'MOVE "' + @OldFile + '" "' + @Printed + '"';

You'll have to work it out yourself if you are doing this in some other language. Here is a short demonstration of how it works in T-SQL:
DECLARE @MOVE VARCHAR(255),
  @OldFile VARCHAR(255) = '\\foo\some filename.pdf',
  @Printed VARCHAR(244) = '\\blat\something else.pdf';

SET @MOVE = 'MOVE "' + @OldFile + '" "' + @Printed + '"';

PRINT @MOVE;

Results:
MOVE "\\foo\some filename.pdf" "\\blat\something else.pdf"

I don't see any extra quotes, so maybe those are coming from whatever value you have in your parameters.
Comment: The Move(parameter) is actually setup using the variables. so it is like set Move(parameter) = 'Move ' + _OldFile + ' ' + _Printed
Comment: I'm not doing it any other language, I just didnt see the bottom part of your answer, which still gave me too many quotes. I really think the smart comments could have been left behind though, I just came on here for help.
Comment: @user2084896 I don't understand what you mean by "too many quotes" - and I presumed it was a different language because you can't have a parameter named `_OldFile` in T-SQL. So, what does `_OldFile` contain?
Comment: @user2084896 And yes, you came on here for help. For free, I might add. But you have to show a little effort on your side, and don't really have a lot of room to complain. You're the one who needs to solve a problem, not the people who are taking time out of their day to help you.

EXEC MASTER.DBO.XP_CMDSHELL MOVE


$k^*/k^{*2}$ is a vector space?

Question: I am reading about Hilbert symbols in Serre's A Course in Arithmetic. Let $k$ denote either the reals, $R,$ or the field $Q_p$ of $p$-adic numbers. I can see how the Hilbert symbol is a map from $k^*/k^{*2} \times k^*/k^{*2}$ to $\{\pm 1\}.$ However, Serre says that $k^*/k^{*2}$ is a vector space over $F_2?$ First of all, I don't think it has an additive abelian group structure on it. Elements are of the form $ak^{*2}, a \in k^*.$ And clearly $ak^{*2} - ak^{*2} = 0k^{*2} \notin k^{*2}.$
Comment: Yes, $k^*$ is the multiplicative group. But doesn't it need to be addition? Or does addition represent just a commutative binary operation when stated as part of the vector space axioms.
Comment: Right, we just treat abelian groups as "additive" as a convention.  It can be any operation that satisfies the group axioms.  Here taking the quotient allows the natural "group action" of $\mathbb Z$ to be interpreted as exponentiation on the field elements, and then modding out by $2$ works (because of the quotient).
Comment: I'm guessing that $k^*$ means the multiplicative group of nonzero elements in the field, so it is an abelian group and also the quotient $k^*/k^{*2}$ as well.
Comment: Wow thanks a lot!
Comment: If you have the energy, why not write up an Answer for your own Question?  There's a reasonable chance it will help someone else in the future.
Answer: Apparently vector spaces don't require 'addition' in the conventional sense, but rather in regards to group property, must be an abelian group. Clearly, $k^*$ is an abelian group by multiplication. Hence, the quotient group $k^*/k^{*2}$ is an abelian group by multiplication as well. The scalar property of $F_2$ determines the exponent. That is, $0 \cdot a = a^0, 1 \cdot a = a^1$ and modding out by 2 works out because we are modding the quotient by $k^{*2}.$ It should be clear from this that the quotient is an $F_2$ vector space.

$k^*/k^{*2}$ is a vector space?


How to show text fields from a User object to anonymous users without "View User Profile" permission?

Question: I have a few basic fields on the user object to display "Author Bio" cards at the bottom of articles. It seems that anonymous users cannot see any of this information.
All I want to do is show first name, last name, phone number and email address. Is this hidden away because it requires "View User Profile" permission? How can I get around enabling that? I don't want to enable that if I don't have to. Conversely, how I can prevent anyone from getting to user/* pages?
Is there something I can change in the render array to change the access check?
Comment: Attaching a View to the content type with [EVA](https://www.drupal.org/project/eva) and providing the node author for a contextual filter?
Comment: Hmmm... so it's already a View Block in a region on the page, let me check the settings
Comment: The EVA display would be if you want to include this in a view mode of the content type (can be displayed in multiple nodes on the same page). A view block display with a contextual filter is OK, if you want to display this for the author of the current node (then of course only for one node at the same time).
Comment: This is coming from a user reference field actually, not the node author core field. The field is set to render the user entity in a given view mode, the view Block is looking at the current node for the field value to render it in a block display.
Comment: In this case it might be easier if you switch the view to field mode and add a relationship to the referenced user, then all field values should be available.
Answer:
Conversely, how I can prevent anyone from getting to user/* pages?

Getting technical here, you wouldn't want to block all /user/*; otherwise, you wouldn't be able to /user/login or /user/logout and also you would still want admins to access those /user/{uid} pages.
If  you inspect core/modules/user/user.routing.yml you can see most of the user routes. But what you expect, the /user/{uid} is not defined here.
It's actually defined in UserRouteProvider.php as /user/{user}

You can easily find the route name by enabling WebProfiler module that comes with Devel and  going to /user/1

Now all you gotta do is override the route's access by giving it a role of administrator.
mymodule/src/Routing/RouteSubscriber.php
namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Allow only admins to access '/user/{user}'.
    if ($route = $collection->get('entity.user.canonical')) {
        $route->setRequirement('_role', 'administrator');
    }
  }

}

Alternatively, in your custom module, you could create a new permission and use that for the Route's setRequirement instead and then assign the new permission to the roles that you want to have access.
mymodule/mymodule.services.yml
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

For more in depth information about altering routes, see: Altering existing routes and adding new routes based on dynamic ones.
Comment: Yeah, when I said that I basically meant I did not want any non authenticated user to be able to access the user pages beyond login or forgot password. At the same time I really don't want _anyone_ to get there even if they are authenticated, and this might be the only path.
Comment: @Kevin yeah I figured, I only stated that for correctness; for the sake of non expert readers who might see this.
Comment: @Kevin curious to know what you ended up doing.
Comment: Wound up giving the permission for the short term until we have time to try this


Is it possible to add layers (more rows) of text using one flex item?

Question: I've created a flexbox container element to which my iframe is on the right.
However, I'd like to have two maybe even three layers of text using different tags to the left of it evenly spaced in the width: 1000px; margin: 0 auto; div I have. likely an H3 header and a P.
at the moment they're side by side. Flexbox has obviously created another item for the P.
Is there a way to bring the P down below the H3 and make it behave so that it's centered in that item? Also I need the P not to spill out of the item and into the iframe (max-width?)
HTML:

A comprehensive view on the Oculus Go

This review

CSS:
    #hide  {
      display: block;
    }

    .vid-1  {
      display: flex;
      width: 1000px;
      padding-bottom: 300px;
      margin: auto;
    }

    iframe  {
      width: 50%;
      height: 300px;
      position: absolute;
      display: block;
      transform: translate(500px, 0)
    }

    .chan-h3-shift  {
      font-size: 0.9em;
      padding: 0 0 0 60px;
    }

    .chan-p-shift  {
      padding: 0 800px 0 60px;
    }

    @keyframes lefttoright {
      0%  {
        transform: translateX(-100%);
        opacity: 0;
      }
      100%  {
        transform: translateX(0);
      }
    }

    .lefttoright  {
      animation-name: lefttoright;
      animation-duration: 3s;
    }

Comment: I think you're trying to do Grid's job with Flexbox. Do you want the p tag to be centered both vertically and horizontally? Where exactly do you want the 1000px gap and what do you want to happen in smaller screens?
Answer: if you want your p and your h3 one on top of the other, the best thing is to use another div to wrap them:

A comprehensive view on the Oculus Go

This review

With this css:
.column {
  display: flex;
  flex-direction: column;
}

Does this do the trick ?


Identificar CSS anterior

Question: É possível identificar CSS anterior?
O foco aqui é a class card.
Exemplo:

                Titulo

                    120

                    Bla bla bla

                    Titulo

                        120

                        Bla bla bla

Na primeira row a class card está sozinha. Na segunda row a class name está dentro de uma coluna representada pelas class sm-6 md-6 lg-6.
PERGUNTA
É possível aplicar um CSS ao card que está apenas em sm, md ou lg?
Obrigado.
Comment: [Problema XY](https://pt.meta.stackoverflow.com/q/499/137387), você está complicado uma coisa simples.  Veja na perguta indicada como duplicada como selecionar um elemento descendente de outro baseado em suas classes `[class="sm-6 md-6 lg-6"] > [class="card"]{  color: red; }`
Comment: Vc não quer estilizar o card que está dentro do sm? Então seria algo como `.sm-6  > .card` (ou sem o `>`, como explicado no link que indiquei). Ou vc quer estilizar o sm, desde que tenha um card dentro? Nesse caso, acho que seria duplicada dessa: https://pt.stackoverflow.com/q/510083/112052
Comment: Aí teria que ser algo [assim](https://pt.stackoverflow.com/q/175300/112052) - mas como não tem "ou", teria que ser um pro sm, outro pro md, etc - mas ainda não ficou claro, vc quer selecionar o card ou o pai dele?
Comment: @hkotsubo não, no meu caso é o inverso, gostaria de verificar para traz.
Comment: Tem como identificar apenas pelas letras? Exemplo VOU INVENTAR: `.sm*, md*, lg* .card`?
Answer: Solução:
div[class^="sm-"] > .card, div[class^="md-"] > .card, div[class^="lg-"] > .card { ... }

Identificar CSS anterior


Porque esse pedaço de código está dando loop infinito?

Question: Todas as variáveis estão declaradas e o Eclipse não está apontando nenhum erro no código inteiro.
O que eu preciso fazer: O usuário só pode escolher entre 1, 2 e 3. Qualquer outro input, inclusive textos (exemplo: teste) e outros números (exemplo: 4) deve acusar erro (por isso o último JOptionPane) e retomar o pedaço de código (por isso o do-while). Caso o usuário entre com os números 1, 2 ou 3, o do-while deve ser quebrado (por isso os brakes) e outra pergunta (que segue o mesmo esquema) aparece na tela.
Antes estava dando tudo certinho. Se o usuário entrasse com "4", o programa realmente acusava erro e reiniciava a pergunta. Só que quando o usuário entrava com um texto, o programa fechava. Provavelmente porque o opção estava sendo transformado em int. Aí pensei em transformar o opção em int apenas se o usuário já tivesse entrado com as opções permitidas. Mas aí começou a dar loop infinito.
Segue o código ATUAL (com problema):
do{
  opção=JOptionPane.showInputDialog(null, cabeçalho+inícioP1+código+espaço+"está alinhada com quantos objetivos da Estratégia da Empresa?"+digite+opção11+"2 ou mais"+opção12+"Apenas 1"+opção13+"Nenhum", cabeçalho, JOptionPane.PLAIN_MESSAGE);
    if(opção=="1" || opção=="2" || opção=="3"){
          opçãoI=Integer.parseInt(opção);
              if(opçãoI==1){
                  pontos1=pontos1+9;
                    break;
                } else if(opçãoI==2){
                    pontos1=pontos1+6;
                    break;
                } else if(opçãoI==3){
                    pontos1=pontos1+3;
                    break;
                }
            } else {
                JOptionPane.showMessageDialog(null, "Você selecionou uma opção inválida. Clique em \"OK\" para retornar.", erro, JOptionPane.PLAIN_MESSAGE);
          }
} while(opçãoI!=1 || opçãoI!=2 || opçãoI!=3);

E aqui o código antigo:
do{
            opção=JOptionPane.showInputDialog(null, "Bem-vindo ao Console de Priorização de Ideias da Nova A3 (v.1.0.0).\n\nDigite o Código ou o Nome da Ideia.", "BEM-VINDO", JOptionPane.PLAIN_MESSAGE);
            código=opção;
            do{
            opção=JOptionPane.showInputDialog(null, cabeçalho+inícioP1+código+espaço+"está alinhada com quantos objetivos da Estratégia da Empresa?"+digite+opção11+"2 ou mais"+opção12+"Apenas 1"+opção13+"Nenhum", cabeçalho, JOptionPane.PLAIN_MESSAGE);
            opçãoI=Integer.parseInt(opção);
                if(opçãoI != 0 || opçãoI == 0){
                    if(opçãoI==1){
                        pontos1=pontos1+9;
                        break;
                    } else if(opçãoI==2){
                        pontos1=pontos1+6;
                        break;
                    } else if(opçãoI==3){
                        pontos1=pontos1+3;
                        break;
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Você selecionou uma opção inválida. Clique em \"OK\" para retornar.", erro, JOptionPane.PLAIN_MESSAGE);
                }
                JOptionPane.showMessageDialog(null, "Você selecionou uma opção inválida. Clique em \"OK\" para retornar.", erro, JOptionPane.PLAIN_MESSAGE);
            } while(opçãoI!=1 || opçãoI!=2 || opçãoI!=3);

Comment: Acredito que existam n formas de resolver isso. Uma delas seria verificar o tipo da entrada antes de comparar com int, outra seria inserir um jtextfield restrito a números apenas, ou uma alternativa fácil e eficiente seria utilizar [JRadioButtons](http://www.javaprogressivo.net/2014/05/JRadioButton-Botao-Radio-Opcao-Tutorial-de-Java-GUI.html?m=1) e exibir apenas as opções que o usuário tem pra escolher.
Comment: O loop infinito acontece apenas quando o usuário entra com um texto, certo? Ou qualquer valor de entrada causa tal loop?
Answer: Veja bem... analizando a condiçao do loop:
valor de opcaoI | opçãoI!=1 || opçãoI!=2 || opçãoI!=3  resultado
     1                false        true         true       true
     2                true         false        true       true
     3                true         true         false      true
     4                true         true         true       true

Para quebrar o loop quando opcaoI for 1, 2 ou 3 o correto é && ao invés de ||:
valor de opcaoI | opçãoI!=1 && opçãoI!=2 && opçãoI!=3  resultado
     1                false        true         true       false
     2                true         false        true       false
     3                true         true         false      false
     4                true         true         true       true

Answer: tudo bem?
Cara me parece apenas um pequeno erro de lógica. Tente fazer o que Gustavo sugeriu. Vamos ver o porquê:
Quando você entra no primeiro if, isso significa que o usuário digitou corretamente uma das opções validas, 1, 2 ou 3. Ou seja, no seu while, nós temos duas condições verdadeiras e uma falsa então o loop sempre retornará para o ponto inicial do DO.
Minha sugestão é criar uma variável boolean de controle, para definir ao final do DO que tudo ocorreu bem e que o processo não precisa se repetir. Outra opção é alterar o valor da variável opcaoI para um valor fictício como "-1" e alterar a condição do while substituindo os "||" por "&&".
Exemplo:`
do{
boolean controle = true;
  opção=JOptionPane.showInputDialog(null, cabeçalho+inícioP1+código+espaço+"está alinhada com quantos objetivos da Estratégia da Empresa?"+digite+opção11+"2 ou mais"+opção12+"Apenas 1"+opção13+"Nenhum", cabeçalho, JOptionPane.PLAIN_MESSAGE);
    if(opção=="1" || opção=="2" || opção=="3"){
          opçãoI=Integer.parseInt(opção);
                controle = false;
              if(opçãoI==1){
                  pontos1=pontos1+9;
                } else if(opçãoI==2){
                    pontos1=pontos1+6;
                } else if(opçãoI==3){
                    pontos1=pontos1+3;
                }
            } else {
                JOptionPane.showMessageDialog(null, "Você selecionou uma opção inválida. Clique em \"OK\" para retornar.", erro, JOptionPane.PLAIN_MESSAGE);
          }
} while(controle);

Espero ter ajudado.
Answer: Os erros são:
String é referência, se você comparar com == vai retornar falso, a não ser que esteja falando do mesmo objeto. Ex: "1" == "1" retorna falso. "1".equals("1") retorna true
Você não precisa usar "do...while".
Como você colocou "break" dentro dos ifs, você pode fazer um "while(true)" que ele vai sair do loop quando entrar em algum if.
Eu dei uma enxugada no seu código... olha aí.
while(true) {
        opção = JOptionPane.showInputDialog(null,
                cabeçalho + inícioP1 + código + espaço
                        + "está alinhada com quantos objetivos da Estratégia da Empresa?" + digite + opção11
                        + "2 ou mais" + opção12 + "Apenas 1" + opção13 + "Nenhum",
                cabeçalho, JOptionPane.PLAIN_MESSAGE);
        if (opção.equals("1")) {
            pontos1 = pontos1 + 9;
            break;
        } else if (opção.equals("2")) {
            pontos1 = pontos1 + 6;
            break;
        } else if (opção.equals("3")) {
            pontos1 = pontos1 + 3;
            break;
        } else {
            JOptionPane.showMessageDialog(null,
                    "Você selecionou uma opção inválida. Clique em \"OK\" para retornar.", erro,
                    JOptionPane.PLAIN_MESSAGE);
        }
    }

E deixo uma dica. Por favor, não use acentos e ç no nome das variáveis. Isso da um calafrio que sobe pela espinha aqui.
Espero ter ajudado.


Finding quotient and remainder

Question: Find the quotient and remainder when $f(x)$ = $3x^3 − 2x^2 + 5x − 7$ is
divided by $x + 2$.
I found quotient to be $3x^2 - 8x -11$ with remainder 15. I'm sure the remainder is correct but not sure about the quotient, am I right?
Comment: Is it hard to check?
Comment: You should check the step where a $-8x^2+5x$ appears.  I believe a sign error occurred there.
Answer: When you factor polynomials like this over, you should end up with
\begin{equation*}
f(x)=p(x)(x+2)+r(x)
\end{equation*}
Where $r(x)$ is a polynomial with degree less than $deg(x+2)$. In this case that gives you a constant. This allows you to plug in $-2$ for $x$ to discover the remainder!
\begin{equation*}
f(-2)=-49
\end{equation*}
It looks like you need to tweak your remainder. Have you heard of synthetic division? This video might help:
https://www.youtube.com/watch?v=bZoMz1Cy1T4
Answer: By definition of the remainder and the quotient, if you are right you should have
$$
3x^3 - 2x^2 + 5x - 7 = (3x^2 -8x - 11)(x + 2) + 15.
$$
Do you?

Finding quotient and remainder


ambiguous overload for 'operator+' when typecasting from unsigned char to a fixed point data type

Question: I implementing an image processing algorithm on vivado hls, as a part of optimization, I am trying to change the floating point representation into fixed point representation.
Here is the part where it is going wrong
#include <ap_fixed.h>
unsigned char win[3][3];
typedef ap_ufixed<11,8> fix;
struct pixel_f
{
    fix r;
    fix g;
    fix b;
};
pixel_f new_pix;
.
.
.
.
.

new_pix.r = ((fix)(win[1][0] + win[1][2]) / 2)+0.5;

when I tried to execute it, it is giving me an error saying
demosiac_core.cpp:16:49: error: ambiguous overload for 'operator+' (operand types are 'ap_fixed_base<11, 8, false, (ap_q_mode)5u, (ap_o_mode)3u, 0>::RType<32, 32, true>::div {aka ap_fixed<12, 9, (ap_q_mode)5u, (ap_o_mode)3u, 0>}' and 'double')
   new_pix.r = ((fix)(win[1][0] + win[1][2]) / 2)+0.5;

can someone help me with any suggestions related to why it is going wrong and what can be done to make this work??
Thanks in advance,
Comment: Do you have an `operator+` overload for the `ap_ufixed` template class and `double`?
Comment: On another note, whenever you "need" to use C-style casting in C++, you should take that as a sign that you're doing something wrong.
Answer: Looking at the header files it seems the problem is that the ap_ufixed class has both a constructor that takes a double i.e. fix::fix(double), and an operator that converts to a double i.e. fix::operator double(). But it does not define an addition operator that takes a fix and a double, i.e. there is no operator+(fix, double).
So when code like this is being compiled
fix x = ...;
double y = ...;
fix z = x + y;

the compiler doesn't know whether to convert y to fix and add two fix values, or whether to convert x to a double and add two double values. That what the ambiguity in the compiler error message is refering to.
The solution is to say precisely what you want, if you want that addition to add two fix values then write this
new_pix.r = ((fix)(win[1][0] + win[1][2]) / 2)+ fix(0.5);

if you want the addition to add two double values (seems less likely) then write this
new_pix.r = (double)((fix)(win[1][0] + win[1][2]) / 2) + 0.5;

or maybe you want to rewrite the expression entirely. I can't see why this wouldn't do the same as your code (get the average of win[1][0] and win[1][2] but rounding up) but in a simpler and more efficient way
new_pix.r = (win[1][0] + win[1][2] + 1) / 2;

Incidentally it seems there are operators defined that take integer values, which is why the / 2 in your code doesn't cause the same problem.
Comment: Note that this is in a sense a library issue. The constructor taking double should be explicit and/or the conversion to double should have a name (like to_double). The benefit of using fix(0.5) is that if/when the library is improved to use an explicit constructor the suggested code will continue to work.


Mathematical formulation for maximum sum of edge weights

Question: For my academic research purposes, I have a situation as below.
The initial problem looks as in below figure.
I need to find one match for each of P1,P2,P3 from the right side such that the sum of edge weights is maximized. If we look at a solution for the below query, the solution can be as below.

If we consider the sum of edge weights now, it is

P1 -> A1 (1.5)
P2 -> A2 (1.9)
P3 -> A3 (2)

And the total would be 5.4 which is the maximum. How can I represent the above problem in the form of a mathematical equation?
Answer: Given the two sets $P$ and $A$ indexed with $i$ and $j$, respectively, I would use a binary variable $x_{ij}$ which is equal to 1 iff I select the edge from $i \in P$ to $j \in A$.
I want to maximize the sum of the edges' weights, subject to the constraints that there are no two edges incident to the same node. As I understand, all nodes in $P$ must have a match, while some nodes in $A$ may not have a match (of course, the cardinality of $P$ must be smaller or equal to the cardinality of $A$):
$$ \max \sum_{i \in P}\sum_{j \in A} x_{ij} \cdot w_{ij} \;\;s.t.$$
$$\sum_{j \in A} x_{ij} = 1\;\;\;\forall i\in P$$
$$\sum_{i \in P} x_{ij} \leq 1\;\;\;\forall j\in A$$
$$x_{ij} \in \{0,1\}$$
where $w_{ij}$ is the weight of the edge from $i$ to $j$.
The first constraint ensures that the degree of each node in $P$ is exactly 1 (all nodes in $P$ have only one incident edge), while the second constraint ensures that each node in $A$ has at most one incident edge.
Hope I correctly understood the question.
Comment: thanks for your response. However, I can not always guarantee the set P has a match in A. So there can be cases where a particular vertex from P can still be empty.
Comment: It should be enough to change the = with $\leq$ in the first constraint. Please, accept the answer if it is satisfactory for you.


Can i use foreach loop to send response for an ajax call?

Question: Sorry if its a silly question.I am making an ajax call to the php script to get some data and here is my code
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Let AJAX change this text

<button type="button" onclick="loadDoc()">Change Content</button>

and here is my php script in YII
if($timevalue != 0)
        {
            $model=new Products;
            $receivedata=$model->retrieveresult($timevalue);
            foreach($receivedata as $finaldata)
            {
                  header('Content-Type: application/json');
            echo json_encode(array('table'=>'products',array('productId'=>$finaldata->productId,'productName'=>$finaldata->productName,'Creation_date'=>$finaldata->Creation_date)));
            }
        }

Now since i have to send multiple records of data but one by one then can i use foreach loop for it. I am a newbie and do not know whether it will work or not. can anyone help please?
Comment: Short answer: no. You can deliver ONE response per call, so ONE header and ONE string
Comment: Exactly. Or concatenate them into one result
Comment: So sir, if i have to send multiple records of data , i will need multiple requests???
Comment: ok sir, thanks for clearing this out. Advice is very much appreciated :)
Answer: You cannot send multiple Content-Type headers. Sending multiple lines of JSON doesn't make sense anyway. Why not echo json_encode($receivedata); right away? Or, inside your foreach loop: $results[] = array( /* Your stuff here */ ); and after the loop echo json_encode($results);, which would send an array of arrays.
Your Javascript code is putting in the div the type of the response (you're using typeof), which would read out as 'object' - not what you expected, but your JSON response is an object for JS, so makes sense. You should think what you want to do with the arrays in JS once you get the data there.


Can't select Cell in UITableView For UITableViewCellAccessoryCheckmark

Question: If you have used Messages application in iOS, you know how we could invoke UITableViewCellAccessoryCheckmark in any message through edit button and then select each bubble/cell for forward or deletion purpose.
I'm trying to do the same in my application. I can tap on edit and UITableViewCellAcessoryCheckMark is shown, but I can't select the cells using it. What more do I need to implement?

Any help would be appreciated. Here is the code -
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem  = self.editButtonItem;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
        return UITableViewCellAccessoryCheckmark;
}

Comment: Can you please give more details about what exactly you are trying to achieve?
Comment: Post updated. Check the image to understand what i'm trying to achieve here.
Comment: Did you set `tableView.allowsSelectionDuringEditing = YES` ?
Comment: For example in `viewDidLoad`. If the tableview is defined in a nib you can also set it there.
Comment: No not working in viewDidLoad.
Comment: Is the table view in a nib file?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16059/discussion-between-martin-r-and-monis-manzoor)
Answer: For a table view as shown in the picture, where one or more cells can be selected with a checkmark symbol, you have to set allowsMultipleSelectionDuringEditing = YES on the table view. This can be done either in viewDidLoad with
self.tableView.allowsMultipleSelectionDuringEditing = YES

or in the Attributes Inspector of the table view in the NIB/Storyboard file by setting "Editing" to "Multiple Selection During Editing".
The tableView:editingStyleForRowAtIndexPath: method is not needed for this.
(And btw your method returns UITableViewCellAccessoryCheckmark which is a UITableViewCellAccessoryType and not a UITableViewCellEditingStyle.)
Comment: Thanks. But without it i am unable to access checkmark style for selecting the cells. What else do i need for it?
Comment: `allowsMultipleSelectionDuringEditing` is an iOS 5 feature. Maybe that is the problem?
Comment: Perhaps I don't understand the problem correctly. Does your table look as in your above picture? What happens if you tap on a cell?
Comment: ok, the problem now is that if i don't use UITableViewCellAccessoryCheckmark in UITableViewCellEditingStyle, i don't get checkmark style option (by default it seems to have delete style). Also, if everything is working fine, selecting the cells is not working even if i enabled it from inspector/code.
Comment: Did you set the allowsMultipleSelectionDuringEditing option?
Comment: Yes, i did. Still the same result. Can't select the cells :/
Comment: So what happens if you tap on a cell? Does it switch between checked/unchecked ? Or does nothing happen?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16074/discussion-between-monis-manzoor-and-martin-r)
Comment: @MonisManzoor: Did you make any progress in this matter?


c# - Handling closing/disconnecting web socket connections (CloseAsync vs CloseOutputAsync)

Question: I am trying to understand and handle the different ways a web socket connection could be closed. From msdn:

You can use the CloseAsync and CloseOutputAsync methods for both
client-initiated and server-initiated requests to close an
AspNetWebSocket connection. The two methods handle client-initiated
requests in the same way: After the client sends a message to the
server to close the connection, the server calls one of these methods
and sends an acknowledgment to the client, and then the method
returns.
For server-initiated requests, the two methods work
differently. The CloseAsync method sends a message to the client to
close the connection, waits for a response, and then returns. The
server does not wait for any additional data sent by the client. In
contrast, the CloseOutputAsync method sends a message to the client to
close the connection and returns without waiting for a response. After
the method returns, you can call the ReceiveAsync method and handle
either additional data or the acknowledgment that the client sends.

In my application the client basically sits there receiving updates from the server, but never actually sends anything to the server outside of opening the connection. However the client also needs to be able to close the connection from their side.
Basically the server's role is to sit there waiting to open a connection, send a bunch of stuff, and handle clients closing connections (but never has to decide to close the connection or not).
So no matter, when we are talking about cleanly closing a connection, a client needs to send the server a message saying it wants to close the connection, correct?
So the client will need to do something like:
var x = await closeAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None)

How does the server know the client executed closeAync? I tried to send a piece of data from server to client using:
await sendAsync(new ArraySegment<byte>(infoBytes), 1, false, cancelled);

and received an error:

"The received message type 'Text' is invalid after calling
WebSocket.CloseAsync. WebSocket.CloseAsync should only be used if no
more data is expected from the remote endpoint. Use
'WebSocket.CloseOutputAsync' instead to keep being able to receive
data but close the output channel."

So how on the server side do I know if the client is trying to cleanly close the connection?
Comment: That error talks about receiving while your code was sending. The two don't match. What's going on?
Comment: That error was on the client side when the server side used sendAsync. Whats going on? is the question I asked haha
Answer: On the server side :
 var result = await webSocket.ReceiveAsync(buffer, cancellationToken);

            if (result.MessageType == WebSocketMessageType.Close)
            {
                await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closed in server by the client", CancellationToken.None);
                return null;
            }

Comment: Edited: CloseOutputAsync is the correct method to acknowledge a Close frame, not CloseAsync. It even says that in the OP's MSDN quote.


How to get an instance of a plugin

Question: I am attempting to use a pre-configured instance of a plugin.  The plugin is of type @CommercePaymentGateway.
I am currently trying to use something like:
/** @var PaymentGatewayManager $manager */
$manager = \Drupal::service('plugin.manager.commerce_payment_gateway');
$manager->getInstance(['module' => 'commerce_paypal']);

But I'm getting the error Error: Call to a member function getInstance() on null.  However, using kint(), $manager is clearly an instance of Drupal\commerce_payment\PaymentGatewayManager.
I see what I think is the instance configuration in the config table under commerce_payment.commerce_payment_gateway.paypal_ec.  But that paypal_ec part is specific to my site.
How do I get an instance of a plugin?
Answer: It turns out, in my case, I'm asking the wrong question.  All that I need is the parent config entity (@bojanz pointed this out in slack), so I was over-complicating the issue:
$gateway = \Drupal::entityTypeManager()
  ->getStorage('commerce_payment_gateway')->loadByProperties([
    'plugin' => 'paypal_express_checkout',
]);

This will return an array of gateways, get a specific one:
// Get the first one
$plugin = reset($gateway);
$plugin = $plugin->getPlugin();

Now you have the $plugin to be used elsewhere.

How to get an instance of a plugin


What is the correct name for this instrument?

Question: I guess it's some type of trombone, but I can't find its correct name anywhere.

P.S. If you're wondering, here's where I got this shot from:
Answer: This is apparently called a  contrabass valve trombone, or sometimes a cimbasso if I am correct.
Comment: @Tim: probably Wagner
Comment: Any particular composer or period of music history it was favoured by/in?
Comment: @Tim Maybe a good new question ;) ?
Comment: Interesting, it appears to have rotary valves like a French horn instead of piston valves like regular valve trombones.
Comment: @johnbelzaguy Might actually be the difference between the CVT and the cimbasso!
Comment: The [Wikipedia article on "types of trombone"](https://en.wikipedia.org/wiki/Types_of_trombone#Cimbasso) has more information for the curious.
Comment: @Tim I forgot to include the link to the wiki article with more info, Michael Siefert put it in. Seems like the shape is the main difference (if you trust wiki). The two have the same range ans can have either piston or rotary valves. Apparently Verdi didn't dig the tuba, lol.
Comment: @JohnBelzaguy For that matter, there are piston-valved French horns too.
Comment: @CarlWitthoft yes I'm aware. The rotary valves on the cimbasso just caught my eye so I commented on it.
Answer: This is a cimbasso (a valve contrabass trombone). The instrument is mainly used in Verdi's operas (and one opera each by Bellini and Puccini). The modern instrument has six rotary valves and is normally pitched in F, but there are also instruments in B-flat (a fifth lower). Both instruments can be heard here (the low B-flat is the one with the smaller bell, lower right):

Mattis Cederberg of the West German Radio Big Band uses a cimbasso for jazz:
Comment: Interesting that it's used in both *Nabucco* and *Norma*, so I may have heard one twice without knowing it.
Answer: The instrument shown is called a cimbasso, an instrument basically created by Verdi as something similar to the contrabass trombone. It's pretty rare!
Comment: Glad to see you're getting active on the site. Since your answer here duplicates the ones already given, just a reminder/suggestion to read the other posts first. What's unique here is your comment that Verdi invented the instrument. If that can be documented, it would add something unique not in the other answers.
Comment: @Aaron From the Wikipedia article referenced from my answer: "Verdi ... developed an instrument with the firm Pelitti"


Difference in Holding 6 holes and 7 holes in Indian Bamboo Flute

Question: Please clear my following doubts.

What is the difference between 6 holes and 7 holes holding position in flutes ?
Can I play a song with 6 holes in 8 hole flute ?
Answer: I've never played this instrument before, but I can play most of the woodwinds, including flute, recorder, and tin whistle.  I did a quick search, and if I'm understanding this thing correctly, it's fundamentally very similar to the fife and uses the same fingerings as the fife and tin whistle.
A 7-hole instrument is extended downwards one extra step.  The first 6 holes function exactly the same as on the 6-hole variety, but covering the additional hole achieves an extra low note.  So music written for a 6-hole instrument is always playable on a 7-hole instrument, but music written for a 7-hole instrument (that uses that lowest note) wouldn't be entirely playable on a 6-hole instrument without transposing the music.
Comment: But I could see people holding 7 holes in 8 hole flute. Does that 8th hole even matters ?
Answer: Indian Music consist of 2 types
1) Carnatic Music
2) North Indian or Hindustani classical music.
Carnatic Musicians uses 7 playing Holes Bamboo flute.
Where as there are only 6 playing holes in Hindustani classical based flute.
The difference is done to produce different notes which are differently produced.


Update attribute in callback Rails 3

Question: Following on from this question, I have spent the day trying to add a cumulative running sales total to my sales table. It's a bit tricky (for me) because I want a running total for sales where the isbn_id is the same, and, within that set, records where the channel_id is the same - ranked by invoice_date. This is all so I can calculate royalties on a particular range of units sold.
Here's my non-working callback code, in the Sale model:
before_save :runningtotal

private

def runningtotal
  @sale = Sale.order("invoice_date ASC")
  @lastbal = @sale.find_all_by_isbn_id(@isbn).group_by(&:channel)
  #that sucessfully gets all sales ranked by date ascending, then groups them by channel, just for the current isbn.
  @lastbal.each do |channel, sale|
    sale.each_with_index do |sale, i|
      previous_sale = sale[i-1] unless i==0
      next unless previous_sale
      @total_quantity = previous_sale.quantity + :quantity
      write_attribute(:total_quantity,@total_quantity)
    end
  end
end

Is this roughly how a callback should be written - just in the model? Does it just run magically before_save of a new sale?
My core question is: how can I update the attribute "total_quantity" to be the sum of "quantity" for the current record, and "total_quantity" for the previous record by date, in a before_save callback, within the constraints of the finds for isbn_id and channel_id?
Here's the output of the find:
ruby-1.9.2-p180 :025 > @lastbal = @sale.find_all_by_isbn_id(@isbn).group_by(&:channel)
=> {#<Channel id: 4, isbn_id: nil, channel_name: "Gratis", created_at: "2011-05-26 11:08:22", updated_at: "2011-05-26 11:08:22">=>[#<Sale id: 26, isbn_id: 2, quantity: 10000, value: 40000, currency: "", total_quantity: nil, created_at: "2011-05-26 11:11:30", updated_at: "2011-05-26 11:11:30", customer: "6", retail_price: nil, discount: nil, channel_id: 4, invoice_date: "2011-05-18", rule_id: nil, trenche: nil>], #<Channel id: 1, isbn_id: nil, channel_name: "Home", created_at: "2011-05-16 19:47:27", updated_at: "2011-05-16 19:47:27">=>[#<Sale id: 22, isbn_id: 2, quantity: 1000, value: 5193, currency: "", total_quantity: nil, created_at: "2011-05-25 19:46:03", updated_at: "2011-05-25 19:46:03", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2011-05-11", rule_id: nil, trenche: nil>, #<Sale id: 24, isbn_id: 2, quantity: 1000, value: 4394, currency: "", total_quantity: nil, created_at: "2011-05-26 09:48:16", updated_at: "2011-05-26 09:48:16", customer: "g", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2011-05-10", rule_id: nil, trenche: nil>, #<Sale id: 25, isbn_id: 2, quantity: 1000, value: 4394, currency: "", total_quantity: nil, created_at: "2011-05-26 10:02:38", updated_at: "2011-05-26 10:02:38", customer: "g", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2011-05-05", rule_id: nil, trenche: nil>, #<Sale id: 21, isbn_id: 2, quantity: 1000, value: 5193, currency: "", total_quantity: nil, created_at: "2011-05-25 14:12:45", updated_at: "2011-05-25 14:12:45", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2010-10-15", rule_id: nil, trenche: nil>, #<Sale id: 13, isbn_id: 2, quantity: 50, value: 159, currency: "", total_quantity: nil, created_at: "2011-05-25 12:33:09", updated_at: "2011-05-25 12:33:09", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2010-01-01", rule_id: nil, trenche: nil>, #<Sale id: 14, isbn_id: 2, quantity: 25, value: 129, currency: "", total_quantity: nil, created_at: "2011-05-25 12:33:23", updated_at: "2011-05-25 12:33:23", customer: "", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2010-01-01", rule_id: nil, trenche: nil>, #<Sale id: 12, isbn_id: 2, quantity: 100, value: 415, currency: "", total_quantity: nil, created_at: "2011-05-25 12:32:50", updated_at: "2011-05-25 15:13:21", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2001-10-01", rule_id: nil, trenche: nil>, #<Sale id: 11, isbn_id: 2, quantity: 500, value: 2197, currency: "", total_quantity: nil, created_at: "2011-05-25 12:32:24", updated_at: "2011-05-25 15:11:20", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2000-10-01", rule_id: nil, trenche: nil>], #<Channel id: 2, isbn_id: nil, channel_name: "Export", created_at: "2011-05-16 19:47:35", updated_at: "2011-05-16 19:47:35">=>[#<Sale id: 23, isbn_id: 2, quantity: 2000, value: 5000, currency: "", total_quantity: nil, created_at: "2011-05-26 09:16:15", updated_at: "2011-05-26 09:16:15", customer: "v", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2011-05-02", rule_id: nil, trenche: nil>, #<Sale id: 17, isbn_id: 2, quantity: 242, value: 657, currency: "", total_quantity: nil, created_at: "2011-05-25 12:34:24", updated_at: "2011-05-25 12:34:24", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-10-15", rule_id: nil, trenche: nil>, #<Sale id: 18, isbn_id: 2, quantity: 54, value: 194, currency: "", total_quantity: nil, created_at: "2011-05-25 12:34:44", updated_at: "2011-05-25 12:34:44", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-10-15", rule_id: nil, trenche: nil>, #<Sale id: 15, isbn_id: 2, quantity: 135, value: 377, currency: "", total_quantity: nil, created_at: "2011-05-25 12:33:48", updated_at: "2011-05-25 12:33:48", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-09-15", rule_id: nil, trenche: nil>, #<Sale id: 16, isbn_id: 2, quantity: 433, value: 830, currency: "", total_quantity: nil, created_at: "2011-05-25 12:34:06", updated_at: "2011-05-25 12:34:06", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-09-15", rule_id: nil, trenche: nil>]}

Here's the columns in my Sale model:
#  id             :integer         not null, primary key
#  isbn_id        :integer
#  quantity       :integer
#  value          :integer
#  currency       :string(255)
#  total_quantity :integer
#  created_at     :datetime
#  updated_at     :datetime
#  customer       :string(255)
#  retail_price   :integer
#  discount       :decimal(, )
#  channel_id     :integer
#  invoice_date   :date
#  rule_id        :integer

Thanks so much in advance.
UPDATE: final solution.
Really not sure that this counts as 'giving back to the community' as it's comically verbose, not DRY, full of puts which I used to figure out all the bugs, and badly formatted to boot, but heck, I'm a noob at and the very least I can come back here and laugh at myself in a few years when I know what I'm doing. So, here's my final solution, in Sale.rb. Poor overstuffed model. I will refactor this, one day.
before_save :runningtotal
after_commit :refresh

private
  def runningtotal
    # get the latest sale that matches the new sale's isbn and channel id, then rank by invoice date descending, and get the first record:
    lastsale = Sale.where(:isbn_id => self.isbn_id).where(:channel_id => self.channel_id).order("invoice_date DESC").first
    allsales = Sale.where(:isbn_id => self.isbn_id).where(:channel_id => self.channel_id).order("invoice_date DESC")
    # set the total_quantity field in the new sales record to its quantity + the last sale's total.
        if allsales.maximum(:invoice_date).nil?
          puts "runningtotal thinks the max of invoice date in the allsales relation is nil"
          puts "and runningtotal is setting total_quantity on the new sale to be #{self.quantity + (lastsale.try(:total_quantity) || 0)}"
          self.total_quantity = self.quantity + (lastsale.try(:total_quantity) || 0)
          else
            if self.invoice_date < allsales.maximum(:invoice_date)
            puts "the runningtotal method has been skipped because runningtotal thinks the current invoice date is less than the highest invoice date in the allsales relation"
            else
              puts "this is a normal entry so runningtotal has set the total quantity to be #{self.quantity + (lastsale.try(:total_quantity) || 0) }"
              self.total_quantity = self.quantity + (lastsale.try(:total_quantity) || 0)
            end
        end
  end

  def refresh
     allsales = Sale.where(:isbn_id => self.isbn_id).where(:channel_id => self.channel_id).order("invoice_date ASC")
       #if the runningtotal callback hasn't run, the total quantity will be nil, and nil triggers this after_commit callback
       if total_quantity.nil?
         puts "running refresh callback"
         puts "here's a sample parameter pass: id: #{id} quantity: #{quantity} date: #{invoice_date} "
         puts "allsales class is #{allsales.class}"
         # if the new sale that's being saved has a date that's before any previous sale...
            puts "before the if, refresh thinks that the earliest invoice date is #{allsales.minimum(:invoice_date)} and that invoice date is #{invoice_date}"
            if invoice_date <= allsales.minimum(:invoice_date)
              puts "date earlier than existing sales dates"
              puts "refresh thinks that the earliest invoice date is #{allsales.minimum(:invoice_date)} and that invoice date is #{invoice_date}"
              #... then set its total_quantity to the sale quantity...

                update_attribute(:total_quantity, quantity)
                puts "total_qty updated with qty"
                # ... and update all subsequent records' total_quantity (skipping the before_save callback which would trigger an infinite loop).
                  allsales.each_with_index do |sale, i|
                    previous_sale = allsales[i-1] unless i==0
                    next unless previous_sale
                     puts "getting qty out of arel when date earlier than others: #{previous_sale.quantity}"
                     puts "this is adding #{quantity} to #{previous_sale.quantity } which is #{quantity + previous_sale.total_quantity }"
                 Sale.skip_callback(:save, :before, :runningtotal )
                    sale.update_attribute(:total_quantity, (sale.quantity + previous_sale.total_quantity ))
                 Sale.set_callback(:save, :before, :runningtotal)
                 end
            else
              # if the invoice date is within the min and max range of the previous sales...
                # ... update all previous and subsequent records' total_quantity (skipping the before_save callback which would trigger an infinite loop).
                  allsales.each_with_index do |sale, i|
                    previous_sale = allsales[i-1] unless i==0
                    next unless previous_sale
                    puts "getting qty out of arel within existing date range: #{previous_sale.quantity}"
                    puts "this is adding #{quantity} to #{previous_sale.quantity } which is #{quantity + previous_sale.total_quantity }"
                Sale.skip_callback(:save, :before, :runningtotal )
                    sale.update_attribute(:total_quantity, (sale.quantity + previous_sale.total_quantity ))
                Sale.set_callback(:save, :before, :runningtotal )
                  end
        end
      end
  end

Comment: This is a little confusing.  But what I got is that you need to sum... Have you ever seen `inject`? `total = @array.inject{|sum, this| sum + this.numeric_value}` for an array of your sales objects
Comment: I was warned off inject on my previous posted question! Thanks though, I'll keep it in reserve.
Answer: Yes, using before_save in the model will run that every time it is saved, whether new or updated.  Thus you need to watch out in calculations the expect the current (new) record to not exist yet. ;)  You might want to use before_save, :on => :create to limit it to the creation action.
However, if I understand your english statement of the problem, your code is rather convoluted.  I don't even see where @isbn is set, that could be dangerous...
Does this need to update the total on other objects this isbn and channel? Usually it's better form to simply calculate that as needed rather than trying to cache the total in every record.
within the callback, self is the current (new?) record, so use it to refer to new values.

  @sale = Sale.order("invoice_date ASC")
  @lastbal = @sale.find_all_by_isbn_id(@isbn).group_by(&:channel)

can be replaced by this, I think:

 @lastbal = Sale.order("invoice_date ASC").where(:isbn_id => self.isbn_id).group_by(&:channel)

I'm assuming that @isbn is actually the new record's isbn.
From there, I'm not sure if you are only intending to update the new record or the old ones... If you want to update the current record, just set the attribute and exit the callback, and it will be saved when the rest is saved:
self.total_quantity = previous_sale.quantity + self.quantity
If you are intending to update the other objects too, then we have to update those objects and save them. I don't see that happening at all here in your code.
Your code goes through several loops, possibly hitting the write_attribute several times... that doesn't make sense.
If you mean you want to find the last record that matches the current isbn and channel to update the new record, here's what I would do:

def runningtotal
  lastsale = Sale.where(:isbn_id => self.isbn_id).
                  where(:channel_id => self.channel_id).
                  order("invoice_date DESC").first
             # that should be the latest sale that matches
             # the current isbn and channel
  self.total_quantity = self.quantity + (lastsale.try(:total_quantity) || 0)
      # watch out for nil if no previous record exists ^
end

`
Comment: Fabulous - thanks so much for such a useful explanation. That works beautifully.
Comment: Have edited my question with my final solution, fwiw which isn't much as it's nasty!

Update attribute in callback Rails 3


Change branching point in git

Question: We have two branches Branch1 and Branch2 which differs each other by 100 commits. I had created a new branch BranchA from Branch1. No commits have been made on BranchA.
Is there a way to change BranchA to appear it was branched from Branch2, so that I can make a commit and raise a pull request against Branch2 - but it won't carry any commits from Branch1?
Comment: Have you tried to delete `BranchA` and create it based on `Branch2`?
Comment: @zaratustra I can do that, just wanted to know if there is an option to update.

We have a tracker that shows branches created, and it will not update branch deletions - unfortunately. So it would be two branches for the same ticket, which I would like to avoid.
Answer: Since no commits have been added to BranchA yet, you can simply reset it to Branch2:
git checkout BranchA
git reset --hard Branch2

Had there been any commits on BranchA that you needed to keep, you could have opted for a rebase:
git checkout BranchA
git rebase Branch2

Comment: Thank you! Exactly what I needed.

Change branching point in git


Firestore: cannot securely query data with a WHERE clause that uses both currentUser.uid and FieldPath.documentId()

Question: firestore.rules
match /databases/{database} {
    match /documents/board/{boardId}/{document=**} {
        allow read: if (resource.data.creatorId == request.auth.uid);

query 1 (works)
this.db
        .collection("board")
        .where("creatorId", "==", app.auth().currentUser.uid).onSnapshot(...)

query 2 (doesnt work, returns FirebaseError: Missing or insufficient permissions)
this.db
        .collection("board")
        .where("creatorId", "==", app.auth().currentUser.uid)
        .where(app.firestore.FieldPath.documentId(), "in", boardIds).onSnapshot(...)

This doesn't make any sense to me. Query 2 is a subset of Query 1 and yet, unlike Query 1, violates the security rules.
Does anyone know why?
Answer: Your security rules prevent reading a document if the creatorId of it is not the user making the query.
Query 1 works because the filter follows the rule and will not read documents whose creator is not the current user.
Then, Query 2 has that second clause which means:
"I want the documents whose DocID is one of the boardIds array".
The problem might be that the documentID is considered a field of a document.
If one were to apply the second clause alone it will probably crash because userA may try to access a userB document to check if the docID is in the array, which is not allowed.
So, even-though the RESULT of the second query would be a subset of query 1, this doesn't mean (or seems to mean) the QUERY itself is allowed.
Comment: Thanks for the answer Nibrass.

I'm still not totally grasping this though. I tried storing `id` as an explicit field of each board document, so that query 2 becomes:

this.db
        .collection("board")
        .where("creatorId", "==", app.auth().currentUser.uid)
        .where("id", "in", boardIds).onSnapshot(...)

and it suddenly works! I can only understand this in terms of FieldPath.documentId() having some special properties. Or possibly I've stumbled upon a bug.
Comment: I found [this post](https://stackoverflow.com/a/61756336/11668444) explaining the fieldPath.documentID() bit further, as it doesn't really return an ID but a string field path, which might be the issue here.


No PostgreSQL, há diferença entre se executar um dump ou fazer uma exportação?

Question: esta pergunta realmente me deixou em dúvida, pois no postgres há três tipos de backup/restore que são:

SQL Dump (Gera um arquivo texto com comando SQL)
File System Level Backup (Salvar o arquivo de dados do PG)
Continuous Archiving (Backup através do LOG)

Gostaria de saber se estas formas são tratados como dump ou/e exportação?
Answer: Olá DiegoSoaresSub o mais adequado sem dúvida é o SQL Dump por gerar de forma otimizada uma copia do seu banco(s) que fácilmente pode ser importado para outras máquinas ou servidores. Veja que o File System Level tem uma série de restrições ( http://www.postgresql.org/docs/8.1/static/backup-file.html ) que se não tomar cuidado pode não ser possível gerar uma cópia fiel por exemplo. Por fim o Continuous Archiving exige que seja ativado o recurso antes para que se possa recuperar independentemente de se fazer um dump ou não, mas é necessário estar consciente que isso exige armazenamento e processamento extra de forma contínua ( http://www.postgresql.org/docs/8.1/static/backup-online.html ) .
Answer: As três formas servem de alguma forma para backup.
SQL Dump é o modo mais flexível, porém o arquivo texto pode ficar muito grande na medida em que o banco cresce. Para importação e exportação parcial, considere o comando COPY, o qual permite exportação usando SELECT.
File System Level Backup é melhor do ponto de vista de administrador de sistemas, por ser apenas uma cópia de arquivos do sistema. Porém, o processo do banco de dados precisa ser devidamente encerrado para garantir que todas as informações estão devidamente atualizadas. Uma cópia a qualquer momento pode gerar um backup corrompido ou com dados parciais (que estão sendo gravados naquele momento).
Uma forma melhor de fazer backup dos arquivos sem precisar parar o processo é usando o comando pg_basebackup. Ele garante que o arquivo copiado está íntegro e atualizado.
Continuous Archiving é a forma mais rígida de backup. Ele permite restaurar o estado do banco em qualquer ponto no tempo. Porém, vai consumir muitos recursos como espaço em disco e tempo de gravação de dados, gerando logs de informações extensos. Para restaurar um determinado estado é necessário ter os logs desde o último backup realizado até aquele ponto.
Técnicas como o "Arquivamento Contínuo" geralmente são usadas de forma mista com backups normais. Enquanto o backup garante a recuperação de dados completa em intervalos de tempo pré-definidos, o Continuous Archiving garante a recuperação em praticamente qualquer momento.
É importante notar que arquivos binários copiados diretamente ou gerados pelo COPY podem ser dependentes da versão do PostgreSQL. Arquivos texto, por outro lado, costumam ser independentes de versão.


Rearrange all strings in vector Matlab

Question: I have a large cell vector containing names of files in a directory using
listing = dir(['foldername','\*.xlsx']).
The files have dates in the name but in a format which makes it difficult to determine order. For example each file is called dataDDMMYYY.xlsx where DDMMYYY are numbers representing the date of the data.
I want to get a vector of locations ranking the files from newest to oldest. One suggestion is to use arrayfun to remove "data" and "xlsx" from the the string and rearrange to YYYYMMDD using something like new=[old(9:12), old(7:6), old(5:6)].
However I have not found combinations of these without errors.
Is there an elegant way to achieve this?
Comment: Have a look at `regexp`, I am sure there is an regular expression that you can sue to extract this particular date format. You might even be able to find one online.
Answer: You can make use of the function datenum that outputs a number (smaller = older, bigger = newer) for each date, according to a specified format (in your case ddmmyyyy). Then you can use those numbers to sort the dates. This method assumes that all the files are either .xls or .xlsx, and their names begin with data before the actual date:
listing = dir(['fildername','\*.xls*']); % list all xls and xlsx files in directory
names = {listing.name}; % cell array with names only

[~,dates,~] = cellfun(@fileparts, names, 'uni', 0); % apply fileparts to every cell
dates = cell2mat(dates'); % convert to char matrix (all the string have to be equally long)
dates = dates(:,5:end); % remove 'data' from each string

new_dates = datenum(dates, 'ddmmyyyy'); % extract date number
[sorted_new_dates, index] = sort(new_dates, 'descend'); % sort from newest to oldest

Then you can use index to process your original files from newest to oldest.
listing(index).name % print sorted filenames :)

Comment: Thanks. Some folders do have a mix of xlsx and xls. How do you invoke fileparts without a loop?
Comment: Do we know for sure that every file starts with `data` right?
Comment: Yes. Only the extension differs
Comment: I edited the answer, this will work for xls and xlsx. You can use fileparts on every cell of a cell array by using `cellfun`. Hope this is what you were looking for! :)
Comment: Excellent. Thanks!

Rearrange all strings in vector Matlab


Pearson correlation coefficient between two time series

Question: How do i compare two time series:(Pearson correlation coefficient)
1st time series is generated by google trends for search term "India"
2nd time series is Foreign Tourist Arrivals(absolute value of arrivals) to India each month.
Comment: Are you sure you want a simple correlation? What kind of comparison do you want? What would you like to know about how they're related? Eg, do you want to know if values in 1 ts predict subsequent values in the other? Do you want to know if they are cointegrated?
Answer: The simple way to compute it is to pair up all observations at the same time and compute the sample Pearson's correlation (this is what Google Correlate does)
For example, Let's say you want to correlate the time series $S_1$ and $S_2$:
<code> time S_1     S_2
 t_1  20.4400 19.7450
 t_2  19.0750 20.3300
 t_3  20.0650 20.1700
 ..   ..      ..
</code>
Which might look like this when plotted:

You just have to use this formula:
$$
r(S_1,S_2) \triangleq \frac{ \sum_{k=1}^n (S_1(t_k) - \bar{S_1})(S_2(t_k) - \bar{S_2})  }{ \sqrt{ \sum_{k=1}^n (S_1(t_k)- \bar{S_1})^2 \sum_{k=1}^n (S_2(t_k) - \bar{S_2})^2 }}
$$
where $S_1(t_k)$ is a particular value of the time series $S_1$ at time $t_k$, and $\bar{S_1}$ is the average value of $S_1$.
(Just look at the formula of the sample Pearson's correlation between two variables $X$ and $Y$, from wikipedia)
As Gung said, there are different approaches to tackle this problem. Pearson's correlation is good if you are interested in linear correlations, which are very intuitive. There are other measures of dependencies which identify non-linear relationships. I can point you out to a presentation I prepared (hope it is not too shameful to add something of mine here)
Comment: Hey Simone, My hypothesis is  to use google trends to improve traditional forecast of FTA  to India . TO narrow down the search queries , i want to choose queries which are correlated to the monthly FTA time series.                Additionally , How can we aggregate weekly google trends data to get monthly data.
Comment: I think that averaging week values would work fine
Comment: I really appreciate you posting your presentation.  It's helpful, not promotional.


How to convert List to List with Flutter?

Question: I have a function that returns List But in my case I want to read and display float values. However, this function is a system function I can't update it.
My question is how to convert List to List?
This is the code:
characteristic.value.listen((event) async {
  var bleData = SetupModeResponse(data: event);
});

Event is by default a List. When I try to declare data as List; I got List cannot assigned to List.
I would be very thankful if you can help me.
Comment: if 'event' is data, then `event.map((i)=>i.toDouble()).toList()`
Comment: You can convert the List to List in flutter using different ways. var list = list.map((i) => i.toDouble()).toList();
Answer: you can use the map method on list
like that:
 List<int> intList = [1, 2, 3];
 List<double> doubleList = intList.map((i) => i.toDouble()).toList();

You can learn more about dart list mapping here map method
Comment: I would say this may look and work like a great solution. But when you try to run the `runtimeType` of each value in `doubleList ` it will be `int`. I also tried others workaround. Guess we sticking with this.
Answer: This should also work:
List<int> ints = [1,2,3];
List<double> doubles = List.from(ints);

Answer: Yo can try this method and see if it works
List<int> num = [1,2,3];
List<double> doubles = List.from(num);

Answer: Try the following code:
List<double> doubleList = event.map((i) => i.toDouble()).toList()


Is $\sup_{x \in \mathbb{R}} \sum_{k \in \mathbb{Z}} |k|(1+|x-k|)^{-100}$ finite?

Question: Consider
$$
\sup_{x \in \mathbb{R}} \sum_{k \in \mathbb{Z}} \frac{|k|}{(1+|x-k|)^{100}}.
$$
Is it finite?
Comment: No. For $x \in \mathbb{Z}$, there is one term of value $\lvert x\rvert$.
Comment: @DanielFischer this is a great comment. Perhaps you might consider posting it as an answer.
Comment: As long as you have one denominator that can be made $1$ by a choice of $x$, the corresponding numerator is a lower bound for the sum for that $x$. As is, you can make the term for each $k$ have denominator $1$, so without changing the denominator, you need a bounded sequence of numerators.
Comment: Thanks. (extra characters)
Answer: With the denominators $(1 + \lvert x - k\rvert)^{100}$, you can always make one denominator $1$ by choosing $x \in \mathbb{Z}$. Then the corresponding numerator is a lower bound for the sum at that $x$, so without changing the denominators - or making some numerators negative - you can only have a finite supremum if the sequence of numerators is bounded. In that case, the supremum is indeed finite.


Regarding the music notation symbol "simili"

Question: I have been researching the music notation symbol "simili" after coming across it in the piano score for Debussy's "Passepied" from the "Suite bergamasque".
The score uses "simili" as the continuation symbol for staccato instead of the more common "simile".
My findings are as follows:

The possibility that "simili" is a misspelling of "simile" is unlikely as it appears in multiple editions of the score.
The possibility that "simili" is the plural of the Italian word "simile" is contradicted by the fact that other composers of this era used "simile" in their scores.
Additionally, Debussy was a French speaker, so he was more likely to follow French musical standards.
The possibility that "simili" comes from the Esperanto word for "synonymous" is supported by the fact that the publication of "Passepied" (1890-?) overlaps with the announcement of Esperanto in 1887.
However, it is unclear why Debussy would choose to use Esperanto in his score when other musical symbols are in Italian.
The possibility of a mistake by the publisher or editor is uncertain since "simili" appears in the original manuscript.

Therefore, the reason for Debussy's use of "simili" instead of "simile" remains unclear.
If anyone has any information on this matter, please let me know.
This question was translated from Japanese, please let me know if you find any expressions that were not conveyed.
Answer: In my 'bible' (Oxford Companion to Music), both simili and simile are quoted as plurals from Italian, so it seems either is acceptable.
Comment: This was not found in the Japanese literature. I learned it. Thank you very much.
Answer: The Dolmetsch music dictionary: Sf - Si, list simili as the plural form of simile:

simile (s.), simili (pl.)
(Italian, literally 'similar') an instruction to continue with some effect or technique
Comment: That was not found in the Japanese music dictionary. I learned it. Thank you very much.


For $x\geq 0$, what is the smallest value of $\frac{4x^2+8x+13}{6(x+1)}$?

Question: I know that I have to use the AM-GM inequality.
I tried separating the fraction:
$$\frac{4x^2+2x+7}{6(x+1)} + \frac{6(x+1)}{6(x+1)}$$
However, it doesn't seem to make either side of the inequality into a number.
I would appreciate some help, thanks!
Answer: $$\frac {4x^2+8x+13}{6(x+1)}$$
$$= \frac {2(x+1)}{3} + \frac {3}{2(x+1)}$$
$$ = y+\frac {1}{y} \ge 2$$
Answer: $$\frac{4x^2+8x+13}{6(x+1)} = \frac{4(x+1)^2+9}{6(x+1)} \ge \frac{2\sqrt{4(x+1)^2\cdot 9}}{6(x+1)} = \frac{2\cdot2\cdot3}{6} =\frac{12}{6} = 2$$
Comment: Ah, I get it. Thanks a bunch!
Answer: Solution
$$\frac{4x^2+8x+13}{6(x+1)}=\frac{4(x+1)^2+9}{6(x+1)}=\frac{2}{3}(x+1)+\frac{3}{2(x+1)}\geq 2$$
with the equality holding if and only if $\dfrac{2}{3}(x+1)=\dfrac{3}{2(x+1)}$,namely, $x=\dfrac{1}{2}.$
Answer: Hint: by polynomial euclidean division $\;\dfrac{4x^2+8x+13}{6(x+1)} = \dfrac{1}{6}\left(4(x+1) + \dfrac{9}{x+1}\right) \ge \ldots\,$