Allow shipping that is calculated using a base rate plus a rate per item?

Question: I figured this would be built in, but it seems it is not. See here:

I have two options:

Flat rate: I can make it 9.99 USD, but then if it's 100 items, it's still 9.99 USD.
I can make it 1 USD per item, but I als don't want that.

What I want is a base rate of 10 USD, and then 1 USD per item after that. Anyone know how to do that?
UPDATE
There is some information available for Commerce 1.0 here, but hardly any information on Commerce 2. This is basically all there is.
Can it be that Commerce 2 doesn't support this? I mean, nowhere can I see "shipping rules" or anything related to that that allows me to set up these rules?
(I miss UberCart)
Answer: Programmatically create your own custom shipping method in a custom module.
Example, custom module called "mymodule":
/modules/custom/mymodule/src/Plugin/Commerce/ShippingMethod/CustomRate.php
<code><?php

namespace Drupal\mymodule\Plugin\Commerce\ShippingMethod;

use Drupal\commerce_shipping\Plugin\Commerce\ShippingMethod\ShippingMethodBase;
use Drupal\commerce_price\Price;
use Drupal\commerce_shipping\Entity\ShipmentInterface;
use Drupal\commerce_shipping\PackageTypeManagerInterface;
use Drupal\commerce_shipping\ShippingRate;
use Drupal\commerce_shipping\ShippingService;
use Drupal\Core\Form\FormStateInterface;
use Drupal\state_machine\WorkflowManagerInterface;

/**
 * Provides the FlatRatePerItem shipping method.
 *
 * @CommerceShippingMethod(
 *   id = "custom_rate",
 *   label = @Translation("Custom Rate"),
 * )
 */
class CustomRate extends ShippingMethodBase {

  /**
   * Constructs a new FlatRate object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\commerce_shipping\PackageTypeManagerInterface $package_type_manager
   *   The package type manager.
   * @param \Drupal\state_machine\WorkflowManagerInterface $workflow_manager
   *   The workflow manager.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, PackageTypeManagerInterface $package_type_manager, WorkflowManagerInterface $workflow_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $package_type_manager, $workflow_manager);

    $this->services['default'] = new ShippingService('default', $this->configuration['rate_label']);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
        'rate_label' => '',
        'rate_description' => '',
        'rate_amount' => NULL,
        'services' => ['default'],
      ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    $amount = $this->configuration['rate_amount'];
    // A bug in the plugin_select form element causes $amount to be incomplete.
    if (isset($amount) && !isset($amount['number'], $amount['currency_code'])) {
      $amount = NULL;
    }
    // A bug in the plugin_select form element causes $base_amount to be undefined.
    if (!empty($this->configuration['base_amount'])) {
      $base_amount = $this->configuration['base_amount'];
    }
    else {
      $base_amount = null;
    }

    $form['rate_label'] = [
      '#type' => 'textfield',
      '#title' => t('Rate label'),
      '#description' => t('Shown to customers when selecting the rate.'),
      '#default_value' => $this->configuration['rate_label'],
      '#required' => TRUE,
    ];
    $form['rate_description'] = [
      '#type' => 'textfield',
      '#title' => t('Rate description'),
      '#description' => t('Provides additional details about the rate to the customer.'),
      '#default_value' => $this->configuration['rate_description'],
    ];
    $form['base_amount'] = [
      '#type' => 'commerce_price',
      '#title' => t('Base amount'),
      '#default_value' => $base_amount,
      '#required' => TRUE,
      '#description' => t('Charged once.'),
    ];
    $form['rate_amount'] = [
      '#type' => 'commerce_price',
      '#title' => t('Rate amount'),
      '#default_value' => $amount,
      '#required' => TRUE,
      '#description' => t('Charged for each quantity of each shipment item.'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    if (!$form_state->getErrors()) {
      $values = $form_state->getValue($form['#parents']);
      $this->configuration['rate_label'] = $values['rate_label'];
      $this->configuration['rate_description'] = $values['rate_description'];
      $this->configuration['base_amount'] = $values['base_amount'];
      $this->configuration['rate_amount'] = $values['rate_amount'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function calculateRates(ShipmentInterface $shipment) {
    $base_amount = Price::fromArray($this->configuration['base_amount']); // create base price
    $amount = Price::fromArray($this->configuration['rate_amount']);
    $quantity = $shipment->getTotalQuantity();
    $ship_price = $amount->multiply($quantity);
    $ship_price = $ship_price->add($base_amount); // add base
    $rates = [];
    $rates[] = new ShippingRate([
      'shipping_method_id' => $this->parentEntity->id(),
      'service' => $this->services['default'],
      'amount' => $ship_price,
    ]);

    return $rates;
  }

}
</code>
Result


Is possible to update a project that has been installed from the archive file?

Question: I'm very new to composer, I've only used it to install the occasional necessary library for our D8 projects. At each Drupal update I normally run
drush up drupal

Which (among other things) replaces the vendor folder and composer.json, so on sites with library dependencies, I need to re-run
composer require [library]

Aware of the touted benefits of Composer as a dependency manager, I want to use composer to maintain our Drupal projects. However I've run into issues, namely that
composer update

or
    composer update drupal/core --with-dependencies
both give me "Nothing to install or update". After some reading, I found this resource https://github.com/drupal-composer/drupal-project. With this unzip, if I run
composer install

I get the correct latest version of Drupal installed in ./web. But when I use the yaml from the template composer.json file in my own composer.json file I still get "Nothing to install or update".
My folder structure is identical to the .zip distribution, so /core and /vendor and /sites etc are all in the same folder, so I have obviously adjusted the composer.json file according. But it doesn't matter what I do, I just get
"Nothing to install or update"
"Nothing to install or update"
"Nothing to install or update"
So, I'm beginning to think that composer update with or without dependencies REQUIRES YOU TO HAVE INSTALL THE DRUPAL 8 PROJECT WITH COMPOSER TO BEGIN WITH.
Is that right? If so, then I can move on.
If not then I need to know what I'm doing wrong. Right now it's not a big deal and I can manage the update process, but it seems each new project requires more and more non-core libraries, so I know composer will save me a lot of time in the future.
TL;DR - Can someone give me a kickstart to configuring my EXISTING, WORKING PRODUCTION SITES so I can use composer to update them, the usual ReadMe's don't seem to work properly with sites that weren't also installed with composer.
Answer: I got this working, I was very close but removing /vendor and composer.lock was what helped in the end.
Here are the steps from the top:

add the line
        "drupal/core": "~8.1"
to the 'require' statement (or update it to whatever version you require - in my case ^8.0 - latest Drupal 8 release).
Remove the drupal/core line from the 'replace' statement.
Add the following line somewhere (at the end? I believe this should replace the existing repositories statement, more information here.
):
"repositories": {
    "drupal": {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
}

Remove the /vendor folder
Remove the composer.lock file
Run your core update as follows
composer update drupal/core --with-dependencies

Comment: You can add a repository via the command-line by running `composer config repositories.drupal composer https://packages.drupal.org/8`. Also if you are managing everything with composer you can start doing `composer require drupal/` instead of manually modifying composer.json. Also, running `composer update` will update your composer.lock file so you don't need to delete it. If you're using Drupal 8.0.x, then you can't really manage things with composer without composer manager.
Comment: @mradcliffe I recently converted a D8 site from drush management to composer management.  Nuking `compsoser.lock` did seem to be a necessary step (still don't know why) to get this to work.
Comment: Two notes.  Personally, I like to pin core to a precise version so I am never surprised (eg,`"drupal/core": "8.2.5",`) to prevent update hook surprises.  Also, adding the `extra` section from the page you reference ensures modules/themes/etc end up where you want them.
Comment: The drupal-merge-plugin might help with not having to delete vendor or the lock file. I use that to bridge the gap between drush make and composer since I have some problems with using composer directly.
Comment: Once I get the hang of what the correct yaml is, I'll look into the correct composer commands. Thanks mradcliffe
Comment: @mpdonadio - I would assume that modules and themes just automatically go to /modules and /themes, no?
Comment: @mradcliffe - 8.2.6 was released yesterday, and I didn't need to remove .lock or /vendor to update, 'composer update drupal/core --with-dependencies' worked as expected.
Comment: @RominRonin Only when you specify the locations, https://www.drupal.org/node/2718229
Comment: If only i had found your answer before. I've struggled hours to find a solution. Do I have to change this manually each time I want to update or was it an issue with composer.json ?


IBM Worklight 6.1 - Tile badge from push notification never cleared on Windows Phone 8

Question: I'm using Worklight 6.1 and sending push notifications to Windows Phone 8.  It is working swell, except for the tile badge.  It is not being cleared when I use the tile to launch the app. The notification that I'm sending is:
{"APNS":{ … },"GCM":{ … },"SMS":{ … },"MPNS":{"raw":{"payload":{}},"toast":{"text1":"Luggage Tracker","text2":"You have 3 available messages"},"tile":{"count":3}}}

The toast message pops up, and the tile gets the badge, but the badge doesn't clear when I  launch the app, and the only way I can find to clear it is to have the server push another notification with: tile {count:0}
Is there any way for the app to clear the tile badge?
Answer: Update: the WL.Badge API is iOS-only. I have submitted an RFE to either enhance it or create specialized API for clearing the tile in Windows Phone 8 as well.
So the solution at this time, as I see it, is to create a Cordova plug-in to update the count... I found this plug-in. Perhaps you take from it when you need: https://github.com/sgrebnov/incubator-cordova-wp8/blob/master/plugins/www/plugins/LiveTiles/liveTilesExample.html

Use the WL.Badge.setNumber() API method.
Setting 0 should clear the badge from the tile.
WL.Badge.setNumber(0);

You can probably use this in the same logic that handles the received push (the one that shows the Toast pop up notification).
Worklight does not provide any mechanism to handle the badges other than methods to set or remove so you need to write one of your own.
Comment: WL.Badge is undefined for Window Phone 8
Comment: Awesome. :) I'll ask the feature implementor about this; if it's a defect, I'll open one...
Comment: @DavidDhuyveter, fixed for Worklight 6.2; setNumber can now also be used to change the number of notifications displayed on the tile in WP8.


How do I contribute a version of the same module for the latest core version?

Question: I have contributed a module for Drupal 7; now I am interested in contributing the Drupal 8 version of the same module.
When I started creating the Drupal 7 version; I had all the instructions (under VERSION CONTROL of the project); now I need instructions in order to start with the Drupal 8 of the module.
So, I am looking for GIT instructions.
Comment: There is no specific git instructions for Drupal 8.... What you should do is to create a 8.x branch.
Answer: Drupal.org apparently doesn't give information for Drupal 8, in the Version control tab of projects. I checked for a project with a Drupal 8 version (the Token module), but even selecting a Drupal 8 branch, the information given is for Drupal 7.
That said, there isn't much difference, with Drupal 8. What I report here are the adapted instructions for Drupal 8.

Creating Releases
See the naming conventions for a complete description of how to name branches and tags so you can create releases.
Branch for a dev release
This creates and checks out a new branch in one command, then pushes it to Drupal.org.
git checkout -b 8.x-1.x
git push -u origin 8.x-1.x

Tag for a stable release
git checkout  8.x-1.x
git tag 8.x-1.0
git push origin tag 8.x-1.0


Estilização de Option via CSS

Question: fiz alguns Select e dentro deles há Options.
Tentei estilizar o Option, só que não estou conseguindo, estou fazendo algo errado?
HTML:

 <select>
  <option>Todos</option>
  <option>teste1</option>
  <option>teste2</option>
 </select>

CSS:
.imobSelect select {
font-family: "Trebuchet MS", Helvetica, sans-serif;
background: transparent;
width: 233px;
color: #474747;
padding: 8px 5px 5px 5px;
font-size: 12px;
line-height: 1;
border: 0;
border-radius: 0;
height: 34px;
-webkit-appearance: none;}

.imobSelect option {
    height: 30px;
    border: 1px solid #cbcbcb;
    padding-left: 17px;
    padding-top: 12px;}

.imobSelect {
    width: 207px;
    height: 34px;
    overflow: hidden;
    background: url(../images/arrow.jpg) no-repeat right #f0f0f0;
    border-radius: 3px;}

Onde estou errando?
Comment: O que está acontecendo de errado?
Comment: O que está faltando?
Comment: Se você acessar aqui www.felipestoker.com/imob verá que os Options não são estilizados no Chrome. E que no Mozilla, ele fica com uma borda preta ao redor.
Comment: Poderia esclarecer qual é a sua dúvida? Está difícil de entender o que vc precisa.
Comment: Qual era exatamente o objetivo com esses estilos? Qual parte não ficou como você gostaria? Qual a dúvida? Mais detalhes ajudariam a esclarecer.
Comment: Já encontrei o que precisava. Estilizar Options é chato demais, cada navegador trata ele com particularidades.
Answer: Options são realmente um dos piores elementos de se estilizar. O suporte dado pelos navegadores varia muito. Eu não recomendaria tentar estilizar esses elementos se você quer consistência do visual entre navegadores.

Chrome: aceita color, background-color e mais nada que eu testei
IE8: aceita somente color e background-color, mas além disso, quando um dos options está selecionado, o texto do select fica igual ao do option
Firefox: aceita todos os estilos que eu testei

Solução javascript
Se uma solução javascript for aceitável, eu recomendaria o chosen. Ele substitui o select por ul e lis, que podem ser estilizados. Este plugin depende do jQuery, então talvez não seja uma opção para o seu caso.
Comment: Verdade, estava analisando as tags de forms, e realmente é muito chato estilizar sem usar Javascript. Vou ter que analisar algum plugin e usá-lo. Muito obrigado.
Answer: Alterei a linha de bakcground ( removi a cor de fundo e funcionou normalmente )
background: url(../img/arrow.jpg) no-repeat right;

Verifique se era esse o problema.
Comment: É boa prática a quem dá voto negativo explicar porquê. Somos uma comunidade e assim aprendêmos mais uns com os outros.
Answer: Sempre que você tentar estilizar um option você não irá estilizá-lo, apenas algumas atribuições dadas aos selects, serão também atribuidas aos options. Por Exemplo
select{
    width: 250px;
    height: 50px;
    font-size: 20px;
    background: #f2f2f3;
    padding-left: 100px
}

No caso do text-align: center isso não funciona, para alinhar basta usar o padding-left. E nos options ele receberam a formatação do select porém ficarão com o seu tamanho e outros requisitos padronizados pelo navegador.
E se você quiser estilizar aquela setinha dos selects. Aqui existe um exemplo em jquery

Estilização de Option via CSS


Calculating Rolling Mean Over Time

Question: I have a data frame as follow:

df = pd.DataFrame([['2019-01-01',2,5],['2019-01-02',15,8],['2019-01-03',1,9],['2019-01-04',10,20],['2019-01-05',5,15]],columns = ['date','data1','data2'])

         date  data1  data2
0  2019-01-01      2      5
1  2019-01-02     15      8
2  2019-01-03      1      9
3  2019-01-04     10     20
4  2019-01-05      5     15

I would like to calculate rolling mean for each two days and put the result into a new data frame. For example for date 2019-01-01 and 2019-01-02, the mean for data1 will be 8.5 and mean for data2 will be 6.5, then for date 2019-01-02 and 2019-01-03, the mean for data 1 will be 8 and for data2 will be 8.5. My original dataframe is larger than this, so I would prefer not to do this one by one and I prefer to create loop or if possible vectorization. My aim is to have the below data frame as result
         date  data1  data2
0  2019-01-02    8.5    6.5
1  2019-01-03    8.0    8.5
2  2019-01-04    5.5   14.5
3  2019-01-05    7.5   17.5

My attempt:
def my_attempt(df):
    result = []
    start_date = datetime.datetime.strptime('2019-01-01','%Y-%m-%d')
    start_date = start_date.date()
    for i in range(5):
        df1 = df.loc[df['date'].isin([str(start_date + datetime.timedelta(days = i)),str(start_date + datetime.timedelta(days = i) + datetime.timedelta(days = 1))])]
        df1_mean = df1.mean()
    result += df1_mean
    return result

THis does not work because df1.mean() will give different format than what I want to get and it is not possible to stack the result by using result+=df1_mean.
Comment: [`rolling`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html) is probably what you are looking for
Comment: Does this answer your question? [Rolling Mean on pandas on a specific column](https://stackoverflow.com/questions/43437657/rolling-mean-on-pandas-on-a-specific-column)
Comment: `df.rolling(2).mean()` or `df[['date']].join(df.rolling(2).mean()).iloc[1:]`
Comment: Why aren't you using the date-related functionality of Pandas?!
Answer: Since your question seems to be about time, it's best to convert date to datetime:
df.date = pd.to_datetime(df.date)

df.rolling('2D', min_periods=2, on='date').mean().dropna()

Output:
      date  data1  data2
2019-01-02    8.5    6.5
2019-01-03    8.0    8.5
2019-01-04    5.5   14.5
2019-01-05    7.5   17.5

Answer: I think it's better to use Quang Hoang's solution, but another approach would be:
(df.set_index('date').iloc[1:] + df.set_index('date').shift(1).iloc[1:]) / 2

Calculating Rolling Mean Over Time


Does python-memcache use consistent hashing?

Question: I'm using the python-memcache library, and I'm wondering if anyone knows if consistent hashing is used by that client as of 1.44.
Answer: If you need something like that you might be interested in hash_ring
Answer: From a quick view into the source code: No it does not. It uses server = hash_key % len(servers) and round-robin if offline/full servers are encountered.
Comment: Yeah my bad, I should have viewed the source myself. Thanks.


Lottie Framework issues - animation won't run

Question: I tried running an animation out of a JSON file which was created in After Effects with the Bodymovin Extension, but unfortunatelly I can't get the animation running in my simulations. The JSON file itself works since I've demoed it on a HTML page and it works fluently. So there must be something wrong in the code. I've already tried out many tutorials, so many variations of coding lines with no success.
The JSON file is simply dragged into my Xcode project, which is called "fire". The only I have to do is inside the "ViewController" according to many tutorials. There are no issues building it but when simulating it, there's only a blank screen on the iPhone. And right after running, it automatically opens the debugging console in Xcode but there aren't any errors.
ViewController.swift:
import UIKit
import Lottie

class ViewController: UIViewController {

    @IBOutlet var animationView: AnimationView!
    override func viewDidLoad() {
        super.viewDidLoad()

        let animation = Animation.named("fire")
        animationView.animation = animation
        animationView.contentMode = .scaleAspectFit
        animationView.loopMode = .loop
        animationView.play()
    }
}

I've noticed in my research that the Lottie commands are changing from time to time. This should be the latest correct commands, but I might be wrong.
After making some given corrections, I'm getting a crash in one thread after successfully building. Here's a screenshot:
Answer: Add the animation view to your top view.
topView.addSubview(animationView)

Make sure you setup the constraints also.
    let xConstraint = NSLayoutConstraint(item: animationView, attribute: .centerX, relatedBy: .equal, toItem: topView, attribute: .centerX, multiplier: 1, constant: 0)

    let yConstraint = NSLayoutConstraint(item: animationView, attribute: .centerY, relatedBy: .equal, toItem: topView, attribute: .centerY, multiplier: 1, constant: 0)

    NSLayoutConstraint.activate([xConstraint, yConstraint])

Comment: Dont update the question. If you have new issue, create a new question. This way will be helpful for other developers.
Comment: I'm getting an unresolved identifier for "topView".
Comment: or u can simply set the frame self.animationview.frame = self.topview.frame
Comment: add self.view instead of topView
Comment: I just added topView and animationView terms just to clarify the flow
Comment: Please check the above update I made of the situation
Answer:     let animation = Animation.named("fire")
    animationView.animation = animation
    animationView.contentMode = .scaleAspectFit
    animationView.loopMode = .loop
    animationView.play()
    animationview.frame = self.view.frame
    self.view.addSubview(animationView)

Change the view to a subview if u need it to fit in a specific view
Comment: @zumry mohamed answer is correct.. I just posted this for clarification


Toeplitz Operator question

Question: Let $\chi_1$ be the map on the unit circle defined by $\chi_1(e^{it})=e^{it}$.  Let $T_{\chi_1}$ be the corresponding Toeplitz operator.  Consider the map $T_{\chi_1}^* T_{\chi_1}- T_{\chi_1} T_{\chi_1}^*$ where $T_{\chi_1}^*$ is the adjoint of $T_{\chi_1}$.  The book I am reading says the map  $T_{\chi_1}^* T_{\chi_1}- T_{\chi_1} T_{\chi_1}^*$ is a nonzero rank one.  It is easy to see it is nonzero but I cannot see why it is rank one.
Answer: If you move your operators to $\ell^2(\mathbb N)$, your $T_{\chi_1}$ goes to the unilateral shift $S$. So you are looking at $S^*S-SS^*$. Now, as $S$ is an isometry, $S^*S=I$. And $SS^*=I-E_{11}$, where $E_{11}$ is the rank one operator onto the first vector in the canonical basis. So
$$
S^*S-SS^*=I-(I-E_{11})=E_{11},
$$
rank-one.
If you are not happy with this, you can do the computation directly. Let $f=\sum_{n=0}^\infty c_ne^{itn}$. Then it is easy to see that $T_{\chi_1}^*T_{\chi_1}f=f$. Also
$$
T_{\chi_1}T_{\chi_1}^*f=T_{\chi_1}P_He^{-it}f=T_{\chi_1}P_H\sum_{n=0}^\infty c_ne^{it(n-1)}=T_{\chi_1}P_H\sum_{n=-1}^\infty c_{n+1} e^{itn}=T_{\chi_1}\sum_{n=0}^\infty c_{n+1} e^{itn}=\sum_{n=0}^\infty c_{n+1} e^{it(n+1)}=\sum_{n=1}^\infty c_{n} e^{itn}.
$$
We conclude that
$$
(T_{\chi_1}^*T_{\chi_1}-T_{\chi_1}T_{\chi_1}^*)f=f-\sum_{n=1}^\infty c_{n} e^{itn}=c_0.
$$
Comment: How do you move your operators to l^2(N)
Comment: Let $e_1,e_2,\ldots$ be the canonical basis of $\ell^2(\mathbb N)$. Then $V:e^{int}\mapsto e_n$ maps one orthonormal basis into another one, and thus induces a unitary operator $H^2\mapsto\ell^2(\mathbb N)$.

Toeplitz Operator question


g++ saying function doesn't exist even when including the proper header

Question: So I am working on some homework for my uni and need to convert a string to a float. For whatever reason g++ is complaining that the 'stof' function doesn't exist. Although I have included the required  header. Here is my code, the error is on the line that says
holder = stof(x.substr(0, end_of_num));
<code>#include <iostream>
#include <string>
#include <list>

using namespace std;

float process_func(string x);
bool isPartOfNum(char x);

int main() {
    string x;
    while (true) {
        cout << "input a string" << endl;
        getline(cin, x);
        cout << process_func(x);
    }
    return 0;
}

float process_func(string x) {
    int end_of_num =0;// used to find last index from num
    int negMult = 1; //used to multiply value at end if there was a negative
    bool onNum = false; //used to
    list <float> numList;
    list <char> operList;

    if ((x.at(0) < 48 || x.at(0) > 57) && x.at(0) != '-') //check if start of string doesnt have a number or negative symbol
        return -1;
    if (x.at(0) != '-')
        negMult = -1;

    float holder;// temp holder for floats
    int i = 0;
    while (i<x.length()) {
        if (isPartOfNum(x.at(i))) {
            end_of_num++;
            onNum = true;
        }
        else if (onNum) {
            holder = stof(x.substr(0, end_of_num));
            numList.push_back(holder); //adds num as float to list
            x.erase(0, end_of_num + 1); //+1 removes the space after the number before the operator
            end_of_num = 0;
            onNum = false;
        }
        if (x.at(i) == '+' || x.at(i) == '-' || x.at(i) == '*' || x.at(i) == '/') {
            operList.push_back(x.at(i));
        }
    } //at this point both lists should be full of all needed pieces of info

    int answer = 0;
    int temp;
    bool firstOper=true; // used to hold first operation

    while (numList.size() >=2) { //requires at least 2 entries for last operation
        while (!operList.empty()) {
            temp = numList.front();
            numList.pop_front();
            if (operList.front() == '+') {
                if (firstOper) {
                    answer = temp + numList.front();
                    numList.pop_front();
                    firstOper = false;
                }
                else {
                    answer += temp;
                }
            }
            else if (operList.front() == '-') {
                if (firstOper) {
                    answer = temp - numList.front();
                    numList.pop_front();
                    firstOper = false;
                }
                else {
                    answer -= temp;
                }
            }
            else if (operList.front() == '*') {
                if (firstOper) {
                    answer = temp * numList.front();
                    numList.pop_front();
                    firstOper = false;
                }
                else {
                    answer *= temp;
                }
            }
            else if (operList.front() == '/') {
                if (firstOper) {
                    answer = temp / numList.front();
                    numList.pop_front();
                    firstOper = false;
                }
                else {
                    answer /= temp;
                }
            }
            operList.pop_front();
        }
    }
    return answer;
}

bool isPartOfNum(char x) {
    if ((x >= 48 && x <= 57) || (x == '-' || x == '.'))
        return true;
    return false;
}
</code>
Comment: Did you enable c++11 as standard (in case you are using an older GCC version)? https://en.cppreference.com/w/cpp/string/basic_string/stof
Comment: I cannot [reproduce your error](http://coliru.stacked-crooked.com/a/195ea420050f2911), some others though.
Comment: You can replace those magic numbers 48 and 57 with `'0'` and `'9'` respectively. It makes the code vastly more clear and makes the comment you attached a lot more redundant.
Comment: no I did not enable c++ 11, how can i do that
Comment: https://stackoverflow.com/questions/16886591/how-do-i-enable-c11-in-gcc
Comment: You should include the exact command you passed to the compiler and the exact error you got. Otherwise, we have to do a lot of guessing.
Answer: Solved by compiling using c++ 11


Left handed Accordion western musical instrument players

Question: Accordion western musical instrument
Are there any Left handers who can play the Accordion western musical instrument?
Comment: @Aaron There are left handed pianos, if you remember my answer to your question: https://music.stackexchange.com/questions/107883/what-modern-innovations-have-been-are-being-made-for-the-piano/109737#109737
Comment: Since it takes two hands to play the accordion, it hardly matters whether one is left or right handed.
Comment: @Aaron I think it was sarcasm. There absolutely are left handed guitars. But I think pianos are a better analogy. Some web searching suggests that left handed people who play accordion just play it the same way right handed people play it. Just like piano.
Comment: @Aaron - whilst there may well not be any left hand snare drums, there are sure as heck drum *kits* set up for lefties.
Comment: @Aaron is this the reason there aren't left handed guitars?
Comment: @ojs No idea. I thought there were left-handed guitars, though. But there's aren't left-handed pianos or snare drums.
Comment: @Aaron but you use both hands to play the guitar, so it should hardly matter whether one is left or right handed and special left handed instrument shouldn't be necessary. Right?
Comment: Do you have any reason to think that left-handed people just don't play accordion ever? I mean, if you asked "are there left-handed people who play [any given kind of musical instrument]?", I'm pretty sure the answer would always be "yes". Or did you actually mean to ask something more specific about playing accordion while left-handed? If so, then don't be shy, ask the actual question. Hopefully there may even be someone able to answer.
Comment: Pretty sure I asked a similar question a long time ago - about 'handed/non handed' instruments.
Comment: @ojs - it's the *fingers* that are more in question with reference to guitar playing rather than 'hands' - and I've always argued that actually, in a lot of playing, the r.h. fingers need to be doing more than the l.h. So, we may all have been playing in the least effective way!
Comment: Prince William plays the accordion? Citation needed!
Comment: Thanks. For example: Prince William a left hander will have a normal piano left hand side and button piano right hand side or vice versa in the Accordion western musical instrument. Will  the Left handers find it difficult to learn and play the Accordion?
Comment: Thanks Brian. Just as a example of a Left hander. Prince William. Example Applicable for all left handers.
Answer: You might want to look up Rudolf Würthner.  After he lost several fingers of the right hand in a harvesting machine accident, he converted to playing accordion upside down.  He is one of the more famous composers for accordion, led the Hohner company orchestra until its dissolution, and wrote methods both for B system accordion (his own instrument) and C system accordion.  His own Morino instrument bore the Hohner logo in a half-circle so that it looked reasonable both when played upside down and rightside up.
However, he is an oddity.  I think I read of some other self-learnt person who played upside down because of accidentally starting the wrong way round and not relearning, but as a rule, lefthanders play accordions just like righthanders do.
One practical reason for the uniform use (like with violins) is practical: seating order in a group is quite shaked up if two persons play with facing bellows movement.
In contrast, a guitar does not require a lot of space beyond the instrument itself on either side.  And of course, in a small combo, the McCartney/Lennon signature look (with McCartney playing lefty) can even be an eyecatcher.
Comment: Please realise that half the world hasn't woken yet, to even see the question, let alone answer it.
Comment: That bit about the guitar doesn't seem right. It's a pretty long neck. I think the difference is that it doesn't move in and out?
Comment: Thanks. For my curiousity to begin with who is a beginner, between guitar and accordion, which could be easier to learn the musical instrument between the two? Or between three Guitar, Accordion & Violin?


Should I edit a closed issue with the issue summary template?

Question: Once you go to create a new issue in drupal.org you can see a message that says:

Learn how to report an issue. Use the issue summary template to
  summarize the issue in the Description field below. Others can also
  change the summary. Editing the summary does not subscribe you to the
  issue or notify subscribers, so add a comment describing your changes
  after any significant edit.

But there are some closed issues like Incorrect call to urldecode() in the www.drupal.org site that don't follow the template format.
Should I edit a closed issue with the issue summary template?
Answer: Yes. It's completely appropriate to edit an issue to clarify the findings, solutions, workarounds etc. and make it easier for people who may look to that issue for reference.
Comment: thanks, this can include edit the commit message to change the title according to the edit?
Comment: All too often the paperwork is not covered
Comment: @LittleCoding What's the paperwork? Sorry but I'm not an english speaker.
Comment: The supporting documentation would be the "paperwork".


Sigma notation for repetitions of 1.01(n+200)

Question: This sounds odd but, there was a math question in my textbook which intrigued me. So it goes 'Sarah puts $200 in her account every month, which is subject to 1% interest. Show the value of money in her account after x months'. So I assumed that you'd need to use the sigma notation in order to reduce using … . This might be a really odd question but does anyone know the answer of how to represent this formula?
$$x_{n+1}=1.01(x_n+200)$$
$$x_1=0$$
$$x_n$$ represents how much was in the account on the nth month prior to placing the $200 in the account on that month.
x represents the value of money in the bank. Essentially, I'm asking whether there is a simplified method of finding the value of money after y months
Comment: Do some investigating. What did she start with. What did she have after month 1, month 2, and month three. Can you see a pattern?
Comment: This has nothing to do with measure theory.
Comment: If you edit the question to show us your answer using "..." we may be able to tell you a fancier way to write it.
Answer: The "sigma notation" is just a summation, so you don't use it directly to convey the notion of interest.  This question requires you to think a bit more about how interest and deposit timing affects what's in the bank account.
One way to think about it is to imagine that instead of putting each month's deposit into the same account, she puts it into a different account each month, with each account earning the same $1$ percent interest.  How much money does she have in the $x$ different accounts after $x$ months?  Is it different from what it would be if she put them into the same account?
The summation simply permits you to denote the addition of what's in all the $x$ accounts together.

P.S.  On a side note, I have to say that I find the use of $x$ to denote an integer number of months a little irritating.  Downvoting the textbook.
Answer: In Month $x=1$, The Account value $A_1$ is $200$.
In Month $x=2$, she puts in an extra $200$, and gets $1\%$ interest on what she already had, so $A_2=402$.
Then it follows $A_{n+1}=1.01(A_n)+200$
What we have here is a recurrence relation. We need to find a closed form from this.
$$A_1=200$$
$$A_2=1.01(200)+200$$
$$A_3=1.01(1.01(200)+200)+200)=1.01^2(200)+1.01(200)+200$$
$$A_4=1.01(1.01^2(200)+1.01(200)+(200))+200$$
$$A_4=1.01^3(200)+1.01^2(200)+1.01(200)+200$$
Note that $A_1=200$ and the pattern is easily spotted:
$$A_n=200\sum_{k=0}^{n-1}{[(1.01)^k]}$$
Sum notation is indeed required as suggested in your question.
Comment: Thank you for the answer. Do you know of anywhere that I could learn more about recurrence relations, as I would like to understand what you did to a greater extent?
Comment: No problem. All I did to find the recurrence relation was consider what happened at each step, the previous month's balance was multiplied by $1.01$ to mark the interest, and then $200$ was added. You just need to be able to convert the worded question into a mathematical expression you can use. Does the second part of the answer (From "$A_2=1.01(A_1)+200$" down) make sense?
Comment: I understand it up to finding the pattern. I do see that it works, but I'm just not sure how you managed to put it into a sum notation.
Comment: I've changed $A_1$ for $200$ throughout to make it a bit clearer. Do you see how the power of $1.01$ in front of each $200$ term increases by $1$ each time, and then the term $200$ is added on the end? I can use this and that $200=1.01^0(200)$ to form the series I gave.
Comment: So based off my sequence for example: $$A_7=200[1.01^6+1.01^5+1.01^4+1.01^3+1.01^2+1.01^1+1.01^0]$$
Comment: Ok wow I get it now, thanks for that. That honestly blew my mind and now I feel stupid for not getting it before. Thank you so much!


Output wrong eye position using CIfacefeature and SquareCam

Question: I am trying to write code which put a sticker on eyes and the code is based on SquareCam.
It detects faces well, but when I tried to output my image on left eye, it always gives wrong position even though I used the same ways on finding face rect.
There are results on my phone.

And the code is here.
  for ff in features as! [CIFaceFeature] {
        // find the correct position for the square layer within the previewLayer
        // the feature box originates in the bottom left of the video frame.
        // (Bottom right if mirroring is turned on)
        var faceRect = ff.bounds

        let temp = faceRect.origin.x
        faceRect.origin.x = faceRect.origin.y
        faceRect.origin.y = temp
        // scale coordinates so they fit in the preview box, which may be scaled
        let widthScaleBy = previewBox.size.width / clap.size.height
        let heightScaleBy = previewBox.size.height / clap.size.width
        faceRect.size.width *= widthScaleBy
        faceRect.size.height *= heightScaleBy
        faceRect.origin.x *= widthScaleBy
        faceRect.origin.y *= heightScaleBy

        var eyeRect : CGRect
        eyeRect = CGRect()
        eyeRect.origin.x = ff.leftEyePosition.y
        eyeRect.origin.y = ff.leftEyePosition.x
        eyeRect.origin.x *= widthScaleBy
        eyeRect.origin.y *= heightScaleBy

        eyeRect.size.width = faceRect.size.width * 0.15
        eyeRect.size.height = eyeRect.size.width

        if isMirrored {
            faceRect = faceRect.offsetBy(dx: previewBox.origin.x + previewBox.size.width - faceRect.size.width - (faceRect.origin.x * 2), dy: previewBox.origin.y)
            eyeRect = eyeRect.offsetBy(dx:previewBox.origin.x + previewBox.size.width - eyeRect.size.width - (eyeRect.origin.x * 2),dy : previewBox.origin.y)

        } else {
            faceRect = faceRect.offsetBy(dx: previewBox.origin.x, dy: previewBox.origin.y)
            eyeRect = eyeRect.offsetBy(dx: previewBox.origin.x, dy:previewBox.origin.y)

        }

        print(eyeRect)
        print(faceRect)

        var featureLayer: CALayer? = nil
        var eyeLayer : CALayer? = nil
        // re-use an existing layer if possible
        while featureLayer == nil && (currentSublayer < sublayersCount) {
            let currentLayer = sublayers[currentSublayer];currentSublayer += 1
            if currentLayer.name == "FaceLayer" {
                featureLayer = currentLayer
                currentLayer.isHidden = false
                eyeLayer = featureLayer?.sublayers?[0]
                //eyeLayer?.isHidden = false
            }
        }

        // create a new one if necessary
        if featureLayer == nil {
            featureLayer = CALayer()
            featureLayer!.contents = square.cgImage
            featureLayer!.name = "FaceLayer"
            previewLayer?.addSublayer(featureLayer!)

            eyeLayer = CALayer()
            eyeLayer!.contents = eyes.cgImage
            eyeLayer!.name = "EyeLayer"
            featureLayer?.addSublayer(eyeLayer!)
        }

        featureLayer!.frame = faceRect
        eyeLayer!.frame = eyeRect

Comment: I have write a [demo](https://github.com/kudocc/CCKit/blob/master/CCKitDemo/coreImage/FaceDetectorViewController.m) with objective-c, hope it will help.
Comment: I am facing the same problem. Did you found a solution?
Answer: 0,0 is at bottom left for the eyePositions, so you have to eyePosition.y = image.size.height - eyePosition.y to be in the same coordinate system as frames.


Does DirectX / Media Foundation have a high-performance intermediate data representation format?

Question: I just used D3D11. I need to intercept the surface in the device / swap X context of thread a and put it into "inter-media-data". This inter-media-data can be locally rendered in the device / swap Y context of another thread B. for performance reasons, I hope that the inter-media-data can copy and operate the original data in the video memory instead of in the system memory as much as possible, and it's better to be independent of these contexts. For example, I hardware encode it as H264 and send it out over the network in another work thread. I tried IMFSample, but I don't know if it can achieve the effect, or if there is a problem with my thinking?

I call MFCreateDxgiSurfaceBuffer and MFCreateSample from the backbuffer of device / swap X to get IMFSample, but I'm not sure whether the sample is related to device / swapx or not? It is hoped that when device / swapx is destroyed, this sample will still be valid.
IMFSample can only query ID3D11Texture2D interface through IMFDXGIBuffer, but in device / swap rendering ID3D11Texture2D, neither CopySubresourceRegion nor CreateRenderTargetView method works. Is there any other efficient and simple rendering method?
Answer: There is no (and perhaps no need in) dedicated intermediate format. Media Foundation model is such that it is has a model of samples and buffers which can be implemented with reference to device and API specific data (for example, Direct3D 11). A video frame can be interfaces as IMFSample to Media Foundation, and in the same time have data residing in D3D11 ID3D11Texture2D texture.

I hope that the inter-media-data can copy and operate the original data in the video memory instead of in the system memory as much as possible

You just need to keep your data in video memory, in D3D11 textures for that purpose. It is you to provide DXGI device manager to Media Foundation pipeline and so generally it is you who control the lifetime and parameters of hosting D3D11 device. You can have textures (frames) outlive the video encoding step in the case you need the frames for other purposes. You can have this device be shared with swapchain and use textures for both encoding and presentation needs (it's possible to have ID3D11DeviceContext::CopySubresourceRegion working, in particular).
Comment: I try to understand your suggestion: if you want the original data in the video memory, the better way is to bind IMFSample to ID3D11Texture2D? Because ID3D11Texture2D is created by ID3D11Device and cannot exist without ID3D11Device, in a multithreaded environment, this is equivalent to the requirement: a global ID3D11Device object and multiple local (hWnd < - > swapchain) objects based on its different thread background? In this way, IMFSample life cycle validity is guaranteed.
Comment: Yes, this is how Media Foundation (MF) is designed. You create a pipeline and supply it with a D3D11 device (via device manager). Video frames are "samples" and there is an option to have a texture attached to sample. Capable MF primitives such as hardware H.264 encoder can process this data without pulling data from video memory to system memory. Sample time, you are free to use, including concurrently, the device and the textures outside the pipeline.
Comment: how to attach to sample?


Positionning correctly text over specific image on Android

Question: I have this dice image
I would like to write text on the grey part, but only on this part. I don't want text overstep black line. How I can do ? Moreover text will be added dynamically.
Comment: I am not quite sure about Android but does it not have something like z-index or position:absolute?
Comment: The real problem is to position text correctly and not writing text.
Comment: I would draw the whole thing + draw the rotated text on it (so to be sure it's scaled properly). It wouldn't be so difficult to paint some lines, some fills and 4 ellipses.
Answer: Have a look at this solution :

    Text over image here!

 .image {
    position: relative;
    max-width: 200px;
    max-height: 175px;
}

.image img {
    position: absolute;
    z-index: -1;
}

.image span {
    width: 75px;
    color: #000;
    display: block;
    position: relative;
    top: 15px;
    left: 45px;
    -webkit-transform: rotate(15deg);
    -moz-transform: rotate(15deg);
    -o-transform: rotate(15deg);
    writing-mode: lr-tb;

}

Link to jsfiddle : http://jsfiddle.net/uvky91gd/
Comment: My bad, I precised I want it for android only with keywords


Order tables in prestashop when should be it created?

Question: When should actually an order must be created in PrestaShop, We integrated a local payment module which will redirect to there page and after entering card details and validating the payment it returns  back , and it creates an order at that time.
My problem is that if the payment is declined , (or if I close the browser when the payment is processing  in the payment page ) order is not created in the ps_order table but cart is created  and if I query the bank  with another WEB service the payment response is success for that cart_id and id_order is 0,
but I dont have an order or entry in ps_order table created in my ps_order table  .How to cater this scenario?
Is it correct to create the order (insert into the order table )before payment processing and put current_state field as 3 status 3 means Processing in progress and change the current_state field if the payment is success or not.
select * from ps_orders
this is how the payemnt module does
<code>if($reponseParameters[8]=='00000'){
                // Update the Respose to the ps_networkonline_payment

                    $sql_response = " UPDATE `"._DB_PREFIX_."networkonline_payment` SET response = '".$text."' , `status` = '".$reponseParameters[4]."', error_code = '".$reponseParameters[8]."' WHERE order_id = '".$cart->id."' ";
                    Db::getInstance()->execute($sql_response);

                // Create Order In prestashop pass the values to order-confrimation class
                    $total = (float)$cart->getOrderTotal(true, Cart::BOTH);
                    $this->module->validateOrder($cart->id, Configuration::get('PS_OS_PAYMENT'), $total, $this->module->displayName, 'Transaction Reference: ' . $reponseParameters[5], array(), (int)$currency->id, false, $customer->secure_key);

                // Update the ps_order_payment table to make the PrestaShop Payment success
                     $q_orders  = 'SELECT `reference` FROM ' . _DB_PREFIX_ . 'orders WHERE `id_cart` = ' . (int) $cart->id;

                    if ($r_orders = Db::getInstance()->getRow($q_orders)){
                        Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'order_payment` SET `transaction_id` = \'' . pSQL($reponseParameters[5]) . '\' , `card_brand` = \'' . pSQL($reponseParameters[7]) . '\' WHERE `order_reference` = \'' . pSQL($r_orders['reference']) . '\'');
                    }

                    Tools::redirect('index.php?controller=order-confirmation&id_cart='.$cart->id.'&id_module='.$this->module->id.'&id_order='.$this->module->currentOrder.'&key='.$customer->secure_key);
                return;
            }else{

                $this->error = $reponseParameters[9];//$this->module->getErrorMessage($object->error_code);
                $total = (float)$cart->getOrderTotal(true, Cart::BOTH);
                $this->module->validateOrder($cart->id, Configuration::get('PS_OS_ERROR'), $total, $this->module->displayName, $this->error, array(), (int)$currency->id, false, $customer->secure_key);

            }

        }else{

            //fail
            $this->error = $reponseParameters[9];//$this->module->getErrorMessage($object->error_code);
            $total = (float)$cart->getOrderTotal(true, Cart::BOTH);
            $this->module->validateOrder($cart->id, Configuration::get('PS_OS_ERROR'), $total, $this->module->displayName, $this->error, array(), (int)$currency->id, false, $customer->secure_key);

        }

}
</code>
Comment: In code example you have two "else" blocks with same code, but no "if" for the second "else". But anyway, if I understood correctly, the problem is when external service returns error code, your module do not create the order, right? Order is creating in *PaymentModule::validateOrder* method, did you try to debug this part? I mean if you have no data in DB then something goes wrong
Comment: but my question is when will the order table must be populated with order (order creation happen when ) when it goes to payment pages  and returns or before it goes to the payment page
Comment: yes, you can create/validate order and then change the status.
Answer: What payments modules usually have is a way for the bank to query your website when your customers are redirected to their platform, this way the order is created on your side no matter what happens on their side (leaving you with a freshly created order with a state like "pending payment").
Then the order is updated on the customer's return to your website, by a call from the bank (be it with a status "blocked", "cancelled", or "payment accepted").
Comment: So  you mean  to say create the order  when it redirects to the payment page until waiting for the response of the payment , Is there any example of any payment module  how  do they do this ?
Comment: nah, what I mean is that some most payment module allow you to have an automated response, where a request is sent to your server whenever your customer reaches there platform, thus allowing you to create a "fresh" order.
Comment: That means when  it reached there site the payment module have to create a fresh  order  and make the order state as " pending payment "? In our case this does not happen's and if in some case if I close the browser when i reach there platform/page there is no order created so this is wrong right??


Prove that the mean value of a convolution is the sum of the mean values of its individual parts

Question: Prove that the mean value of a density function convolution, if the mean values exist (they may not for fat-tailed distributions) is the sum of the mean values of the density functions used to make that convolution.
This is a simple one, but, I would like to see what the compact formal notation looks like for it.
Comment: Convolution of densities arises when you add independent r.v.s; but the result you ask for proof of doesn't require independence -- it's quite general that  E(X+Y) = E(X)+E(Y)
Comment: @Glen_b I know, I just want to see it.
Comment: There are *two* calculations involved: one is to demonstrate that integration is additive (which is clear for Riemann integration and involves technical subtleties for other integrals, such as Lebesgue integrals) and the other is to demonstrate that the density of a sum of RVs is the convolution of their densities.  Your question implicitly assumes not only that a demonstration would be uncomplicated, but also that there exists some unique "compact formal notation."  There is not: consult a textbook that is appropriate for your interests and background and use its notation.
Comment: @whuber Is the answer below correct?
Comment: It's a nice answer.  Note that it assumes much of the essential matter: namely, that the PDF of a sum of RVs is given by the convolution of their PDFs.  Although one has to start somewhere in any demonstration, the way your question was asked suggested to me that you were looking primarily for a demonstration of this particular fact.  In comparison, linearity of expectation is obvious and almost trivial to demonstrate, and so would appear to be by far the lesser part of your question.
Comment: @whuber Yes, ideally I would have wanted some iff's, if exists then's.
Answer: Like many demonstrations involving convolutions, it comes down to applying Fubini's Theorem.
Let's establish notation and assumptions.
Let $f$ and $g$ be integrable real-valued functions defined on $\mathbb{R}^n$ having unit integrals (with respect to Lebesgue measure): that is,
$$1=\int_{\mathbb{R}^n} f(x) dx = \int_{\mathbb{R}^n} g(x) dx.$$
(For convenience, let's drop the "$\mathbb{R}^n$" subscript, because all integrals will be evaluated over this entire space.)
The convolution $f\star g$ is the function defined by
$$(f\star g)(x) = \int f(x-y) g(y) dy.$$
(This is guaranteed to exist when $f$ and $g$ are both bounded or whenever $f$ and $g$ are both probability density functions.)
The mean of any integrable function is
$$E[f] = \int x f(x) dx.$$
It might be infinite or undefined.
Solution
The question asks to compute $E[f\star g]$ (in the special case where $f$ and $g$ are nonnegative--but this assumption doesn't matter). Apply the definitions of $E$ and $\star$ to obtain a double integral; switch the order of integration according to Fubini's Theorem (which requires assuming $E[f\star g]$ is finite), then substitute $x-y\to u$ and exploit linearity of integration (which is a basic property established immediately whenever any theory of integration is developed).  The result will appear because both $f$ and $g$ have unit integrals.

For those who want to see the details, here they are:
$$\eqalign{
E[f\star g] &= \int x (f\star g)(x) dx &\text{Definition of }E\\
&= \int x \left(\int f(x-y) g(y) dy\right) dx &\text{Definition of convolution}\\
&= \int g(y) \left(\int x f(x-y) dx\right) dy &\text{Fubini}\\
&= \int g(y) \left(\int (x-y)f(x-y) + yf(x-y) dx\right) dy&\text{Expand }x=(x-y)+y \\
&= \int g(y) \left(\int (x-y)f(x-y) dx + y\int f(x-y) dx\right) dy &\text{Linearity of integration}\\
&= \int g(y) \left(\int u f(u) du + y \int f(u) du\right) dy &\text{Substitution } x-y\to u\\
&= \int g(y) (E[f] + y(1)) dy &\text{Assumptions about }f\\
&= E[f]\int g(y) dy + \int y g(y) dy &\text{Linearity of integration}\\
&= E[f](1) + E[g] &\text{Assumptions about }g\\
&= E[f] + E[g].
}$$
These calculations are legitimate provided all three expectations $E[f\star g], E[f], E[g]$ are defined and finite.  Fubini's Theorem requires only the finiteness of $E[f\star g],$ but the steps at the end (involving linearity) also need the finiteness of the other two expectations.
Comment: If two of the means exist, the third exists.
Comment: Like your's better. Has the iff's.
Comment: Moreover, if $E[f\star g]$ is finite, then $[]$ and $[]$ are defined and finite.
Answer: Convolving distributions corresponds to adding independent random variables. Given PDFs $f_X$ and $f_Y$, let $f_Z = f_X * f_Y$ denote their convolution. $f_Z$ is the PDF of a random variable $Z = X + Y$, where $X \sim f_X$, $Y \sim f_Y$, and $X$ and $Y$ are independent. By linearity of expectation, $E[Z] = E[X+Y] = E[X] + E[Y]$.
Proof for linearity of expectation:
Let $f_{X,Y}$ be the joint distribution of $X$ and $Y$, with marginal distributions $f_X$ and $f_Y$. $X$ and $Y$ need not be independent.
The expected value of $X+Y$ is:
$$E[X+Y] =
\int_{-\infty}^\infty \int_{-\infty}^\infty
(x+y) \ f_{X,Y}(x, y) \ dx \ dy$$
Re-arranging terms gives:
$$E[X+Y] =
\int_{-\infty}^\infty x
\underbrace{\int_{-\infty}^\infty f_{X,Y}(x, y) \ dy}_{f_X} \ dx
+ \int_{-\infty}^\infty y
\underbrace{\int_{-\infty}^\infty f_{X,Y}(x, y) \ dx}_{f_Y} dy$$
As indicated under the terms above, integrating over the joint distribution gives the marginal distributions for $X$ and $Y$, so:
$$E[X+Y] =
\int_{-\infty}^\infty x \ f_X(x) \ dx
+ \int_{-\infty}^\infty y \ f_Y(y) \ dy$$
This corresponds to the sum of the expected values of $X$ and $Y$:
$$E[X+Y] = E[X] + E[Y]$$


How to build API that will return HTML for the site and JSON for other clients

Question: I have started learning DRF just a while ago and had a little question -
how can I code one API that will return HTML for the site that I am currently working on and return JSON format for other "clients"(e.g. mobile apps, desktop, etc)?
I have tried to search for this information, but didn't found any answering content.
The only way I see is to create default Django views for the site and create separated API's for other requests. Can anybody tell me if I am right and need to do so, or there is some code that is solving my problem?
Comment: please describe what you understand as "the site" and "other clients". What exactly is the difference you want to identify to switch between json and html
Answer: Ultimately, you can think of it as a whole separate set of views, urls and instead of models you have a serializer.  Within you're app you can create an API folder.  Within that directory you will need to have an '_ _ init _ _.py', 'urls.py', 'views.py' and a 'serializers.py'. Its analogous to creating a standard url, view, model structure to display an HTML page, but without the HTML template.  Make distinct urls for the serializers too. For example for login do something like this:
<code>path('my_app_api/login', serializer_view)
</code>
Youtube has tons of videos if you search django rest framework
Comment: Thank you! I really needed that answer afap!


Logit or arcsine transformation for proportion in meta-analysis

Question: I am performing a meta-analysis with 137 study arms. From each arm I have extracted a proportion of a disease. Here are my proportions:
[1] 0.002710027 0.000000000 0.000000000 0.000000000 0.017857143 0.000000000 0.010269576 0.000000000 0.000000000 0.000000000 0.000000000
 [12] 0.010000000 0.053691275 0.052631579 0.070351759 0.000000000 0.108333333 0.262626263 0.013043478 0.000000000 0.007000000 0.000000000
 [23] 0.000000000 0.000000000 0.240000000 0.000000000 0.033333333 0.000000000 0.000000000 0.000000000 0.000000000 0.013201320 0.000000000
 [34] 0.005361930 0.002308403 0.000000000 0.000000000 0.000000000 0.030000000 0.046296296 0.000000000 0.020000000 0.045454545 0.161073826
 [45] 0.000000000 0.000000000 0.000000000 0.095238095 0.007194245 0.001472754 0.000000000 0.000000000 0.000000000 0.000000000 0.012048193
 [56] 0.000000000 0.048780488 0.000000000 0.086253369 0.033898305 0.011966701 0.004162331 0.062790698 0.005555556 0.004451039 0.287356322
 [67] 0.083333333 0.000000000 0.000000000 0.014666667 0.006160164 0.023809524 0.000000000 0.000000000 0.000000000 0.001552795 0.102564103
 [78] 0.030555556 0.000000000 0.000000000 0.000000000 0.000000000 0.029411765 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000
 [89] 0.003231018 0.000000000 0.037500000 0.040247678 0.000000000 0.000000000 0.007299270 0.014598540 0.000000000 0.015118790 0.000000000
[100] 0.000000000 0.005555556 0.000000000 0.000000000 0.000000000 0.003039514 0.042145594 0.250000000 0.307692308 0.324444444 0.002057613
[111] 0.008333333 0.000000000 0.027522936 0.022598870 0.000000000 0.000000000 0.000000000 0.135278515 0.033333333 0.000000000 0.000000000
[122] 0.003690037 0.003412969 0.000000000 0.017391304 0.004237288 0.033210332 0.000000000 0.008928571 0.038834951 0.030303030 0.142857143
[133] 0.170000000 0.000000000 0.112903226 0.000000000 0.007299270

A majority of the proportions has zero value. I am struggling with whether I should go for logit or arcsine transformation. One source says that arcsine transformation should not be used (1). On the other hand, I several zero counts. With logit transformation values 0 and 1 are mapped to infinity, and according to another source I should go with arcsine transformation (2). Furthermore, I found another study close to my topic in which they used arcsine transformation. The default in R with metaprop function is logit.
Which one I should go with my data?
Answer: If all your proportions were in an intermediate range the choice would be quite arbitrary as they are very similar. In your case that is not true as you have many zero counts in the numerator. If you want to do meta-regression and see if your 137 study arms are affected by some covariate then there would be arguments for going with the logit as you cannot then end up with impossible predictions (as you say, it ranges over the whole real line). If you just want an overall summary then arcsine would be fine and would avoid having to make an arbitrary choice about adding a small constant. To add to your collection of refences you might be interested in this article by Rücker and colleagures with the title "Why add anything to nothing? The arcsine difference as a measure of treatment effect in meta--analysis with zero cells".


Proof Verification: Prove that $AB-BA=A$ is false, given $A$ is invertible

Question: Steps taken:

Multiply both sides by $A^{-1}$, given $A$ is invertible.

$A^{-1}AB - A^{-1}BA = A^{-1}A $
Thus,  $B - A^{-1}BA = I$

Take the trace of both sides.

$\operatorname{Tr}(B-A^{-1}BA) = \operatorname{Tr}(I)$

Utilize the linear mapping property of trace.

$\operatorname{Tr}(B)-\operatorname{tr}(A^{-1}BA) = \operatorname{Tr}(I)$

Utilize the cyclic property of trace.

$\operatorname{Tr}(B)-\operatorname{tr}(BAA^{-1}) = \operatorname{Tr}(I)$
$\operatorname{Tr}(B)-\operatorname{tr}(BI) = \operatorname{Tr}(I)$
$\operatorname{Tr}(B)-\operatorname{tr}(B) = \operatorname{Tr}(I)$

Reaching a contradiction

$0 = \operatorname{Tr}(I)$
Is my usage of the trace properties correct?
Comment: Looks right to me.
Comment: I think that your title is wrong. Replace 'true' with 'false'. For example, if $n=1$ then $AB-BA=0=A$ is false if $A$ is invertible.
Comment: Edited - Title changed. Thanks for the remark
Comment: The field characteristic needs to be mentioned for this to be a complete proof.  e.g. $\text{trace}\big(I_3\big) = 0$ when the field is $\mathbb F_3$
Answer: It is correct.
Here is a different, more high level proof. Consider the linear map $\delta : M_n \to M_n$ given by
$$\delta(X):= XB-BX.$$
Then we can show by induction that for all $k \in \Bbb{N}$ holds $\delta(A^k) = kA^k$. Indeed, for $k=1$ the claim is true by assumption. Assuming it holds for some $k$, we have
\begin{align}
\delta(A^{k+1}) &= A^{k+1}B-BA^{k+1} \\
&= A^k(AB-BA) + (A^kB - BA^k)A \\
&= A^k\delta(A) + \delta(A^k)A \\
&= (k+1)A^{k+1}
\end{align}
so it holds for $k+1$ as well.
If all $A^k$ were nonzero, we would get that $k$ is an eigenvalue of $\delta$ for all $k \in \Bbb{N}$. This is impossible since there are at most $n^2$ different eigenvalues of $\delta$ so it has to be $A^k =0$ for some $k \in \Bbb{N}$. This is a contradiction since $A$ is invertible.
Comment: Indeed more high level. Thank you


Weighted summation of irrational numbers

Question: Consider the set $\{\sqrt{p_1},\dots,\sqrt{p_n}\}$, where none of $p_i$'s are perfect squares, and ${\rm gcd}(p_i,p_j)=1$ for every $i \neq j$.  Prove that $0$ cannot be expressed as $\sum\limits_{k=1}^n q_k\sqrt{p_k}$, where $q_k\in \mathbb{Q}$ for every $k$, and $(q_1,\dots,q_k)\neq (0,0,\dots,0)$.
Comment: Good catch. Fixed, thanks Thomas.
Comment: Show that $[\mathbb{Q}(\sqrt{p_1},\ldots,\sqrt{p_n}):\mathbb{Q}]= 2^n$ so $\mathbb{Q}(\sqrt{p_1},\ldots,\sqrt{p_n})$ is a $2^n$ dimensional $\mathbb{Q}$-vector space. Do you see a basis ?
Comment: In [this answer](https://math.stackexchange.com/a/113701/11619) I think Bill Dubuque managed to stirp the argument to bare essentials. The inductive step there does take some care. My answer below makes the induction step easier, but at the cost of assuming basic Galois theory.
Comment: Ah, reuns. So, the thing is I did a brief google search, hence I know that the tools I need are related to Galois fields, but I know close to $0$ abstract algebra, not to even mention Galois theory. Any theorems that you recommend me reading, so that I can tackle this problem?
Comment: Or, whether there is an elementary way of solving this?
Comment: If $x^2-m$ is irreducible in $K[x]$ then $\{ a+b \sqrt{m}, (a,b) \in K\}$ is a field (denoted $K(\sqrt{m})$) and a $2$-dimensional vector space (with basis $1,\sqrt{m}$). Here you need to look at $K_0 = \mathbb{Q}, K_{j+1} = K_j(\sqrt{p_{j+1}})$, to obtain that each $K_j$ is a $2^j$-dimensional $ \mathbb{Q}$ vector space. The basis will appear naturally, as well as your result.
Answer: Oops, I have a semi-rigorous idea. Can someone help me with checking and rigorizing it?
I will prove the result when $p_i$'s are all prime.
Lemma: There exists a large prime $p$ such that, in modulo $p$, $p_1,\dots,p_{n-1}$ are all quadratic residues, while $p_n$ is not.
Proof. Here is the construction. Let $P$ be a large prime. The strategy is to use the law of quadratic reciprocity. Select $p\equiv 1\pmod{4}$, and $p\equiv 1\pmod{p_i}$, for every $i$. Now, the law of quadratic reciprocity implies,
$$
\left(\frac{P}{p_i}\right)\left(\frac{p_i}{P}\right)=\left(\frac{p_i}{P}\right)=(-1)^{\frac{p_i-1}{2}\cdot \frac{P-1}{2}}=1,
$$
hence, $p_i$ is indeed a quadratic residue, in modulo $P$, for every $i =1,2,\dots,n-1$. Now, let $\alpha_i\in\{0,1,\dots,p_n-1\}$ be a number, such that $\alpha_n$ is a quadratic non-residue, in modulo $p_n$. With this, we select $P\equiv \alpha_n\pmod{p_n}$. One can immediately see, using the law of quadratic reciprocity that, $p_n$ is a quadratic non-residue, in modulo $P$. Finally, the existence of such a prime $P$ obeying the congruences $P\equiv 1\pmod{4}$, $P\equiv 1\pmod{p_i}$ for $i =1,2,\dots,n-1$, and $P\equiv \alpha_n\pmod{p_n}$, follows immediately from the Chinese Remainder Theorem and Dirichlet's theorem on primes.
Now, in this prime $P$ modulus, if $\sum_{i=1}^n q_i\sqrt{p_i}=0$, then by multiplying with a large $M$ everywhere we get $\sum_{i =1}^{n-1} M_i\sqrt{p_i} \equiv -q_i\sqrt{p_n}\pmod{P}$, from here, we deduce that $p_n$ is a quadratic-residue, a contradiction.
Comment: From quadratic reciprocity and Dirichlet theorem on arithmetic progression, for any $a_1,\ldots,a_n$ coprime and any $b_i = \pm 1$ you can find a prime $p$ such that $(a_i/p) = b_i$. But how does it help here since you don't know anything on the $q_i$ ?
Comment: Very naively, on one side you get $\sum_{i=1}^{n-1}q_i\sqrt{p_i}$, where since $p_i$ is a quadratic residue, $\sqrt{p_i}$ exists modulo $P$, from here, you'd deduce that $q_n\sqrt{p_n}=c$ for some $c$ in modulo $P$. Hence, $\sqrt{p_n}$ must also exist in modulo $P$, but $p_n$ is not a quadratic residue. Note $q_i$'s are all rational, hence by taking P large enough (in fact, assuming the existence of a non-trivial combo, looking at all the denominators of involved $q_i$'s and taking $P$ sufficiently large), we can carry out modulo $p$ computation, no?
Comment: The only thing is that, how to make this rigorous?
Comment: Ah ok then yes (That's the same as showing that $x^2-p_n$ is irreducible over $\mathbb{Q}(\sqrt{p_1},\ldots,\sqrt{p_{n-1}})$). You can look at the ring $R = \mathbb{Z}/P \mathbb{Z}[\sqrt{p_1},\ldots,\sqrt{p_{n-1}}]$ where the $\sqrt{p_j}$ are symbols whose square is $p_j$. That ring may be not an integral domain, but there is a prime ideal such that $R/I$ is an integral domain, thus a finite field, containing the square root of each $p_j$. If $\mathbb{Z}/P \mathbb{Z}$ already contained a square root of each $p_j$ then $R/I \cong \mathbb{Z}/P \mathbb{Z}$ so you can lift $\sum_i M_i \sqrt{p_i}$
Comment: see [here](https://math.stackexchange.com/a/437374/305862)


Numbers of ways to choose $k$ out of the first $n$ natural numbers so the longest string of consecutive numbers is exactly $m$?

Question: How many ways can $k$ numbers be chosen from the first $n$ natural numbers so that the longest string of consecutive numbers is exactly $m$ numbers long
For example, if choosing $k = 7$ distinct numbers from the first $n = 14$ natural numbers ($1-14$), how many combinations of numbers are there that have exactly $m = 3$ consecutive numbers?
Some sets that satisfy this would be $[1,2,3,5,7,10,13]$, $[1,2,3,7,8,10,11]$, or $[1,2,3,6,9,10,11]$.
Obviously $m \le k \le n$, and the order of the numbers picked does not matter, but there is no repetition, so $[1,2,3]$ is the same as $[2,1,3]$, but $[1,1,3]$ is not allowed.
For cases when $m \gt \frac k2$ I believe the equation
$$2* \binom {n-m-1}{k-m} + (n-m-1)*\binom{n-m-2}{k-m}$$
will produce the correct answer, but for values of $m \le \frac k2$ I do not know how to account for multiple strings of consecutive digits in the same set (eg. $[\textbf{1,2,3},6,\textbf{8,9,10}]$) not being counted twice.

If anyone could give me help with this example that I could extrapolate from or (ideally) a formula or any references to solve for a general case it would be much appreciated.
Comment: Thanks for explaining this; I think we misinterpreted the question because of the way the title is worded.
Comment: Good, that sounds better. With standard terminology you are speaking of *k-subsets from set $\{1,2,\cdots , n\}$ which contains ...*. It's a very interesting problem I am trying to work out.
Comment: I posted an answer, but then looked back at your question and realized that I didn't understand it completely.  When you say the selection has exactly $m$ consecutive numbers, do you mean there is exactly one string of $m$ consecutive numbers but that there may also be other consecutive strings that are shorter?
Comment: Yes. The way I meant it was that there may be other strings that are shorter, so for example if $n=10$, $k=7$, and $m=3$ you could have $[1,2,3, 5,6,7,9]$ which would have multiple strings of length $m$ or $[1,3,4,5,7,8,10]$ which would have one string of length $m$ but also other shorter strings of consecutive numbers. However, you could not have $[1,2,4,5,6,7,9]$ because that has a string of length greater than $m$.
Comment: Sorry, I realize that what I wrote could have been interpreted differently than what I meant. Instead of exactly one string of length $m$, I meant that there could be multiple strings, but none longer than length $m$.
Comment: ok, but then amend your post, not to compel to go through the comments !
Comment: @GCab I deleted my original post when I realized this, and posted a different answer instead.
Comment: and I could work it out: hope my answer is satisfactory to you
Answer: Let $l=n-k$, and line up $l$ sticks (representing the numbers not chosen).
If we let $x_i$ represent the number of integers in gap $i$, the number of choices with no string longer than $m$ is given by the number of solutions of $x_1+\cdots+x_{l+1}=k\;$ with $0\le x_i\le m$ for each $i$,
so there are $\displaystyle s_1=\binom{n}{l}-\binom{l+1}{1}\binom{n-(m+1)}{l}+\binom{l+1}{2}\binom{n-2(m+1)}{l}-\cdots$ such choices.
To count the number of choices with at least one string of length $m$, we can subtract the number of choices with no string longer than $m-1$, which is given by the number of solutions of
$\hspace{.2 in}x_1+\cdots+x_{l+1}=k\;$ with $0\le x_i\le m-1$ for each $i$,
so there are $\displaystyle s_2=\binom{n}{l}-\binom{l+1}{1}\binom{n-m}{l}+\binom{l+1}{2}\binom{n-2m}{l}-\cdots$ such choices.
Then there are $\displaystyle s_1-s_2=\sum_{j=1}^{\lfloor\frac{k}{m}\rfloor}(-1)^{j+1}\binom{l+1}{j}\left[\binom{n-jm}{l}-\binom{n-j(m+1)}{l}\right]$ possibilities.

(I am using the nonstandard convention that $\dbinom{r}{l}=0$ if $r<l$.)
Comment: @corndog I think these answers might help:  https://math.stackexchange.com/questions/1429561  https://math.stackexchange.com/questions/904734                                            (I may not have the stopping point for the summation right, but I think it's correct.)
Comment: If $n=5,k=3,m=2$ the possible subsets are $[1,2,4], [1,2,5], [2,3,5], [1,3,4], [1,3,5], [2,3,5]$. However your formula gives $\sum_{j=1}^{\lceil\frac{6-5}{2}\rceil}(-1)^{j+1}\binom{2+1}{j}\left[\binom{3-2j}{2}-\binom{3-3j}{2}\right] = \binom{3}{1}\left[\binom{1}{2}-\binom{0}{2}\right]$ which is also wrong.
Comment: Okay it seems your solution now works and some of bits I said were wrong were actually right, it took me a while to work out what some of the terms were doing (sorry about that). Your solution is now very nice, I wish I'd thought of some of it.
Comment: I saw your amended formula after I posted mine. The results coincides (apart that your formula gives 0 for the case n=k) (+1)
Comment: This still isn't working for me. I'll be honest, I don't quite understand how you got the equations for $s_1$ and $s_2$. But also, the stopping point for the summation ($\lceil\frac{2k-n}{m}\rceil$) doesn't really seem to work because if $k \lt \frac m2$ it goes to zero and the summation returns 0 een if we know this is wrong.
Comment: Thanks so much for those links, I admittedly know very little about combinatorics, so just reading all of this is slowly starting to make it all come together for me
Comment: This is wrong in a few ways. Firstly in the $s_1$ and $s_2$ expressions I see you're using inclusion exclusion to count the number but $\binom{k-(m+1)}{l}$ is not how many ways you have to distribute the remaining $k-(m+1)$ integers in the gaps and even if it was it counts some possibilities twice (For example if k=6 and m=2, you could choose your gap of 3 to be in gap 1 and then distribute the remaining 3 all in gap 2 or you could choose your gap of 3 to be in gap 2 and then distribute the remaining 3 all in gap 1 and these are counted differently).
Comment: Then when you come to work out an expression for $s_1 - s_2$ the limit of your summation is wrong due to the fact $\binom{k-jm}{l}$ is wrong (if $2k\le n$ you have to sum between 1 and 0). Also it is possible for $s_1$ and $s_2$ to have a different number of terms and so putting them in the same summation is impossible.
Comment: @PJF49 I don't understand your comments, but if you give a specific example where this gives the wrong answer, that would be helpful.
Comment: Okay examples, if n=2, k=1 and m=1 the possible s
Comment: If $n=2, k=1, m=1$ the possible subsets are $[1]$ and $[2]$ whereas your formula gives $\sum_{j=1}^{0}(-1)^{j+1}\binom{l+1}{j}\left[\binom{k-jm}{l}-\binom{k-j(m+1)}{l}\right]$ which isn't defined as the upper limit is less than the lower limit. Even worse if $n=3, k=1, m=1$ there are three possible subsets but in your formula the upper limit is $-1$. Even if the upper limit is positive it still doesn't work. For example if $n=3, k=2, m=2$ the possible subsets are $[1,2]$ and $[2,3]$ whereas your formula gives $\binom{2}{1}\left[\binom{0}{1}-\binom{-1}{1}\right]$ which is obviously wrong.
Comment: @PJF49 Thank you for these examples -- this helped me find a typo in my formula, and a mistake in the upper limit.
Comment: @user84413 in the final function, should the two expressions in the brackets $\binom{n-jm}{l}$ and $\binom{n-j(m+1)}{l}$ be switched? What you have appears to be $s_2-s_1$
Comment: also could you explain how you got the stopping point of $\lfloor{\frac km}\rfloor$
Comment: @corndog I believe the expression given equals $s_1-s_2$, because of the alternating signs in both sums.  I found the upper limit for the sum by solving $n-jm<l$, where $l=n-k$.
Comment: Yeah you're right, I had just flipped the powers for $(-1)$, (I had $(-1)^j$ not $(-1)^{j+1}$ so everything was coming out negative.
Answer: Another more practical solution uses a recurrence relation. Let the size of the gaps between the $n-k$ numbers not chosen be $x_1,x_2,...,x_{n-k+1}$. Then the problem reduces to how many ways are there such that $\forall i$, $x_i\in [0,1...m]$, $\sum_{i=1}^{n-k+1}x_i = k$ and at least one of $x_i = m$.
To solve this first consider the solutions of another similar problem, $\forall i$, $x_i\in [0,1...m]$, $\sum_{i=1}^{y}x_i = k$ where the constraint at least one of $x_i = m$ doesn't exist and $n-k+1$ has been replaced by $y$. Let the number of solutions of this problem be the function $S(y,k,m)$. Next consider removing the last $x_i$ in a solution of $y,k,m$. Then the remaining $x_i$ will give us a solution of $y-1,k-a,m$ for some $a\in [0,1...m]$. Therefore $S(y,k,m) = \sum_{a=0}^{m}S(y-1,k-a,m)$. $S(1,k,m) = 1$ iff $k\in [0,1...m]$ which allows us to tabulate all other values.
For example in the $m=2$ case:
$$\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|}
\hline \text{y\k} & \text{0} & \text{1} & \text{2} & \text{3} & \text{4} & \text{5} & \text{6} & \text{7} & \text{8} & \text{9} & \text{10} \\
\hline \text{1} & \text{1} & \text{1} & \text{1} & \text{0} & \text{0} & \text{0} & \text{0} & \text{0} & \text{0} & \text{0} & \text{0} \\
\hline \text{2} & \text{1} & \text{2} & \text{3} & \text{2} & \text{1} & \text{0} & \text{0} & \text{0} & \text{0} & \text{0} & \text{0} \\
\hline \text{3} & \text{1} & \text{3} & \text{6} & \text{7} & \text{6} & \text{3} & \text{1} & \text{0} & \text{0} & \text{0} & \text{0} \\
\hline \text{4} & \text{1} & \text{4} & \text{10} & \text{16} & \text{19} & \text{16} & \text{10} & \text{4} & \text{1} & \text{0} & \text{0} \\
\hline \text{5} & \text{1} & \text{5} & \text{15} & \text{30} & \text{45} & \text{51} & \text{45} & \text{30} & \text{15} & \text{5} & \text{1} \\
\hline \end{array}$$
Then let $P(y,k,m)$ be the number of solutions of the problem with the constraint at least one of $x_i = m$ included. $P(y,k,m) = S(y,k,m) - S(y,k,m-1)$.
For example $P(3,3,2) = S(3,3,2) - S(3,3,1) = 7-1 = 6$ (with $S(3,3,1)$ quickly worked out by hand).
Therefore the number of solutions of the original problem with $n=5, k=3, m=2$ is $P(5-3+1,3,2) = P(3,3,1) = 6$ and as the possible solutions of this problem are $[1,2,4], [1,2,5], [2,3,5], [1,3,4], [1,3,5], [2,3,5]$ this is indeed correct.
Although this is a bit time consuming by hand it should be possible to get a computer to use the recurrence relation to generate the solutions.
Comment: I quite like this idea, as it is a lot more practical and straightforward. It's a shame though that it involves so much backtracking to produce a lot of solutions.
Answer: So we can arrange the $k$ choosen numbers in order, and therefore we are speaking of k-subsets from the set $\{1,\cdots , n\}$.
Let's
 - put a $0$ in front of the subset (sequence);
 - take the backward differences;
 - neglecting the first ($=a_1$), consider the differences from the 2nd to $k$-term.
$$ \bbox[lightyellow] {
\eqalign{
  & 0,a_{\,1} ,a_{\,2} , \cdots ,a_{\,k} \quad \left| {\;1 \le j \le a_{\,j}  \le n} \right.\quad  \Rightarrow   \cr
  & \;a_{\,1} ,a_{\,2}  - a_{\,1} , \cdots ,a_{\,k}  - a_{\,k - 1}  = a_{\,1} ,d_{\,2} , \cdots ,d_{\,k} \quad  \Rightarrow   \cr
  &  \Rightarrow \quad d_{\,2} ,d_{\,3} , \cdots ,d_{\,k} \quad \left| \matrix{
  \;2 \le j \hfill \cr
  \;1 \le d_{\,j}  = a_{\,j}  - a_{\,j - 1}  \le n - 1 \hfill \cr
  \;1 \le \sum\limits_{2\, \le \,j\, \le \,k} {d_{\,j} }  = q = a_{\,k}  - a_{\,1}  \le n - 1 \hfill \cr}  \right. \cr}
 } \tag{1}$$
Then we are looking for the
number of (standard) compositions of $0 \le q \le n-1$ into $1 \le k-1 \le n-1$ parts , each positive (and no greater than $n-1$) , that contain runs of contiguous ones no longer than $0 \le m-1$.
We will take for the moment the cumulative version "runs no longer than", and will later manage to get the version "runs with max length equal to".
For $k=1$, the above scheme does not apply, but for subsets with one element ,clearly, the number of contiguous elements is $1$,
and there are $n$ possible subsets.
For $2 \le k$, the same value of $q=a_{k}-a_{1}$ can be attained in $n-q$ ways, and the result shall be summed over $1 \le q \le n-1$.
It is known that the number of compositions of $q$ into $k$ parts is
$$ \bbox[lightyellow] {
N_{\,s\,c} (q,k) = \left[ {1 \le q} \right]\left( \matrix{
  q - 1 \cr
  k - 1 \cr}  \right)
 } \tag{2.a}$$
where $[P]$ denotes the Iverson bracket.
We can part this quantity according to the number of ones that it contains, denoted by $0\le s \le k$, as
$$ \bbox[lightyellow] {
\eqalign{
  & N_{\,s\,cs} (q,k,s) = \left[ {k = q} \right]\left[ {k = s} \right] + \left[ {k + 1 \le q} \right]\left( \matrix{
  q - k - 1 \cr
  k - s - 1 \cr}  \right)\left( \matrix{
  k \cr
  s \cr}  \right) =   \cr
  &  = \left( {\left[ {k = q} \right]\left[ {k = s} \right] + \left[ {k + 1 \le q} \right]\left( \matrix{
  q - k - 1 \cr
  k - s - 1 \cr}  \right)} \right)\left( \matrix{
  k \cr
  s \cr}  \right) \cr}
 } \tag{2.b}$$
where the second term (${{k} \choose {s}}$) corresponds to the number of binary string $(1,\cdots,X,\cdots)$
obtained by replacing with $X$ the parts greater than one, and the first factor to the number of ways to compose the $X$s.
Coming to the binary string, clearly we can change the $X$ with a $0$, then
the number of binary strings of a given length , number of ones, and max length of runs of ones
is extensively treated in this other post.
From there we have that  the
Number of binary strings, with $s$ ones , $m$ zeros and runs of ones which are not longer than $r$
 is given by
$$ \bbox[lightyellow] {
N_b (s,r,m + 1)\quad \left| {\;0 \le {\rm integers  }\,s,m,r} \right.\quad  = \sum\limits_{\left( {0\, \le } \right)\,\,j\,\,\left( { \le \,{s \over r}\, \le \,m + 1} \right)} {\left( { - 1} \right)^j \left( \matrix{
  m + 1 \cr
  j \cr}  \right)\left( \matrix{
  s + m - j\left( {r + 1} \right) \cr
  s - j\left( {r + 1} \right) \cr}  \right)}
 }\tag {3.a}$$
Translating that into into our case, the number of
binary strings with  length $k$ and $s$ ones and runs of ones no longer than $m$ is
$$ \bbox[lightyellow] {
\eqalign{
  & N_b (s,m,k + 1 - s)\quad \left| {\;0 \le {\rm integers  }\, s,m,k  - s} \right.\quad  =   \cr
  &  = \left[ {\;0 \le s} \right]\left[ {\;0 \le m} \right]\left[ {\;s  \le k} \right]\sum\limits_{\left( {0\, \le } \right)\,\,j\,\,\left( { \le \,\,k - s + 1} \right)} {\left( { - 1} \right)^j \left( \matrix{
  k + 1 - s \cr
  j \cr}  \right)\left( \matrix{
  k - j\left( {m + 1} \right) \cr
  s - j\left( {m + 1} \right) \cr}  \right)}  \cr}
 } \tag{3.b}$$
Going back through the steps above, the
Number of composition of $q$, with length $k$ , number of ones $s$ and runs of ones no longer than $m$
will be the above multiplied by the first factor in (2.b)
$$ \bbox[lightyellow] {
\eqalign{
  & N_{\,c\,q\,s}  = (q,k,s,m)\quad \left| {\;{\rm integers  }q,s,m,k} \right.\quad  =   \cr
  &  = \left( {\left[ {k = q} \right]\left[ {k = s} \right] + \left[ {k + 1 \le q} \right]\left( \matrix{
  q - k - 1 \cr
  k - s - 1 \cr}  \right)} \right)N_b (s,m,k - s + 1) =   \cr
  &  = \left( {\left[ {k = q} \right]\left[ {k = s} \right] + \left[ {k + 1 \le q} \right]\left( \matrix{
  q - k - 1 \cr
  k - s - 1 \cr}  \right)} \right)\; \cdot   \cr
  &  \cdot \sum\limits_{\left( {0\, \le } \right)\,\,j\,\,\left( { \le \,\,k - s + 1} \right)} {\left( { - 1} \right)^j \left( \matrix{
  k + 1 - s \cr
  j \cr}  \right)\left( \matrix{
  k - j\left( {m + 1} \right) \cr
  s - j\left( {m + 1} \right) \cr}  \right)}  \cr}
 } \tag{4}$$
Therefore, the
number of k-subsets from the set $\{1,\cdots , n\}$ having no more than $m$ contiguous characters
is
$$ \bbox[lightyellow] {
\eqalign{
  & N_{c\,u\,m} (n,k,m) = \left[ {1 = k} \right]\left[ {1 \le m} \right]n +   \cr
  &  + \left[ {2 \le k} \right]\sum\limits_{0\, \le \,q\, \le \,n - 1} {\sum\limits_{0\, \le \,s\, \le \,k} {\left( {n - q} \right)N_{\,c\,q\,s} (q,k - 1,s,m - 1)} }  \cr}
 } \tag{5.a}$$
Finally, the number of k-subsets with one or more run of contiguous elements
of length $m$, and none longer will clearly be
$$ \bbox[lightyellow] {
N_{c\,u\,m} (n,k,m)-N_{c\,u\,m} (n,k,m-1)
 } \tag{5.b}$$


Use a block in a panel

Question: Like the title says, is there a way I can use a block inside my panel? It looks like it can't be done...
As you can see here, there is no option to add a block to my panel...
Comment: @Letharion, I'm terrible sorry, but my colleague changed the language (very stupid) and I can't change it back!
Comment: Please keep screenshots to English. My answer "Miscellaneous" is "Diverse" in that screenshot, but it becomes needlessly hard to both answer your question and derive value from it later when it's not in english.
Answer: Most of the blocks are under the "Miscellaneous" category.
I'm not sure exactly what the distinction is, but a few of them, such as user login, end up under "Widgets" instead.
Comment: @DigitalFire As far as I can tell, `ctools/plugins/content_types/block/block.inc` implements panes for _all_ blocks, with explicit exceptions for book and profile, which is what Camil refered to above. That search block would also end up under 'Widgets'.
Comment: Do you know the criterion by which blocks are displayed in Miscellaneous/Widgets or not? I can't seem to find the "Book navigation" block anywhere in order to put it in a panel. Although this probably is a full question in itself...
Comment: @CamilBăncioiu All "normal" blocks go there. Though I think there's actually an odd exception for some book related blocks. Check the Panels issue queue, I know there's a relevant issue somewhere. But yeah, separate question. :)
Comment: @Letharion I explored the code and found the cause in CTools, it explicitly refrains from exposing the Book Navigation block (the reason was in a comment, but I didn't understand it). Okay, no more off-topic-ness. Still, people should take note of some exceptions when it comes to blocks in Panels, so I'm leaving this here.
Comment: regarding the login block, when I enable it for one of my panels, it won't show up. All other widgets display fine. Any ideas?
Comment: You're logged in?
Comment: @CamilB: You mention of seeing something in Ctools. Can you elaborate WHERE in ctools that is please? Letharion: Do you know if the default search module enables a block here? I can't find it in my setup so i'm wondering if anyone else see's this issue.
Comment: @DigitalFire, ctools implements its own "Advanced search form", and it's categorized under "Widgets". You can see it in `ctools/plugins/content_types/search/search_form.inc`
Comment: @Letharion Yes I'm aware of that one. But it has a problem that the "results page" widget that is required to view the results of "search form" widget doesn't seem to format html correctly. Was hoping maybe I can find a way to enable the default search block somehow.
Answer: If your block from a view you can use Views but If you want to add a block there is an option called widgets to add your block like poll
Comment: I can't add a poll by using widgets...
Answer: I have same problem that I can't see block view on Miscellaneous.
My solution is go to Module menu. Find the module "Views content panes" and uninstall it. So, the block view will display on Miscellaneous of panel.
Regards,
Bien

Use a block in a panel


an unhandled exception is occured in myproject.vshost.exe

Question: I am creating a windows application using 3rd party dll. They had given some predefined methods to use. There is a method SetTag() which is use to update a value. Now my work is to get data from tcp client and send to this method. My tcp part is working well, I had tested it. The problem is occurring at the time when I call SetTag(). It works well for a while but after some time, it's showing just-in-time debugger pop-up with exception

An unhandled exception has occurred in myproject.vshost.exe

I don't understand from where this exception is occurring.
Whenever I get data from tcp client, my UpdateValues() is called, which calls the third-party SetTag()
// valuesInArray is an object array which contain
// the data from tcp client after converted to object
UpdateValues(valuesInArray);

and the method:
public void UpdateValues(object[] values)
{
    this.BeginUpdate();
    for (int i = 0; i < 9; i++)
    {
        this.SetTag(TagHandle[i], (values[i]), Quality.Good, FileTime.UtcNow);
    }
    this.EndUpdate(false);
}

I had created a simulator, where the data is not coming from tcp client, itis sending data in a timer tick event. In that case no error is occurring and the program runs smoothly. Can you suggest why this error is occurring using tcp client and how I get rid of it?
Comment: Subscribe to AppDomain.Current.DomainUnhandledException to understand what happends.
Comment: How about surrounding SetTag(...) with a try catch and investigating stacktrace and inner exception of the "unhandled" exception when it occurs? [Debug tutorial](http://msdn.microsoft.com/en-us/library/vstudio/sc65sadd.aspx)
Comment: What is the declaration of SetTag in your c# code? Are the parameters correct as expected?
Comment: try catch is not catching any error. how to see stacktrace?
Comment: @stamhaney: yes sir,this method is provided by the vendor.
Comment: Why dont you enable all exceptions in VS and see where are you getting the exception?
Answer: In .NET 4 and later, you need to mark the containing method (UpdateValues) with HandleProcessCorruptedStateExceptionsAttribute and SecurityCriticalAttribute to catch some special exceptions such as AccessViolationException
Answer: You haven't provided enough details to explain what the error is. However, your code will benefit from using a try {} catch {} to 'handle' the exception. The exception has the details you are looking for.
public void UpdateValues(
object[] values)
{
    this.BeginUpdate();
    for (int i = 0; i < 9; i++)
    {
        try
        {
            this.SetTag(TagHandle[i], (values[i]), Quality.Good, FileTime.UtcNow);
        }
        catch (Exception e)
        {
            // Log or print out the details
            Console.WriteLine("Error occurred setting the value.");
            Console.WriteLine(e);
        }
    }
    this.EndUpdate(false);
}

In this example, the exception message and stack trace are printed to the console. Look in this output for the cause of your exception.


Active Directory without global catalog

Question: Are there any Active Directory configurations supported, where forest contains no Global Catalog?
EDIT: Since it was a prevalent comment to the question, I will answer it here: I am working on a product and QA requested that it must work in environment with no GC is present at all. Hence the question: are there conceivably any environments which don't have one.
Comment: Why should you want such a thing?
Comment: Unless you've somehow created such a config, you are on to support, you are being told that they won't touch you with a 10 foot pole, and you want to prove them wrong...
Comment: What is the QA scenario? Do they have a customer using ADAM? Or is your app running at a remote site that could be cut off from the GC?
Answer: Active Directory Directory Services: No. You need at least one GC
Active Directory Application Mode: Yes (to my knowledge, you don't need a GC)
As Massimo asks; Why would you want such a thing?
Answer: You need at least on GC, your first domain controller is setup by default as a Global Catalog server.
As many have said, I can't understand why you want to do this. If you have multiple domains in your forest, you really need a GC per domain for them to communicate effectively and if you only have 1 domain in your forest, then your GC really doesn't add much overhead.
Answer: This is a bizarre request.  According to the TechNet article on GCs, in a single-Domain environment the only absolute requirement for a GC seems (and I do say "seems") to be for GAL lookups in Exchange, but all the same I'm failing to understand why creating a GC could be something you would want to avoid.
Answer: The GC is the system against which you actually authenticate.  If you have no GCs you can't authenticate.  Hit TechNet and you will see this pervasively throughout the documentation.
Comment: afaik, GC does not authenticale, DC does
Answer: I wonder if they meant an AD site where there are no GC's, which would be not a good thing but possible.
Answer: In a single domain environment without Exchange you don't need a GC, even with multiple sites. GC has got nothing to do with locating domain controllers in this scenario.
Comment: Yes, in a single domain with no apps (such as Exchange) that require GC.
Comment: are you saying it is possible to set up functional environment where GC will not be running?

Active Directory without global catalog


jQuery Wait for select to populate from database

Question: I have ddl(drop down list) which populates from database after change event of another ddl but I want to change the value of this ddl after it populated from database.
Example:
<code>// This work very well
$("#ddlGroups").on('change',function(){
    // Load data from database and populate ddlUsers
    // response is loaded from database with $.ajax
    // Query Example: SELECT User_ID, Username FROM tblUsers WHERE Group_ID = [Group_ID] (Just for undrestanding the question)

    var Records = response.d;
    $("#ddlUsers").empty();
    $.each(Records, function(){
    var _Key = this.User_ID;
        _Value = this.Username;
        $("#ddlUsers").append($("<option />").val(_Key).text(_Value));
    });
});

// When button clicked then trigger ddlGroups change event and assign select option from ddlUsers
var _UserID = User_ID_From_Database; // Loaded from Database when button clicked
$("#ddlGroups").trigger('change'); // Users are loaded from database based on group ID
$("#ddlUsers").val(_UserID); // But this dosn't change
</code>
How do I check if ddlUsers is loaded or not, I tried while loop but it never stops.
Comment: I presume you mean [`trigger`](http://api.jquery.com/trigger) rather than [`tigger`](http://en.wikipedia.org/wiki/Tigger).
Comment: Can you be more clear? Maybe show us more code?
Comment: Changed all question.
Comment: That is not the problem it works fine.
Comment: You can check the length of the options: `$("#ddlUsers option").length`
Comment: @tymeJV, but it takes time to load from database it passes the line `$("#ddlUsers").val(_UserID);`
Comment: I dont see an AJAX call? You have to post that as well, I see the comments for it.
Answer: With jquery there are two main ways (really the same underlying) to connect a ajax response from the database to a event or UI result.  The first is promises and the second is a callback.  Both these have 1 million examples and jquery documentation is quite robust.
In your case rather than "trigger", you callback calls the right function.  The below is just junk code to show.
<code>No:  $("#ddlGroups").tigger('change');

Yes:
//Your code
$("#ddlGroups").on('change', updateDDL);

//I have just externalized this function to a scope/place where both the ajax and on change line of code can reference it.
function updateDDL(){

    var Records = response.d;
    $("#ddlUsers").empty();
    $.each(Records, function(){
    var _Key = this.User_ID;
        _Value = this.Username;
        $("#ddlUsers").append($("<option />").val(_Key).text(_Value));
    }
};

$.ajax(...., function (data) {
// Update ddl, the existing function you have.
// You should already have something like this.
updateDDL();  //Like this
});
</code>
BTW: You could pass the data into the updateDDL directly use $(this) in the updateDDL to improve it etc but that is not key to your question/issue.  It seems that you are new to jquery and some of the Javascript features it uses.  Take a little time to learn about them and you will be WELL rewarded.  I would start by reading examples around ajax/jquery and watch how then update the DOM.


Is there any way to bulk many upserts to mysql db?

Question: The current process is doing an upsert like the code below.
However, the high number of requests seems to cause problems.
Is there a way to do it with fewer requests?
1.
INSERT INTO example_table (id, prop_a, prop_b) VALUES (1,1,7)
ON DUPLICATE KEY UPDATE prop_a=1,prop_b=7;

-------------------------------------------------------------
id(primary key), prop_a, prop_b, prop_c
1                1       7       0
-------------------------------------------------------------

INSERT INTO example_table (id, prop_b, prop_c) VALUES (1,5,8)
ON DUPLICATE KEY UPDATE prop_b=5,prop_c=8;
-------------------------------------------------------------
id(primary key), prop_a, prop_b, prop_c
1                1       5       8
-------------------------------------------------------------

INSERT INTO example_table (id, prop_a, prop_b) VALUES (7,3,3)
ON DUPLICATE KEY UPDATE prop_a=3,prop_b=3;
-------------------------------------------------------------
id(primary key), prop_a, prop_b, prop_c
1                1       5       8
7                3       3       0
-------------------------------------------------------------

Answer: INSERT INTO example_table (id, prop_a, prop_b, prop_c)
SELECT 1,1,7,0 UNION ALL
SELECT 1,5,0,8 UNION ALL
SELECT 7,3,3,0
ON DUPLICATE KEY UPDATE
prop_a=CASE WHEN VALUES(prop_a) = 0
            THEN COALESCE(prop_a, 0)
            ELSE VALUES(prop_a) END,
prop_b=CASE WHEN VALUES(prop_b) = 0
            THEN COALESCE(prop_b, 0)
            ELSE VALUES(prop_b) END,
prop_c=CASE WHEN VALUES(prop_c) = 0
            THEN COALESCE(prop_c, 0)
            ELSE VALUES(prop_c) END;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=64a0ef6520c65de8ac7e97ea90dc40d5


By considering a right-angled triangle, Prove that if $A$ is an acute angle, then $\tan(90-A)=\frac1{\tan A }$.

Question: By considering a right-angled triangle, Prove that if $A$ is an acute angle, then $\tan(90-A)=\dfrac1{\tan A}$.
I'm not too sure with this question, would it be a good starting point by  using the identity $\tan x=\dfrac{\sin x}{\cos x}$ ?
Comment: Have you draw a triangle?
Comment: $A+B=90^{0}$ consider $ \cot(A+B)$
Answer: $\tan(90-A) = \sin(90°-A)/\cos(90°-A) = \cos(A) / \sin(A) = 1/\tan(A)$
Answer: If the legs are
$a$ and $b$
opposite corresponding angles
$A$ and $B$ then
$\tan(A) = a/b$
and
$\tan(B) = b/a$.
But $A+B = 90$
so
$\tan(B)
=\tan(90-A)
=b/a
=1/(a/b)
=1/\tan(A)
$.