Mongoose-mongoDB advanced query joins

Question: I have two models in my database, the Room model and Block model
The room schema
var RoomSchema = new Schema({
  name: String,
  floor: { type: Number, min: 0},
  capacity: { type: Number, min: 0},
  free: { type: Number, min: 0},
  block: {type: mongoose.Schema.Types.ObjectId, ref: 'Block'}
});

the block schema
var BlockSchema = new Schema({
  name: String,
  type: Boolean, // 0->man, 1->woman
  rooms: [{type: mongoose.Schema.Types.ObjectId, ref: 'Room'}]
});

I would like to retrieve all rooms that belong to a block where the type is false (rooms for men),
so if I was to write this in pseduo sql it would be like
select * from rooms
left join blocks on blocks.id = romms.block_id
where blocks.type = false;

filtering the rooms entities just after the query returns, won't work because it would change the pagination data.
Any help is appreciated!!
Answer: You can do this with a single query when you use Mongoose's populate method which is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). For example, you can populate your block's rooms using the query builder:
var query = { "type": false };
Block.find(query)
     .select('-_id -name -type')
     .poulate('rooms')
     .exec(function (err, res){
        console.log('The first room is %s', res[0].rooms[0].name);
     })

Comment: `populate()` is a better solution when using Mongoose, so +1. Although technically, it's not _"one single query"_, it just looks like one. Internally Mongoose will do the same as the accepted answer.
Comment: @robertklep Thanks for the enlightenment, indeed technically it's equivalent to the two queries above under the Mongoose hood.
Answer: This has to be done as two separate queries in mongodb as it is not a relational database.
First do the blocks query:
db.blocksCollection.find({type : false})

This will return an array of blocks of type false.
This can be used to query the rooms collection for rooms in those blocks, using the $in operator: http://docs.mongodb.org/manual/reference/operator/query/in/
db.roomsCollection.find({block : { $in : [block1,block2,etc...]}})

Mongoose-mongoDB advanced query joins


ASP Clássico no Windows Azure

Question: Tenho uma aplicação web em ASP Clássico que utiliza uma DLL .NET registrada pelo regasm, um componente de upload (dundas upload) e o CDOSYS para enviar emails.
Esta aplicação é acessada por vários clientes e possui conexão com banco de dados SQL Server 2005.
É possível colocar esta aplicação no Windows Azure? E qual seria a melhor solução: Web Site, Virtual Machine ou Cloud Services?
Answer: Como sua aplicação precisa do registro de DLLs, o ideal é utilizar Virtual Machine, pois serão necessárias algumas configurações extras.
Aqui tem os passos para habilitar o ASP Clássico no seu site Azure:
http://khailiangtech.wordpress.com/2011/06/03/windows-azure-how-to-enable-classic-asp-support/
Aqui tem os passos para realizar o procedimento no modo Virtual Machine:
Link
O regasm pode ser usado pela Shell sem problemas.
Comment: Olá Cigano.
Eu li que o Cloud Service permite fazer algumas configurações no servidor. Só não sei se esse "pouco" seria o suficiente para instalar componentes e DLLs. (http://azure.microsoft.com/en-us/documentation/articles/choose-web-site-cloud-service-vm/)
Comment: Em teoria, uma Virtual Machine permite um grande controle. Não vejo porque isso não seria possível.

ASP Clássico no Windows Azure


HTTPS via cURL resposta JSON

Question: Estou tentando trazer o retorno da seguinte página com o cURL.
https://api.mercadolibre.com/sites/MLA/search/
Como faço isso, sendo o protocolo HTTPS?
Comment: `curl https://api.mercadolibre.com/sites/MLA/search/`?
Comment: Pela tag php, deve ser um método para realizar um request utilizando a API do cURL.
Answer: <?php
//$url = 'https://api.mercadolibre.com/sites/MLB/search/';
$url = 'https://api.mercadolibre.com/sites/MLB/search?category=MLB1648';

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CAINFO, getcwd() . DIRECTORY_SEPARATOR . 'cacert.pem');

$output = curl_exec($curl);
curl_close($curl);

header('Content-Type: application/json');
echo $output;

O arquivo cacert.pem deve ser baixado no endereço http://curl.haxx.se/ca/cacert.pem e colocado na mesma pasta onde fica o script acima.
OBS.: Quando usar a API do Mercado Livre, especifique MLB para buscar dados na versão brasileira do site. MLA se refere à versão argentina.

É possível também criar uma função para facilitar um pouco:
<?php

function get($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_CAINFO, getcwd() . DIRECTORY_SEPARATOR . 'cacert.pem');

    $output = curl_exec($curl);
    curl_close($curl);

    return $output;
}

header('Content-Type: application/json');

// Obtém produtos da categoria "Informática"
echo get('https://api.mercadolibre.com/sites/MLB/search?category=MLB1648');

// Obtém as categorias do site;
echo get('https://api.mercadolibre.com/sites/MLB/categories');

// Faz uma busca com a palavra-chave "pendrive"
echo get('https://api.mercadolibre.com/sites/MLB/search?q=pendrive');

Ver também:

Biblioteca cURL PHP

Documentação da API do Mercado Livre
Comment: Gabriel, deu certo com esse certificado. Muito obrigado pela ajuda. Vlw mesmo.
Comment: De nada. Estamos aqui para ensinar e aprender uns com os outros.
Comment: mais uma opção, que define a versão do SSL:
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
Comment: Esse arquivo cacert.pem é seguro?? E que site hacker é esse http://curl.haxx.se ?? Sinceramente tomem bastante cuidado, o certo é o arquivo PEM ser gerado no próprio servidor, um para cada domínio!!

HTTPS via cURL resposta JSON


EBS volume size?

Question: I'm looking at setting up an ubuntu instance with EC2.
It's asking me about EBS and the size in GB I need.
How do I know how much size I would need? All I want to do is run a few websites using nginx and install and run mysql.
I'm not expecting a huge amount of traffic.
What factors do you need to consider when picking a volume size?
Comment: Possible duplicate of [How much hard drive space to install MYSQL, PHP7 & nginx?](http://serverfault.com/questions/807978/how-much-hard-drive-space-to-install-mysql-php7-nginx)
Answer: You need to consider following things.
1. What is the source code size for your websites.
2. Are you going to use the MySQL on system or AWS RDS instance?
Considering these 2 facts you can decide. For instance Assuming 4 websites each of which have source code of 150 Mb. And Also assuming MySQL installed on ec2. A 20 GB EBS Volume is enough considering that all backups are on S3 bucket.
Comment: Thanks, how large would a MYSQL install be?
Comment: Installation of MySQL doesn't take more than 200 Mb of your disk space.

EBS volume size?


setting usb port to write only on linux

Question: How would I go about disabling reading from usb sticks but still have the ability to write to them?
The reasoning is this is a public internet access (kiosk more or less) computer but we want the user to be able save files to a usb stick but not have the ability to save files to the machine or execute files from the usb stick.
Thank you
Comment: Interesting problem: the USB drives are auto-mounted, so you'd have to work out how that happens, and whether you can configure a mount in write-only mode.
Comment: I never thought it would be possible to even have write-only storage (because you need to read the filesystem and all that stuff).
Answer: http://www.tuxfiles.org/linuxhelp/fstab.html
exec and noexec exec lets you execute binaries that are on that partition, whereas noexec doesn't let you do that. noexec might be useful for a partition that contains binaries you don't want to execute on your system, or that can't even be executed on your system. This might be the case of a Windows partition.
Answer: If I were you, I'd leave the USB stick read-write (as that makes a lot of sense), but I'd set your machine's partitions to read-only.  If you lock down X enough (prevent anyone from opening a shell via xterm, for example), then it should be a piece of cake.
Some notes :
mount /var as a ramdisk?
use noexec to prevent exection of binaries
It might be easier to just chroot execute the browser, with the USB-stick mounted under the chrooted jail.
Comment: i think that's what we will do..
Answer: Unless you control the USB sticks, write-only isn't going to work well. You're going to end up with all sorts of support issues and grousing by your users.
If I were you, I would setup the kiosks to run as dumb LTSP terminals, and start the users with a completely clean environment with every session. There are all sorts of ways to do this... my college had an XTerminal lab running on some ancient Unix back in 1994.

setting usb port to write only on linux


A record for www

Question:
Possible Duplicate:
What's the point in having "www" in a URL?

My present DNS configuration for my website's A record is as below
Name              Value
---------------------------
example.com       67.45.xx.xx
www.example.com   67.45.xx.xx

In above configuration user can open website either by example.com or by www.example.com.
One of my SEO team-member argues for single point access.
According to him search engine's crawler see 2 different name with same content. It is not good and we should configure domain in such a way that if user open example.com then browser automatically get redirected to www.example.com.
Now I have 2 questions

Does above argument is valid?
If yes then what changes I need to do in my DNS?
Answer: You don't need to change DNS for this at all.. He is correct in his argument though. Google doesn't like the same content for multiple hosts. So pick which one you want to use
example.com or www.example.com and do a 301 redirect from the one you don't want to use to the one you want to use.
The 301 re-direct is done with your webserver not dns. The 301 tells google.. hey.. the site now lives here.. change your links to use this url now and not the old one if it has links to both of the hosts.
Comment: Note that both `example.com` and `www.example.com` should pull up your website.  Despite what Google may or may not "like", users should be able to type either and get to your site (how you redirect and map things is your call, but if you break one or the other you're shooting yourself in the foot)
Comment: True, which is why they should implement the 301 redirect from one site name to the other, but remember that *users* punish domains that don't work when they type them in (and the [UX folks](http://ux.stackexchange.com) probably have harsh words for people whose sites break just because you didn't type "www").
Comment: yes but google punishes domains that serve the same content under different subdomains
Answer: Use a CNAME record to redirect to the correct page
A record
www.example.com :192.168.1.1
Then a CNAME record
*.example.com : www.example.com
example.com : www.example.com

A record for www


Why do some tennis broadcasts show the player's country next to their name?

Question: For example, see this screenshot of the broadcast of the men's final from the 2018 Australian Open, between Roger Federer and Marin Cilic. https://pbs.twimg.com/media/DUoA7E-VMAMDD0C.jpg
They show the player's country flag next to their name. I noticed that not all tournaments will do this, it depends on the people broadcasting the match.
I can understand if it was an Olympic event or something like the Davis Cup, where the players are representing and playing for their countries. However, in most other instances, tennis is an individual sport, and the player is representing and playing solely for themselves, so knowing their nationality is unnecessary.
My questions:

Why do the broadcasts show this information? What purpose does it serve?
Why do some broadcasts show it, but some do not?
Answer: I can't tell you exactly why, but it's not specific to tennis.  It appears that US broadcasts will show this on other sports competed by individuals.  In particular, country can also bee seen for some auto racing, golf, and cycling broadcasts.

For many sports, it's somewhat common to see a player's birthplace or hometown listed.  I can speculate that's it's simply easy-to-determine information about an individual that they can show to help viewers gain better familiarity with them.  It seems a small step to move from there to showing a country if there's a sufficient number of participants that would make such a graphic entertaining.

Comment: Thanks for the input! I figured that this was common in other individual sports, but I used tennis as the example since that's the only sport I'm familiar with. I didn't think that a player's nationality was important or even relevant in individual sports, but I guess enough people do care.


Definition of measurability of $f:\Bbb R\to \Bbb R$

Question: Let $\cal B$ be the set of all Borel-measurable subsets of $\Bbb R$ and $\cal L$ be the set of all Lebesgue-measurable subsets of $\Bbb R$. In measure theory texts, a function $f:\Bbb R\to \Bbb R$ is said to be measurable if for every $B\in \cal B$, we have $f^{-1}(B)\in \cal L$.
Why is $\cal B$ used for range of the function. Why $\cal L$ is not used on both sides:

a function $f:\Bbb R\to \Bbb R$ is said to be measurable if for every
  $L\in \cal L$, we have $f^{-1}(L)\in \cal L$

?
Comment: I think a big part of the reason is that you want continuous functions to be measurable.
Comment: And, more generally, for a function $X \to \mathbb R$, where $X$ is any measure space, we use Borel sets in $\mathbb R$ and the given measurable sets in $X$.  Perhaps you are just confused by using the same underlying set for two different purposes.
Answer: The basic reason is that the primary purpose of measurable functions is being able to integrate them, and we only need Borel sets in the codomain to define integrals.  Indeed, you can define the integral of a measurable function by approximating it by simple functions.  For these simple functions to be measurable, you need sets of the form $f^{-1}(I)$ to be measurable, where $I\subseteq\mathbb{R}$ is an interval.  The $\sigma$-algebra generated by intervals is the Borel $\sigma$-algebra, so asking for $f^{-1}(I)$ to be measurable for all intervals $I$ is equivalent to asking for $f^{-1}(B)$ to be measurable for all Borel $B$.
So, for most purposes, we don't lose anything if we only require the inverse images of Borel sets to be measurable, rather than the inverse sets of Lebesgue measurable sets.  On the other hand, we do lose quite a lot if we use Lebesgue measurable sets on the codomain.  In particular, not every continuous function (or even every homeomorphism) $\mathbb{R}\to\mathbb{R}$ would be measurable, if we used $\mathcal{L}$ on both the domain and codomain.  (Proof sketch: take a fat Cantor set $C$ and the usual null Cantor set $D$, and a homeomorphism $f:\mathbb{R}\to\mathbb{R}$ that maps $C$ to $D$.  Every subset of $D$ is in $\mathcal{L}$ since it is null, but not every subset of $C$ is in $\mathcal{L}$, so $f$ is not $\mathcal{L}$-to-$\mathcal{L}$ measurable.)
Underlying all of this is that the domain and codomain play fundamentally different roles when we're talking about measurable functions $\mathbb{R}\to\mathbb{R}$.  The domain is a measure space: we care about measuring the size of subsets of this, and using this to more generally define integrals of functions on it.  We don't actually care that the domain is $\mathbb{R}$ specifically; we can make similar definitions for functions $X\to\mathbb{R}$ where $X$ is any measure space.  So, that's the difference between using $\mathcal{B}$ and $\mathcal{L}$ on the domain: we're just changing what our domain measure space is.
On the other hand, the codomain $\mathbb{R}$ is all about actual real numbers and their algebraic (and topological) properties.  An integral of a real-valued function is a kind of "continuous weighted sum" of values of the function, so we care very much about being able to take linear combinations of elements of our codomain, and take limits of them.  The natural generalization of the codomain is to consider an arbitrary topological vector space, rather than an arbitrary measure space.  We don't care about measuring sizes of subsets of our codomain, and so we don't care about throwing in arbitrary Lebesgue null sets.


Fixed div no matter which browser size

Question: I have a little image, with some decoration, that I need to stick to the top-right corner of my page. But no matter how many different types of code I've used, I can't get it right.
It's sort of like the "Welcome to Q&A for professional.." on top of this page, it stays there no matter how far down I scroll.
I just need to do this with a  containing an image, that sticks to the right-margin of the browser, even if i resize.
You can look at the website http://dawtano.com/pp/ and see the image, that's currently in the middle of the page..
Answer: Apply {background-position: right top;} to the background image.
Answer: You just need to specify the gravity of the background to right top.
#deco {
    background: url("images/header-deco.png") no-repeat scroll right top transparent;
    height: 375px;
    margin-top: 7px;
    width: auto;
}

Answer: If i unsterstand your question correct:
Use position: fixed and top, right in your css
Oh, it´s a background-image...
Use background-position:right top;
Answer: I assume you mean for the #deco div. If so, based on your current example, this should work:

Fixed div no matter which browser size


does it work to nest media queries inside keyframes for CSS?

Question: This is my generated CSS after running this in my extra css under components
<code>@layer components {
  @keyframes alt-pop-enter {
    from {
      @apply translate-y-2 opacity-0 sm:translate-y-0 sm:translate-x-2;
    }
    to {
      @apply translate-y-0 opacity-100 sm:translate-x-0;
    }
  }
</code>
this produces the following as generated css
<code>@keyframes alt-pop-enter {
  from {
    --tw-translate-y: 0.5rem;
    transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
    opacity: 0;
  }

  @media (min-width: 640px) {
    from {
      --tw-translate-y: 0px;
      --tw-translate-x: 0.5rem;
      transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
    }
  }

  to {
    --tw-translate-y: 0px;
    transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
    opacity: 1;
  }

  @media (min-width: 640px) {
    to {
      --tw-translate-x: 0px;
      transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
    }
  }
}
</code>
Am I right to say that the media queries will not be executed since they are not legal inside keyframes?
Answer: i think you should change to this instead
As state in https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes and https://www.w3schools.com/cssref/css3_pr_animation-keyframes.php, the valid value are

0-100%
from (same as 0%)
to (same as 100%)

<code>@keyframes alt-pop-enter {
  from {
    --tw-translate-y: 0.5rem;
    transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
    opacity: 0;
  }

  to {
    --tw-translate-y: 0px;
    transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
    opacity: 1;
  }
}

@media (min-width: 640px) {
  @keyframes alt-pop-enter {
    from {
      --tw-translate-y: 0px;
      --tw-translate-x: 0.5rem;
      transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
    }

    to {
      --tw-translate-x: 0px;
      transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
    }
  }
}
</code>
Comment: so the answer to the question "the media queries will not be executed since they are not legal inside keyframes?" is yes, they will not be executed because they are not legal inside keyframes. Yes?
Comment: @KimStacks yea, as you can check this documentation at https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes, as it values only support `,  from, to ,`


What could happen, if we dont leave Beta

Question: During promoting for more upvotes to be able leaving Beta I got asked if it would be bad, if we dont leave beta.
So now I ask, could there be a penalty, if we dont leave beta?
Answer: A few reasons being 'stuck' would be bad:
Moderators:
In my opinion the longer we're stuck in beta the longer we're stuck with pro-tem moderators. Since the last moderator election the participation of the community has widened and we can see who now has the time and effort to invest in moderation. This means that they're also stuck with moderating until graduation. This isn't fair to them, and the burden at some point needs to be shouldered.
SO questions won't be migrated
As with ServerFault, Programmers, we would enjoy the benefit of being able to migrate all Magento-centric questions here. We get the odd ones from time to time - but having them all flow to this site would only increase its value to the community.
Branding
Less of an issue, but not having a properly designed SE-site theme makes us less legit and perhaps contributes to the high number of flyby questions; people just don't know/remember who we are and how to get back here.
URL?
The .stackexchange.com may stick around as it has recently with other beta launches - and maybe a mod can answer to this - but how cool would mageoverflow.com be?
Comment: +5 for mageoverflow.com
Comment: +10 for mageoverflow.com ;)
Comment: unless you have special powers only +1 (or multiple accounts) is possible ;-)
Comment: I have special powers, but I can only go up to +5. I guess @davidalger is twice as powerful as I am. :)
Answer: StackExchange are pretty good at letting only "mature" sites make it to "the big league". I doubt that they will let the site go away. There's a lot of activity and visibility here, and I see that trend increasing (based on my time spent moderating)
I think that we may soon see some increased visibility for the Magento SE site which will hopefully help drive traffic, grow the community (which will need remediation for sure).
We just all need to knuckle up and buckle up to ensure that the good content bubbles up and that users get the help they need.
It would be nice to get a custom domain name, but this privilege is reserved for a select few sites on the SE network; ref http://stackexchange.com/sites.


Training threshold vs validation threshold for better prediction results?

Question: Between the two, should I use a model's training or validation threshold to get best results (from a distributed random forest binary classifier built using h2o.ai) (especially when their values differ by orders of magnitude)?
Details:
Used h2o flow UI to create a RDF model and examined the testing and validation thresholds optimized for maximizing the minimum per class accuracy in each set (since the classes were imbalanced), eg. for the validation set ...

Now I have a set of new data that I would like to make a prediction on using the exported model. The RDF is just going to output probability values for both of the response classes, so I need to choose a threshold (in my case, for the max_min_per_class_accuracy) to use as a cutoff point to delineate them.
Don't know much about machine learning, but to me, I would think that using the validation threshold would be better since the threshold that worked best with the training set would be too optimistic and overfit. However, the default threshold used by the h2o python API is for the training set which makes me question my own preference (as again, I have little experience). So which should I use, the threshold for the training set or for the validation set? Thanks
Is this a wrong-headed question to be asking in the first place or is there something about this question that shows some general confusion about concepts? Let me know if so.
Answer: I like to use the average of the best threshold on each of training and validation data set.
This is figure 4-2 from Practical Machine Learning with H2O (Disclaimer: my book):

It shows the best threshold on each of train, valid and test. The dashed line is the average of the two. (Aside: valid and test lines are noisier, as they are based on less data: the split was 13:1:1 )
The point is that any of these (training, valid, their average) will be in the right ballpark.
The reason I use the average is because the training data is 13x more data, but might have over-fitted, so I hope that the validation data can balance it. I give them equal weight because this particular example is time series, so the validation data is newer (closer to the test data) than the training data.  (In this particular example, using the average is worse than using the training threshold, but better than the validation threshold.)
Comment: @lampShadesDrifter a) It is the metric value difference, not so much the threshold difference, that matters; b) if you get huge differences in your metric, too, that would be a red flag that the model has not learned anything real. Try cross-validation or other train/valid splits (assuming it is not a time-series) to see if the gap is always there? (And to give you more things to average together!)
Comment: For my particular example, the training and validation thresholds that maximize the metric I'm using are in totally different ballparks (differing by orders of magnitude (eg. train_thresh=0.101, valid_thresh=0.000188)) (note that the classes in the data were very imbalanced and I used the `balance classes` flag in `h2o flow UI` to try to account for this). Would the same averaging logic hold in this scenario?


How to get custom product line item text field value?

Question: by using commerce customisable products module, I created a custom product line item type to which I added a text field (Machine name field_license_details). By following this excellent video tutorial
http://commerceguys.com/blog/commerce-module-tuesday-commerce-customizable-products-screencast
I was able to create a node/page which include the text field I mentioned before. However, what I find impossible to do, is to get the value that the user entered to that field. For example, when the user has entered something in the text field and clicks the add to cart button, I want the text he typed , to be 'placed' to a variable so i can do whatever i like with it for example display it back to the user or write it down to a file etc.
I understand that in order to achieve that I would need to write my own module , but I am not sure which hook I should implement, and how exactly  extract the string to a variable.
As you probably already understood by the nature of the question ,I am just getting started on drupal, so any suggestions would be more than welcome.
Thanks in advance
PS I am using drupal 7.22 (the latest stable version and I have installed the drupal commerce module, the commerce file and commerce customisable products modules.
Comment: you can use view module to get that variable.
Comment: @Human love Thanks for the suggestion. I will give it a go
Answer: I ended up doing the following :
<code>    function my_Module_form_alter(&$form, &$form_state, $form_id){
           if ($form_id == 'commerce_cart_add_to_cart_form_12'){
                  dpm($form, 'cart form'); //to use with deve module
                  $form['#submit'][]=('my_Module_commerce_add_to_cart_form_12_submit');
                  }
            }

       function my_Module_commerce_add_to_cart_form_12_submit($form, &$form_state){

             $user_text_temp=$form_state['values']['line_item_fields']['field_license_details'][LANGUAGE_NONE][0]['value'];
             dpm($user_text_temp, 'extract value is ');
            // whatever else you want to do with that user_text_temp value
          }
</code>
I think that's the easiest way to do what i want. I posted it because it may be of use to people new to drupal.


Is it better to use a separate commit message for a git merge?

Question: I come from an SVN background so I'm not sure what the typical git workflow looks like. When you merge in SVN, you provide a commit message describing the merge. This is necessary because SVN's merge-tracking has historically been poor.
I noticed that git's default behavior is to automatically commit the results of the merge if it is successful. This means that the log normally won't show merges, so everything in the history looks like it was developed in one branch. Is this preferable to showing merges as additional commits? I can think of several reasons why and why not, but I'd like some input from other users.
Answer: I think you are mistaking two situations (or I do not understand what you are asking about).

If you merge a side branch which is direct child of the branch you are currently on, it results in so called fast forward situation. Ordinary git wouldn't create a merge commit, but just advance branch tip, but you can prevent it with --no-ff option.
The default is to avoid such pointless merges because it plays better in truly distributed development.

If the branch you are on and the branch you are merging are truly divergent, i.e there are on each branch commits which are not on other branch, the git would do a merge, and if it can do a merge without conflict, it would automatically create a merge commit. Such merge commit would have automated commit message, subject to merge.log config variable (formerly merge.summary). You can prevent comitting such an automated commit with --no-commit option.
Of course "git log" would show merge commits, unless you use "git log --no-merges".

I hope that this explanation would help a bit.
Comment: Ah, so that's what fast forward means. Good to know that less trivial merges have automatic commit messages. Thanks for clearing that up.
Answer: Unless you supply the --no-merges option to git log, it will normally show merges which are given a brief auto-generated commit description.
This is usually fine as git records the parentage of the commit and the interesting features of a merge are its constituent branches.
Try a git log --graph --oneline or use a graphical history viewer and you may (should!) be convinced that the way that git records merges is much more important and useful than a long winded merge commit message.
Merges only really need a detailed commit message if there was something 'magical' that was done in the resolve. As this means manual intervention this is easy to add at the this point.
Comment: When a merge has conflicts, the merge commit is aborted to let you fix them. You then commit, and get another helpful auto-generated message with a list of files which had conflicts. This is the most common case for adding description - it's helpful to know why there were conflicts and how they were resolved. If there weren't conflicts, the simple auto-generated message tends to be good - though some will add a quick list of features merged in (see git.git for an example of this).
Comment: Marking this as the answer because you point out that merges only need messages if something special happens (i.e. manual conflict resolution). I'm so used to writing out the range of revisions being merged in SVN that I just assumed merge messages were necessary everywhere.


A question about an epsilon-delta proof

Question: Currently, I am stuck on a question:
 Let $ g : [ 0 , \infty ) \mapsto \mathbb{R} $ be defined by $g(x)=  \left\{
 \begin{array}{ll}
  x^2  & \mbox{if } 0 \leq x \leq 1 \\
  3x & \mbox{if } x > 1
 \end{array}
\right.$
Prove: For $\epsilon =1$, $\forall \delta >0$, $\exists x \in \mathbb{R}$ such that $|x-1|<\delta$ and $|g(x)-g(1)|>\epsilon$.
I know how to do a normal epsilon-delta proof with continuity. But now $\epsilon$ is fixed and I do not know how to handle this problem. My work so far:
Proof: Let $g$, $\epsilon$, and $x$ as above:
$|g(x)-g(1)|=|x^2-1|=|(x+1)(x-1)|=|x+1||x-1|=(|x|+1)|x-1|$
I have no clue how to get rid of the $|x|$, normally I would use that $|x|<|a|+\delta$, but since we do not have an $a$ here, I am pretty sure we cannot use that.
Any hints would be appreciated, preferably no full answers as I have to do it myself one day.
Thanks in advance!
Comment: Your $g$ is piecewise defined. Look at both pieces.
Comment: I think you have an inequality direction typo there, $|g(x)-g(1)|<\epsilon$ makes more sense to me.
Comment: @J.W.Perry I wish I was, but the question clearly states $|g(x)-g(1)> \epsilon$ Daniel Fischer, what do you mean?
Comment: You want to find an $x$ with $\lvert x-1\rvert < \delta$ but $\lvert g(x) - g(1)\rvert > 1$. Try for example $x_1 = 1 - \frac{\delta}{2}$ and $x_2 = 1+\frac{\delta}{2}$.
Comment: $x_1$ gives $g(x_1)=1-\delta + \frac{\delta ^2}{4}$ and $x_2$ gives $g(x_2)=3+1.5 \delta$. The difference is $g(x_2)-g(x_1)=2+2.5 \delta - \frac{\delta ^2}{4}$ So we have to find a $\delta$ s.t. $2+2.5 \delta - \frac{\delta ^2}{4}=1$?
Answer: Note that you'er busy showing that $g$ is discontinuous at $x = 1$.
For $0 \leq x < 1$, $| g(x) - g(1) | = 1 - x^2$ and for $x > 1$, $| g(x) - g(1) | = 3x - 1$. Given some $\delta > 0$, you have to either find an $x \in (1 - \delta, 1)$ such that $1 - x^2 > 1$ or an $x \in (1, 1 + \delta)$ such $3x - 1 > 1$.
Now the first one is not going to work, which was to be expected, because $g$ is continuous on $[0,1]$, so we better try the other one. So let's try $x = 1 + \delta/3$, which satisfies $x \in (1, 1 + \delta)$ and also $3x - 1 = 2 + \delta > 1$.
Comment: So this would be correct? Proof: For $0 \leq x \leq 1, |g(x)-g(1)|=1-x^2$ and for $x>1, |g(x)-g(1)|=3x-1$. Given some $\delta > 0$, we have to find a $x \in (1-\delta, 1)$ such that $1-x^2>1$ or a $x \in (1, 1+\delta)$ such that $3x-1>1$. \\*
Since $\forall x \in \mathbb{R}, x^2>0 \Rightarrow 1-x^2 < 1$. Hence, this will not work. \\*
If we let $x=1+\frac{\delta}{3}$, $3x-1=2+\delta > 1$ \\*
Conclusion: For $\epsilon =1$, $\forall \delta >0$, $\exists x \in \mathbb{R}$ such that $|x-1|<\delta$ and $|g(x)-g(1)|>\epsilon$, namely $x= 1 + \frac{\delta}{3}$.
Comment: Actually, shouldn't it be: for $x>1$, $|g(x)-g(1)|=3x-3$ @Magdiragdag ?
Comment: @NigelOvermars No, $g(1) = 1$, since it falls in the case $0 \leq x \leq 1$. This is basically the reason you have to look at the case $x > 1$ for your $x$.
Comment: @NigelOvermars And yes, that would be correct, although if you want to just give a short proof without any explanation, I'd just do the following. Proof: Take $\delta > 0$. Let $x$ be $1 + \delta/3$. Then $|x-1| = \delta/3 < \delta$ and $|g(x) - g(1)| = |3(1 + \delta/3) - 1|  = 2 + \delta > 1$.

A question about an epsilon-delta proof


why we need to to identify the external markers in marker-controlled watershed segmentaion?

Question: why we need to to identify the external markers in marker-controlled watershed segmentaion?
why it is not enough to identify internal markers of the objects of interest?
please help, i'm confused
thanks
Comment: From your question, it appears you're trying to script some existing watershed segmentation tool or algorithm, probably running in some GIS environment.  This seems more like a question about the specific algorithm you're using, rather than a programming question.
Comment: my question is about this: http://cmm.ensmp.fr/~beucher/wtshed.html
Answer: Using mahotas, with a marker for the background, I get weird things like that


Nodejs com erro de sintaxe

Question: Ola, eu uso o linux Mint 20.3.
Instalei o nodejs  e o npm, funcionam normalmente, mas quando eu tento executar um arquivo com node, ele da esse erro ai.
Eu instalei o node em um pc velho que tambem tem mint, e roda normal, Como pode? Alguem sabe oq é?ja aconteceu contigo?
Veja que ele guarda variaveis, executa funções  normalmente, mas nao executa arquivos, nesse caso o index.js(que tem dentro un console.log).
É como se eu tivesse digitado o index errado, mas é assim mesmo, deveria funcionar.
Answer: Para executar o arquivo pela linha de comando dá pra executar no console
node caminho/para/arquivo.js

Também tem como carregar o arquivo de script dentro do comando node se digitar ´.load caminho/para/arquivo.js´
Comment: kkkkkkk nossa perdi muuuito tempo com isso, eu sou muito burro.
Comment: Muito obrigado mesmo

Nodejs com erro de sintaxe


Too many open output files while splitting a CSV

Question: Very novice attempt at python here.
I tried implementing something like was discussed in this question Splitting csv file based on a particular column using Python
My goal is to take a file with 15 million lines of 500 ticker symbols and put each ticker in their own file.
However, when I'm running it, I'm getting
OSError: [Errno 24] Too many open files: 'APH.csv'
All of the lines of data are in order (ie all of the lines of data for ticker "A" are one right after another, so I could close a file before going on to the next one). I'm not sure where in this code I would close the file before going on to the next one. FYI - this is on a Mac if that matters.
My code is
import csv

with open('WIKI_PRICES_big.csv') as fin:
    csvin = csv.DictReader(fin)
    # Category -> open file lookup
    outputs = {}
    for row in csvin:
        cat = row['ticker']
        # Open a new file and write the header
        if cat not in outputs:
            fout = open('{}.csv'.format(cat), 'w')
            dw = csv.DictWriter(fout, fieldnames=csvin.fieldnames)
            dw.writeheader()
            outputs[cat] = fout, dw
        # Always write the row
        outputs[cat][1].writerow(row)
    # Close all the files
    for fout, _ in outputs.values():
        fout.close()

Comment: Are you open to using Pandas?
Answer: Based on the file structure you describe, the following should do it.
The trick is that if the ticker values are always in order, you only need to keep open a single file output file at any one time. You can then close the old one and reopen the new one when you come across a new ticker value.
import csv

fout = False
with open('WIKI_PRICES_big.csv') as fin:
    csvin = csv.DictReader(fin)
    seen = []

    for row in csvin:
        cat = row['ticker']

        # Open a new file and write the header.
        if cat not in seen:
            seen.append(cat)

            if fout:  # Close old file if we have one.
                fout.close()

            fout = open('{}.csv'.format(cat), 'w')
            dw = csv.DictWriter(fout, fieldnames=csvin.fieldnames)
            dw.writeheader()

        # Always write the row
        dw.writerow(row)

    fout.close()

Comment: This is still giving a too many open files. I'm going to take a different approach tomorrow... Thank you
Comment: @Mary are you sure you copied and ran this code correctly? I've tested this here (also on a Mac) up to 10,000 output files without issue.


Multiple DatePickers in same activity

Question: I am absolutely new to the Android platform and have been building an application while learning the development process.
Currently, I am working on an activity in which i need to deploy 2 date pickers. One is a "Start Date" and the other is an "End date". I have been following the DatePicker tutorial on the android developers page here: http://developer.android.com/resources/tutorials/views/hello-datepicker.html
For one DatePicker, it works just fine.
Now my problem is, when I replicate the whole process for a second date picker, it shows up just fine on the emulator as well as on the handset. But when no matter which button I press to select the dates, only the first TextView is updated and the second TextView keeps showing the current date.
Here is the code:
package com.datepicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class datepicker extends Activity {

private TextView mDateDisplay;
private TextView endDateDisplay;
private Button mPickDate;
private Button endPickDate;
private int mYear;
private int mMonth;
private int mDay;

static final int START_DATE_DIALOG_ID = 0;
static final int END_DATE_DIALOG_ID = 0;

/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    /*  capture our View elements for the start date function   */
    mDateDisplay = (TextView) findViewById(R.id.startdateDisplay);
    mPickDate = (Button) findViewById(R.id.startpickDate);

    /* add a click listener to the button   */
    mPickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(START_DATE_DIALOG_ID);
        }
    });

    /* get the current date */
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    /* display the current date (this method is below)  */
    updateStartDisplay();

 /* capture our View elements for the end date function */
    endDateDisplay = (TextView) findViewById(R.id.enddateDisplay);
    endPickDate = (Button) findViewById(R.id.endpickDate);

    /* add a click listener to the button   */
    endPickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(END_DATE_DIALOG_ID);
        }
    });

    /* get the current date */
    final Calendar c1 = Calendar.getInstance();
    mYear = c1.get(Calendar.YEAR);
    mMonth = c1.get(Calendar.MONTH);
    mDay = c1.get(Calendar.DAY_OF_MONTH);

    /* display the current date (this method is below)  */
    updateEndDisplay();
}

private void updateEndDisplay() {
    endDateDisplay.setText(
            new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("-")
                .append(mDay).append("-")
                .append(mYear).append(" "));

}

private void updateStartDisplay() {
    mDateDisplay.setText(
            new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("-")
                .append(mDay).append("-")
                .append(mYear).append(" "));

}

/* the callback received when the user "sets" the date in the dialog for the start date function    */
 private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateStartDisplay();
            }
        };

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case START_DATE_DIALOG_ID:
        return new DatePickerDialog(this,
                    mDateSetListener,
                    mYear, mMonth, mDay);
    }
    return null;
}
/* the callback received when the user "sets" the date in the dialog for the end date function  */

private DatePickerDialog.OnDateSetListener endDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateStartDisplay();
            }
        };

protected Dialog onCreateDialog1(int id) {
    switch (id) {
    case END_DATE_DIALOG_ID:
        return new DatePickerDialog(this,
                    endDateSetListener,
                    mYear, mMonth, mDay);
    }
    return null;
}

}
Please advise on the changes required for the code.
Comment: Both ID's need to be different.
Comment: You do not need to make two separate DatePicker Dialogs. See my answer
Answer: I have a solution that allows for an unlimited number of date fields without adding new dialog types. When the user clicks one of the buttons, I register which TextView and Calendar is currently being modified before launching the DatePickerDialog. The dialog's OnDateSetListener then updates the registered TextView and Calendar.
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MultiDatePickerActivity extends Activity {

    private TextView startDateDisplay;
    private TextView endDateDisplay;
    private Button startPickDate;
    private Button endPickDate;
    private Calendar startDate;
    private Calendar endDate;

    static final int DATE_DIALOG_ID = 0;

    private TextView activeDateDisplay;
    private Calendar activeDate;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.multidatepicker);

        /*  capture our View elements for the start date function   */
        startDateDisplay = (TextView) findViewById(R.id.startDateDisplay);
        startPickDate = (Button) findViewById(R.id.startPickDate);

        /* get the current date */
        startDate = Calendar.getInstance();

        /* add a click listener to the button   */
        startPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDateDialog(startDateDisplay, startDate);
            }
        });

        /* capture our View elements for the end date function */
        endDateDisplay = (TextView) findViewById(R.id.endDateDisplay);
        endPickDate = (Button) findViewById(R.id.endPickDate);

        /* get the current date */
        endDate = Calendar.getInstance();

        /* add a click listener to the button   */
        endPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDateDialog(endDateDisplay, endDate);
            }
        });

        /* display the current date (this method is below)  */
        updateDisplay(startDateDisplay, startDate);
        updateDisplay(endDateDisplay, endDate);
    }

    private void updateDisplay(TextView dateDisplay, Calendar date) {
        dateDisplay.setText(
                new StringBuilder()
                    // Month is 0 based so add 1
                    .append(date.get(Calendar.MONTH) + 1).append("-")
                    .append(date.get(Calendar.DAY_OF_MONTH)).append("-")
                    .append(date.get(Calendar.YEAR)).append(" "));

    }

    public void showDateDialog(TextView dateDisplay, Calendar date) {
        activeDateDisplay = dateDisplay;
        activeDate = date;
        showDialog(DATE_DIALOG_ID);
    }

    private OnDateSetListener dateSetListener = new OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            activeDate.set(Calendar.YEAR, year);
            activeDate.set(Calendar.MONTH, monthOfYear);
            activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateDisplay(activeDateDisplay, activeDate);
            unregisterDateDisplay();
        }
    };

    private void unregisterDateDisplay() {
        activeDateDisplay = null;
        activeDate = null;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this, dateSetListener, activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DAY_OF_MONTH));
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);
        switch (id) {
            case DATE_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DAY_OF_MONTH));
                break;
        }
    }
}

This kind of flexibility is useful in an application where you don't know how many date pickers you will need until runtime.
Comment: I like this approach. I needed to use 4 DatePickers and the first approached seemed like too much work.
Comment: the best solution, very elegant, i like it.
Answer: You need to make 2 separate DatePicker Dialogs
Make 2 Listeners
int from_year, from_month, from_day,to_year, to_month, to_day; //initialize them to current date in onStart()/onCreate()
DatePickerDialog.OnDateSetListener from_dateListener,to_dateListener;

Implement them...
         from_dateListener = new OnDateSetListener(){

            public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {

                          ...

                }
            }

        };
        to_dateListener = new OnDateSetListener(){
            public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
                .....
            }
        };

Create Seperate Dialogs for both of them
int DATE_PICKER_TO = 0;
int DATE_PICKER_FROM = 1;

@Override
protected Dialog onCreateDialog(int id) {

    switch(id){
        case DATE_PICKER_FROM:
                return new DatePickerDialog(this, from_dateListener, from_year, from_month, from_day);
            case DATE_PICKER_TO:
                return new DatePickerDialog(this, to_dateListener, to_year, to_month, to_day);
    }
        return null;
}

Comment: Just one question. Would it be alright to add my working code along with its XML so anyone with a similar problem can get the solution right away?
Comment: You can take a look here how they used setCallBack method to pass the callback function - http://androidtrainningcenter.blogspot.com/2012/10/creating-datepicker-using.html
Answer: Expanding Adam's option into an slightly lighter weight interpretation and potentially more useful, I decided to maintain an int reference for the element ID that instantiated the dialog request and then just referenced that in the final event handler.  This has the added benefit of fitting nicely into a switch statement in this method in case you have multiple date inputs but want specific formatting for each or groups of each.  All snippets below are in my Activity class directly
Instance variables
private static final int        DIALOG_DATE_PICKER  = 100;
private int                     datePickerInput;

Dialog Handler
@Override
public Dialog onCreateDialog(int id)
{
    switch(id) {
        case DIALOG_DATE_PICKER:
            final Calendar c = Calendar.getInstance();
            DatePickerDialog dialog = new DatePickerDialog(this, dateSetListener, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
            return dialog;
    }
    return null;
}

Click Listener
private OnClickListener datePickerListener =
    new OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        datePickerInput = v.getId();
        showDialog(DIALOG_DATE_PICKER);
    }
};

Date Selection Handler
private DatePickerDialog.OnDateSetListener dateSetListener =
    new DatePickerDialog.OnDateSetListener()
{
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        switch( datePickerInput ) {
            case R.id.datePicker1:
                ((EditText) findViewById( datePickerInput ))
                    .setText(...);
                ...
                break;
            case R.id.datePicker2:
                ...
                break;
            default:
                ...
                break;
        }
    }
};

Answer: I think I've found a cleaner solution. It's a mix between what's advised by Google and the comments I read here.
In my case, It's even working when called from a Viewpager's fragment.
Basically, I pass a bundle of arguments to the dialog fragment when calling the picker dialog from my fragment, as defined here : Android: Pass data(extras) to a fragment
Then I get back the bundle value in my DialogFragment class, and switch on its value.
Here are the two listeners of both my startDate and endDate buttons, from my Fragment code :
    mWylStartDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Bundle bundle = new Bundle();
            bundle.putInt("DATE",1);

            DialogFragment newFragment = new DatePickerFragment();
            newFragment.setArguments(bundle);

            newFragment.show(getFragmentManager(), "datePicker");
        }
    });

    mWylEndDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Bundle bundle = new Bundle();
            bundle.putInt("DATE",2);

            DialogFragment newFragment = new DatePickerFragment();
            newFragment.setArguments(bundle);

            newFragment.show(getFragmentManager(), "datePicker");

        }
    });

Here's my DatePickerFragment class
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{

    static final int START_DATE = 1;
    static final int END_DATE = 2;

    private int mChosenDate;

    int cur = 0;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {

        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        Bundle bundle = this.getArguments();
        if (bundle != null)
        {
            mChosenDate = bundle.getInt("DATE", 1);
        }

        switch (mChosenDate)
        {

            case START_DATE:
                cur = START_DATE;
                return new DatePickerDialog(getActivity(), this, year, month, day);

            case END_DATE:
                cur = END_DATE;
                return new DatePickerDialog(getActivity(), this, year, month, day);

        }
        return null;
    }

    @Override
    public void onDateSet(DatePicker datePicker, int year, int month, int day)
    {

        if (cur == START_DATE)
        {
            // set selected date into textview
            Log.v("Date Début", "Date1 : " + new StringBuilder().append(month + 1)
                    .append("-").append(day).append("-").append(year)
                    .append(" "));
        } else
        {
            Log.v("Date fin", "Date2 : " + new StringBuilder().append(month + 1)
                    .append("-").append(day).append("-").append(year)
                    .append(" "));
        }
    }
}

Answer: simply make boolean variable in mainActivity like this ::
private boolean startDateOrEndDAte = true;

then make the listeners for the buttons like this like this and make the value of the variable change for evrey button::
DialogFragment datePicker = new DatePickerFragment();

attendDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePicker.show(getSupportFragmentManager(),"Date Picker");
                startOrEnd = true ;
            }
        });
        leaveDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePicker.show(getSupportFragmentManager(),"Date Picker");
                startOrEnd = false ;
            }
        });

then in onDateSet methode just add if statment like this ::
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR, year);
    c.set(Calendar.MONTH, month);
    c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    String date = DateFormat.getDateInstance().format(c.getTime());
    attendDate = findViewById(R.id.attend_date);
    leaveDate = findViewById(R.id.leave_date);

    if (startOrEnd) {
        attendDate.setText(date);
    } else {
        leaveDate.setText(date);
    }
}

Answer: you can use simply this type
public class MainActivity extends Activity {

     private TextView startDateDisplay;
        private TextView endDateDisplay;
        private Button startPickDate;
        private Button endPickDate;
        private Calendar startDate;
        private Calendar endDate;

        static final int DATE_DIALOG_ID = 0;

        private TextView activeDateDisplay;
        private Calendar activeDate;

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            /*  capture our View elements for the start date function   */
            startDateDisplay = (TextView) findViewById(R.id.startDateDisplay);
            startPickDate = (Button) findViewById(R.id.startPickDate);

            /* get the current date */
            startDate = Calendar.getInstance();

            /* add a click listener to the button   */
            startPickDate.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDateDialog(startDateDisplay, startDate);
                }
            });

            /* capture our View elements for the end date function */
            endDateDisplay = (TextView) findViewById(R.id.endDateDisplay);
            endPickDate = (Button) findViewById(R.id.endPickDate);

            /* get the current date */
            endDate = Calendar.getInstance();

            /* add a click listener to the button   */
            endPickDate.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDateDialog(endDateDisplay, endDate);
                }
            });

            /* display the current date (this method is below)  */
            updateDisplay(startDateDisplay, startDate);
            updateDisplay(endDateDisplay, endDate);
        }

        private void updateDisplay(TextView dateDisplay, Calendar date) {
            dateDisplay.setText(
                    new StringBuilder()
                        // Month is 0 based so add 1
                        .append(date.get(Calendar.MONTH) + 1).append("-")
                        .append(date.get(Calendar.DAY_OF_MONTH)).append("-")
                        .append(date.get(Calendar.YEAR)).append(" "));

        }

        public void showDateDialog(TextView dateDisplay, Calendar date) {
            activeDateDisplay = dateDisplay;
            activeDate = date;
            showDialog(DATE_DIALOG_ID);
        }

        private OnDateSetListener dateSetListener = new OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                activeDate.set(Calendar.YEAR, year);
                activeDate.set(Calendar.MONTH, monthOfYear);
                activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                updateDisplay(activeDateDisplay, activeDate);
                unregisterDateDisplay();
            }
        };

        private void unregisterDateDisplay() {
            activeDateDisplay = null;
            activeDate = null;
        }

        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
                case DATE_DIALOG_ID:
                    return new DatePickerDialog(this, dateSetListener, activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DAY_OF_MONTH));
            }
            return null;
        }

        @Override
        protected void onPrepareDialog(int id, Dialog dialog) {
            super.onPrepareDialog(id, dialog);
            switch (id) {
                case DATE_DIALOG_ID:
                    ((DatePickerDialog) dialog).updateDate(activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DAY_OF_MONTH));
                    break;
            }
        }

}

Answer: I make use of the DialogFragment tag to distinguish between instances of the DatePickerFragment in my activity. It works well and keeps things simple. This way you can reuse the same DatePickerFragment class and have numerous instances on your activity, set apart by the unique tag used for each.
The DatePickerFragment class is straight forward as per Android Dev documentation with an added interface which the activity has to implement. This allows the DatePickerFragment to call back to the activity, passing a Date object and identifying tag back.
Android Pickers
public class DatePickerFragment extends DialogFragment
  implements DatePickerDialog.OnDateSetListener {

  public interface DatePickerWithTagListener {
    public void onDateSet(String tag, Date date);
  }

  private static final String ARG_YEAR = "paramYear";
  private static final String ARG_MONTH = "paramMonth";
  private static final String ARG_DAY = "paramDay";

  private int mParamYear;
  private int mParamMonth;
  private int mParamDay;

  private Activity mActivity;
  private DatePickerFragment.DatePickerWithTagListener mListener;

  public DatePickerFragment() {
    // Required empty public constructor
  }

  /**
   * Use this factory method to create a new instance of
   * this fragment using the provided parameters.
   *
   * @param paramYear Year parameter.
   * @param paramMonth Month parameter.
   * @param paramDay Day parameter.
   * @return A new instance of fragment DatePickerFragment.
   */
  public static DatePickerFragment newInstance(int paramYear, int paramMonth, int paramDay) {
    DatePickerFragment fragment = new DatePickerFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_YEAR, paramYear);
    args.putInt(ARG_MONTH, paramMonth);
    args.putInt(ARG_DAY, paramDay);
    fragment.setArguments(args);
    return fragment;
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
      mParamYear = getArguments().getInt(ARG_YEAR);
      mParamMonth = getArguments().getInt(ARG_MONTH);
      mParamDay = getArguments().getInt(ARG_DAY);
    }
  }

  @Override
  public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    mActivity = (Activity) context;

    try {
      mListener = (DatePickerFragment.DatePickerWithTagListener) mActivity;
    } catch (ClassCastException e) {
      throw new ClassCastException(mActivity.getClass().getName() + " must implement DatePickerWithTagListener");
    }
  }

  @NonNull
  @Override
  public DatePickerDialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(mActivity, R.style.MyAlertDialog, this, mParamYear, mParamMonth, mParamDay);
  }

  /**
   * @param view       the picker associated with the dialog
   * @param year       the selected year
   * @param month      the selected month (0-11 for compatibility with
   *                   {@link Calendar#MONTH})
   * @param dayOfMonth the selected day of the month (1-31, depending on
   */
  @Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    Date date = null;
    Calendar cal = Calendar.getInstance();

    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    date = cal.getTime();

    mListener.onDateSet(this.getTag(), date);
  }
}

Your activity needs to implement DatePickerFragment.DatePickerWithTagListener.
public class SelectFilterActivity extends AppCompatActivity
 implements DatePickerFragment.DatePickerWithTagListener {
  private static final String START_DATE_PICKER = "startDatePicker";
  private static final String END_DATE_PICKER = "endDatePicker";

....

private void setupStartDateClick() {
    binding.startDateTV.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (binding.useDateRange.isChecked()) {
          Calendar cal = Calendar.getInstance();
          cal.setTime(mFilter.getDateRangeStart());
          int year = cal.get(Calendar.YEAR);
          int month = cal.get(Calendar.MONTH);
          int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
          DialogFragment newFragment = DatePickerFragment.newInstance(year, month, dayOfMonth);
          newFragment.show(getSupportFragmentManager(), START_DATE_PICKER);
        }
      }
    });
  }

  private void setupEndDateClick() {
    binding.endDateTV.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (binding.useDateRange.isChecked()) {
          Calendar cal = Calendar.getInstance();
          cal.setTime(mFilter.getDateRangeStart());
          int year = cal.get(Calendar.YEAR);
          int month = cal.get(Calendar.MONTH);
          int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
          DialogFragment newFragment = DatePickerFragment.newInstance(year, month, dayOfMonth);
          newFragment.show(getSupportFragmentManager(), END_DATE_PICKER);
        }
      }
    });
  }

  @Override
  public void onDateSet(String tag, Date date) {
    if (tag.equals(START_DATE_PICKER)) {
      // do whatever you need to with the date returned for the start date picker
    }
    else if (tag.equals(END_DATE_PICKER)) {
      // do whatever you need to with the date returned for the end date picker
    }
  }

Answer: I was not satisfied with any of the aforementioned solutions so I made my own as follows: https://gist.github.com/JoachimR/f82b2b371b1ced4a09918c970e045d4f
import android.app.DatePickerDialog
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import java.util.*

class ChooseDayDialog : DialogFragment() {

    companion object {

        private val KEY_INITIAL_TIMESTAMP = "KEY_INITIAL_TIMESTAMP"
        private val KEY_REQUEST_CODE = "KEY_REQUEST_CODE"

        private val DEFAULT_REQUEST_CODE = 20

        fun createInstance(initialTimestamp: Long,
                           requestCode: Int = DEFAULT_REQUEST_CODE) =
                ChooseDayDialog().apply {
                    arguments = Bundle().apply {
                        putLong(KEY_INITIAL_TIMESTAMP, initialTimestamp)
                        putInt(KEY_REQUEST_CODE, requestCode)
                    }
                }

    }

    interface OnDayChosenListener {

        fun onDayChosen(requestCode: Int, year: Int, month: Int, dayOfMonth: Int)

    }

    private lateinit var listener: OnDayChosenListener

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val activity = activity
        if (activity is OnDayChosenListener) {
            listener = activity
        } else {
            throw IllegalStateException("Activity must implement OnDayChosenListener")
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val timestamp = arguments?.getLong(KEY_INITIAL_TIMESTAMP, -1L) ?: -1L
        if (timestamp == -1L) {
            throw IllegalStateException("no initial time given")
        }
        val requestCode = arguments?.getInt(KEY_REQUEST_CODE, DEFAULT_REQUEST_CODE)
                ?: DEFAULT_REQUEST_CODE

        val calendar = Calendar.getInstance().apply {
            timeInMillis = timestamp
        }
        return DatePickerDialog(activity,
                DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
                    listener.onDayChosen(requestCode, year, month, dayOfMonth)
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH))
    }

}

Answer: I had to implement 2 date pickers for the starting date of a trip and an ending date of it. I used a boolean flag to know which text view to fill with the picked date from the date picker dialog. Below, a visual representation of the code.
public class AddTrip extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {

    private boolean startOrEnd = true;
    private Button startDateBtn;
    private Button endDateBtn;
    private TextView startDateText;
    private TextView endDateText;

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

        initAll();

        startDateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
                startOrEnd = true;
            }
        });

        endDateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
                startOrEnd = false;
            }
        });
    }

    public void initAll(){
        startDateBtn = findViewById(R.id.idstartDateBtn);
        endDateBtn = findViewById(R.id.idendDateBtn);
        startDateText = findViewById(R.id.startDateText);
        endDateText = findViewById(R.id.endDateText);
    }

    private void showDatePickerDialog() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                this,
                Calendar.getInstance().get(Calendar.YEAR),
                Calendar.getInstance().get(Calendar.MONTH),
                Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        String date = "month/day/year: " + month + "/" + dayOfMonth + "/" + year;
        if (startOrEnd) {
            startDateText.setText(date);
        } else {
            endDateText.setText(date);
        }
    }
}

Answer: you can just use the following code
@Override
protected Dialog onCreateDialog(int id) {
    /*
     * final Dialog d = new Dialog(this); d.set
     */

    switch (id) {
    case DATE_DIALOG_ID:
        return new DatePickerDialog(this,
                android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                mDateSetListener, cmYear, cmMonth, cmDay);

    }
    return null;
}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        cmYear = year;
        cmMonth = monthOfYear;
        cmDay = dayOfMonth;
        updateDisplay();
    }
};

private void updateDisplay() {

    String date_check = ""
            + new StringBuilder()
                    // Month is 0 based so add 1
                    .append(cmYear).append("-").append(cmMonth + 1)
                    .append("-").append(cmDay).append(" ");
}

you can call on Dialog in any onclick
showDialog(DATE_DIALOG_ID);

where DATE_DIALOG_ID is declared as
static final int DATE_DIALOG_ID = 0;

I hope this is useful.
Answer:     issue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Bundle bundle = new Bundle();
            bundle.putInt("DATE", 1);

            DialogFragment newFragment = new MyDatePickerFragment();
            newFragment.setArguments(bundle);
            newFragment.show(getSupportFragmentManager(), "datePicker");
        }
    });

    expiry.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Bundle bundle = new Bundle();
            bundle.putInt("DATE", 2);

            DialogFragment newFragment = new MyDatePickerFragment();
            newFragment.setArguments(bundle);
            newFragment.show(getSupportFragmentManager(), "datePicker");

        }
    });

}

@Override
public void sendInput(String input, int id) {
    date = input;
    switch (id) {
        case 1:
            issue.setText(date);
            break;
        case 2:
            expiry.setText(date);
            break;
    }

public class MyDatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    static final int ISSUE_DATE = 1;
    static final int EXPIRY_DATE = 2;

    private int mChosenDate;

    int cur = 0;

    @Override
    public void onDateSet(DatePicker datePicker, int year, int month, int day) {

        String date;
        if (cur == ISSUE_DATE) {
            // set selected date into textview

            Log.v("Date Issue", "Date1 : " + new StringBuilder().append(month + 1)
                    .append("-").append(day).append("-").append(year)
                    .append(" "));
            date = day + "/0" + (month + 1) + "/" + year;
        } else {
            Log.v("Date expiry", "Date2 : " + new StringBuilder().append(month + 1)
                    .append("-").append(day).append("-").append(year)
                    .append(" "));
            date = day + "/0" + (month + 1) + "/" + year;

        }
        listenerforActivity.sendInput(date, cur);
    }

    public interface OnDateSetListenerInterface {
        void sendInput(String input, int id);
    }

    public OnDateSetListenerInterface listenerforActivity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            listenerforActivity = (OnDateSetListenerInterface) getActivity();
        } catch (ClassCastException e) {
            Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        Bundle bundle = this.getArguments();
        if (bundle != null) {
            mChosenDate = bundle.getInt("DATE", 1);
        }

        switch (mChosenDate) {

            case ISSUE_DATE:
                cur = ISSUE_DATE;
                return new DatePickerDialog(getActivity(), this, year, month, day);

            case EXPIRY_DATE:
                cur = EXPIRY_DATE;
                return new DatePickerDialog(getActivity(), this, year, month, day);

        }
        return null;
    }

}

Answer: My solution for this was simply using a switch
public class RegisterActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
private TextView mDisplayBirthDay;
private TextView mDisplayExpDate;
private TextView mDisplayIssueDate;
private int sw;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false); // to get rid of the title of the activity
    Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

    mDisplayBirthDay = findViewById(R.id.birthDate);
    findViewById(R.id.birthDate).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDatePickerDialog();
            sw = 0;
        }
    });
    mDisplayExpDate = findViewById(R.id.editText_expire);
    findViewById(R.id.editText_expire).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDatePickerDialog();
            sw = 1;
        }
    });
    mDisplayIssueDate = findViewById(R.id.editText_issueDate);
    findViewById(R.id.editText_issueDate).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDatePickerDialog();
            sw = 2;
        }
    });
}
private  void showDatePickerDialog(){
    DatePickerDialog datePickerDialog = new DatePickerDialog(this,
            this,
            Calendar.getInstance().get(Calendar.YEAR),
            Calendar.getInstance().get(Calendar.MONTH),
            Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
    datePickerDialog.show();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.show_registrations:
            getSupportFragmentManager().beginTransaction().replace(R.id.event_description,
                    //TODO: pass eventID as intend when clicked on event
                    EventRegistration.newInstance(69)).commit();
            break;
        case R.id.visibility_event:

            break;
        case android.R.id.home:
            onBackPressed(); //handling the "back" button
            break;
        default:
    }
    return true;
}

@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    month = month + 1;  //because January is the month 0
    String date = dayOfMonth + "/" + month + "/" + year;
    switch (sw){
        case 0:
            mDisplayBirthDay.setText(date);
            break;
        case 1:
            mDisplayExpDate.setText(date);
            break;
        case 2:
            mDisplayIssueDate.setText(date);
            break;
        default:
    }

}

}
Answer: I solved this problem by passing a flag id to the DialogFragment and then onDateSet make use of the flag to set the textview data accordingly
Here is the code portion for Dialog Fragment:
public class twodatepickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
private int first ;

public twodatepickerFragment(int i) {
    first=i;
}

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    int date=c.get( Calendar.DAY_OF_MONTH);
    int month= c.get( Calendar.MONTH);
    int year=c.get ( Calendar.YEAR );
    return new DatePickerDialog(getActivity(),(DatePickerDialog.OnDateSetListener) getActivity (), year, month, date);
    return new DatePickerDialog(getActivity(),this, year, month, date);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

    Date date = calendar.getTime();
    TextView textView = findViewById(R.id.date_selected);
    textView.setText(new SimpleDateFormat("dd-MMMM-yyyy").format(date));
    if(first==0){
        TextView tv= getActivity().findViewById(R.id.date_selected);
        tv.setText(new SimpleDateFormat("dd-MMMM-yyyy").format(date));
    }else{
        TextView tv= getActivity().findViewById(R.id.date_selected_2);
        tv.setText(new SimpleDateFormat("dd-MMMM-yyyy").format(date));
    }
}

}
Here is the code for MainActivity, here select_date_1 and select_date_2 are button.
 select_date_2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DialogFragment datepicker = new twodatepickerFragment (1);
            datepicker.show ( getSupportFragmentManager (),"date picker" );
        }
    });
    select_date_1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DialogFragment datepicker = new twodatepickerFragment (0);
            datepicker.show ( getSupportFragmentManager (),"date picker" );
        }
    });

Answer: You can simply use a boolean flag variable to determine the view you are making the call from.

Multiple DatePickers in same activity


The definition of the sample standard deviation

Question: I am reviewing the statistic.
I read the book "Probability and Statistical Inference"
which is written by Robert V. Hogg and Ellit A. Tanis.

There is a statement in the book says that:
(Section: The Mean, Variance, and Standard Deviation)
The sample standard deviation,
$$ s = \sqrt{\frac{1}{n-1}\sum_{i=1}^{n}(x_i-\bar{x})^2}\geq 0,$$
is a measure of how dispersed the data are from the sample mean.
At this stage of your study of statistics,
it is difficult to get a good understanding or meaning of the standard deviation $s$,
but you can roughly think of it as the average distance of the values $x_1, x_2, \ldots, x_n$
from the mean $\bar{x}$.
This is not true exactly,
for, in general,
$$ s > \frac{1}{n} \sum_{i=1}^{n} |x_i-\bar{x}|, $$
but it is fair to say that $s$ is somewhat larger,
yet of the same magnitude,
as the average of the distances of $x_1, x_2, ..., x_n$ from $\bar{x}$.

Question 1:
What book could provide a "good understanding or meaning" of the standard deviation for me.
Question 2:
Why don't we define the sample standard deviation as the
average distance of the values $x_1, x_2, \ldots, x_n$
from the mean $\bar{x}$,
that is,
$$ s:=\frac{1}{n} \sum_{i=1}^{n} |x_i-\bar{x}|. $$
Comment: Question 2 has probably appeared here a few times before.
Comment: The sum of squares is more amenable to calculations and is differentiable.
Answer: Question 2 is answered in this Wikipedia article about Bessel's correction.
The meaning of the standard deviation is largely the same as the meaning of the mean absolute deviation:

Both are translation invariant, i.e. if you add the same number to every data point, you don't change the measure of dispersion, whether it is the standard deviation or the mean absolute deviation; and
Both are equivariant under multiplication by non-negative numbers, i.e. if you multiply every data point by the same non-negative number, then you multiply the measure of dispersion by that.  (And if the number you multiply by may be negative, then the measure of dispersion is multiplied by the absolute value of that number.)

However, the standard deviation enjoys one great advantage over the mean absolute deviation: the variance (the square of the standard deviation) of the sum of independent random variables is the sum of their variances.  For example, suppose you toss a coin $1800$ times.  What is the variance of the probability distribution of the number of heads?  You can find it easily, whereas you can't do the same with the mean absolute deviation. That makes it possible to find the probability that the number of heads is between 895 and 912, by using the central limit theorem.
A subtler advantage is also enjoyed by the standard deviation.  Suppose the population standard deviation is $\sigma$, and you can't observe that but must estimate it based on a sample.  You can multiply the sample standard deviation by a particular constant (I don't remember its value off hand) to get an unbiased estimate of $\sigma$, and you can do the same with the mean absolute deviation and a different constant to do the same.  Which one is more accurate, in the sense of having a smaller mean square error?  It is the sample standard deviation if the population is normally distributed.  However, one way in which this advantage is subtler is that it may be lost of there is a slight deviation from normality.  I seem to recall that with a mixture of normal distributions with different variances, with mixing weights $0.99$ and $0.01$, that advantage may be lost.


Prove $\lim\limits_{x \to +\infty}\int_0^{\pi} xe^{-x\sin t}{\rm d}t=2$.

Question: Someone gives a proof as follows:

Above all, notice that \begin{align*} I(x):&=\int_0^{\pi} x{\rm  e}^{-x\sin t}{\rm d}t=\int_0^{\frac{\pi}{2}} x{\rm e}^{-x\sin t}{\rm  d}t+\overbrace{\int_{\frac{\pi}{2}}^{\pi} x{\rm e}^{-x\sin t}{\rm  d}t}^{t~ \mapsto ~t+\frac{\pi}{2}}\\ &=\int_0^{\frac{\pi}{2}} x{\rm  e}^{-x\sin t}{\rm d}t+\int_0^{\frac{\pi}{2}} x{\rm e}^{-x\sin  \left(t+\frac{\pi}{2}\right)}{\rm d}t\\ &=\int_0^{\frac{\pi}{2}} x{\rm e}^{-x\sin t}{\rm d}t+\int_0^{\frac{\pi}{2}} x{\rm e}^{-x\cos t}{\rm  d}t\\ &=\int_0^{\frac{\pi}{2}} x{\rm e}^{-x\sin t}{\rm  d}t+\int_0^{\frac{\pi}{2}} x{\rm e}^{-x\cos\left(\frac{\pi}{2}-  t\right)}{\rm d}t\\ &=\int_0^{\frac{\pi}{2}} x{\rm e}^{-x\sin t}{\rm
d}t+\int_0^{\frac{\pi}{2}} x{\rm e}^{-x\sin t}{\rm d}t\\
&=2\int_0^{\frac{\pi}{2}} x{\rm e}^{-x\sin t}{\rm d}t. \end{align*}
  Consider making a substitution that $\theta:=tx.$ Then $x=\theta/t,
 {\rm d}\theta=x{\rm d}t.$ Thus $$I(x):=2\int_0^{\frac{\pi x}{2}}
 \exp\left(-x\sin\frac{\theta}{x}\right){\rm d}\theta.$$ Since
   $\theta/x \in[0,\pi/2],$ and $f(x):=\dfrac{\sin x}{x}$ decreases over
   $(0,\pi/2]$, hence $ \sin \dfrac{\theta}{x}\ge \dfrac{2\theta}{\pi x}.$
  Therefore $ -x\sin \dfrac{\theta}{x}\le -\dfrac{2\theta}{\pi },$ and
   further we obtain $$\left|
\exp\left(-x\sin\frac{\theta}{x}\right)\right|=
 \exp\left(-x\sin\frac{\theta}{x}\right)\le \rm
 e^{-\frac{2\theta}{\pi}},$$ the right hand side of which is integrable
   over $ [0,+\infty) .$ Moreover $$\lim_{x \to
 +\infty}\exp\left(-x\sin\frac{\theta}{x}\right)=\exp\lim_{x \to +\infty}\left(\frac{\sin \frac{\theta}{x}}{\frac{\theta}{x}}\cdot -\theta\right)=e^{-\theta}.$$ Now, we can exchange the orders of the limit and the integral by Lebesgue dominated convergence theorem and
   obtain $$\lim_{x \to +\infty}I(x)=2\int_0^{+\infty}{\rm
 e}^{-\theta}{\rm d}\theta=2.$$

Is this correct? I don't know Lebesgue dominated convergence theorem well. Is there another proof more elementary?
Comment: Looks ok to me.
Comment: It is better to rewirte $I(x)$ as $$I(x):=2\int_0^\infty
 \exp\left(-x\sin\frac{\theta}{x}\right){\rm \chi_{\frac{\pi x}{2}}}(\theta)d\theta.$$
Answer:
The proof in the OP is a standard way forward when equiped with the Dominated Convergence Theorem.  Herein, we present a way forward that relies on elementary calculus only and uses integration by parts.  To that end, we now proceed.

Let $I(x)$ be given by the integral
$$\begin{align}
I(x)&=\int_0^\pi xe^{-x\sin(t)}\,dt\\\\
&=2\int_0^{\pi/2} xe^{-x\sin(t)}\,dt\\\\
&=2\int_0^1 xe^{-x\sin(t)}\,dt+2\int_1^{\pi/2} xe^{-x\sin(t)}\,dt\tag1
\end{align}$$

As $x\to \infty$, it is evident that the second integral on the right-hand side of $(1)$ approaches $0$ (since $\lim_{x\to\infty}xe^{-x\sin(1)}=0$).

For the first integral, we integrate by parts with $u=\sec(t)$ and $v=-\frac1x e^{-x\sin(t)}\cos(t)$.  Proceeding we find that
$$\begin{align}
2\int_0^1 xe^{-x\sin(t)}\,dt&=2\left.\left(- \sec(t)e^{-x\sin(t)}\right)\right|_0^1+2\int_0^1 \sec(t)\tan(t)e^{-x\sin(t)}\,dt\\\\
&=2-2\sec(1)e^{-x\sin(1)}+2\int_0^1 \sec(t)\tan(t)e^{-x\sin(t)}\,dt\tag2
\end{align}$$
Letting $x\to\infty$ in $(2)$ yields the coveted limit
$$\lim_{x\to\infty}\int_0^\pi xe^{-x\sin(t)}\,dt=2$$
as was to be shown!
Comment: It does not approach $0$ since at $t=0$, $\sin(t)=0$, and hence $e^{-x\sin(0)}=1$.  All of the "action" of this limit comes from integration near $t=0$.
Comment: Seeing $$2\int_0^1 xe^{-x\sin(t)}\,dt+2\int_1^{\pi/2} xe^{-x\sin(t)},$$  why the first does not tend to $0$? It's the same $\lim\limits_{x\to\infty}xe^{-x\sin(1)}=0$.
Comment: +1 for the elementary approach (a regular feature in your answers).
Comment: @paramanandsingh Thank you.  Not all my answers are bases on elementary analysis
Comment: +1 does appear in my browser (will try to upvote again in case there is a problem) . And yes you also do a lot of complex analysis (my weak spot) but I tend to like these elementary ones
Comment: @ParamanandSingh I see the up vote now.  And thank you again my friend!  I hope that you're staying safe and healthy.
Comment: I am fine but to be frank in these difficult times MSE is the only source of enjoyment and hope left. Apart from this all online activity is mostly around Corona. Take care!
Comment: Pleased to hear that you're fine; sad to hear that MSE is your only source of hope. Take care too!
Comment: +1 from me. I can't help to enjoy the beauty of an elementary calculus problem!
Comment: @taylorrendon Thank you.  Much appreciated.
Answer: Let $ x>1 $ :
First of all, as you've shown : \begin{aligned}\int_{0}^{\pi}{x\,\mathrm{e}^{-x\sin{t}}\,\mathrm{d}t}=\int_{0}^{\frac{\pi}{2}}{x\,\mathrm{e}^{-x\sin{t}}\,\mathrm{d}t}+\int_{\frac{\pi}{2}}^{\pi}{x\,\mathrm{e}^{-x\sin{t}}\,\mathrm{d}t}\end{aligned}
Substituting $ t=\pi-y $ in the second term, we get : \begin{aligned}\int_{0}^{\pi}{x\,\mathrm{e}^{-x\sin{t}}\,\mathrm{d}t}=2\int_{0}^{\frac{\pi}{2}}{x\,\mathrm{e}^{-x\sin{t}}\,\mathrm{d}t}\end{aligned}
Now substituting $ \small\left\lbrace\begin{aligned}y&=x\sin{t}\\ \mathrm{d}t&=\frac{\mathrm{d}y}{\sqrt{1-\frac{y^{2}}{x^{2}}}}\end{aligned}\right. $, we get : \begin{aligned}\int_{0}^{\pi}{x\,\mathrm{e}^{-x\sin{t}}\,\mathrm{d}t}=2\int_{0}^{x}{\frac{\mathrm{e}^{-y}}{\sqrt{1-\frac{y^{2}}{x^{2}}}}\,\mathrm{d}y}\end{aligned}
We have : \begin{aligned}\left|\int_{0}^{+\infty}{\mathrm{e}^{-y}\,\mathrm{d}y}-\int_{0}^{x}{\frac{\mathrm{e}^{-y}}{\sqrt{1-\frac{y^{2}}{x^{2}}}}\,\mathrm{d}y}\right|&=\left|\int_{x}^{+\infty}{\mathrm{e}^{-y}\,\mathrm{d}y}-\int_{0}^{x}{\mathrm{e}^{-y}\left(1-\frac{1}{\sqrt{1-\frac{y^{2}}{x^{2}}}}\right)\mathrm{d}y}\right|\\ &=\left|\int_{x}^{+\infty}{\mathrm{e}^{-y}\,\mathrm{d}y}-\frac{1}{x^{2}}\int_{0}^{x}{\frac{y^{2}\,\mathrm{e}^{-y}}{\sqrt{1-\frac{y^{2}}{x^{2}}}\left(1+\sqrt{1-\frac{y^{2}}{x^{2}}}\right)}\,\mathrm{d}y}\right|\\ &\leq\int_{x}^{+\infty}{\mathrm{e}^{-y}\,\mathrm{d}y}+\frac{1}{x^{2}}\int_{0}^{x}{\frac{y^{2}\,\mathrm{e}^{-y}}{\sqrt{1-\frac{y^{2}}{x^{2}}}\left(1+\sqrt{1-\frac{y^{2}}{x^{2}}}\right)}\,\mathrm{d}y}\\ &\leq\int_{x}^{+\infty}{\mathrm{e}^{-y}\,\mathrm{d}y}+\frac{1}{x^{2}}\int_{0}^{x}{\frac{y^{2}\,\mathrm{e}^{-y}}{\sqrt{1-\frac{y^{2}}{x^{2}}}}\,\mathrm{d}y}\\ &\leq\int_{x}^{+\infty}{\mathrm{e}^{-y}\,\mathrm{d}y}+\frac{1}{x^{2}}\int_{0}^{x}{\frac{y^{2}}{\left(1+\frac{y^{2}}{2}\right)\sqrt{1-\frac{y^{2}}{x^{2}}}}\,\mathrm{d}y}\end{aligned}
(We used the fact that $ \mathrm{e}^{y}\geq 1+y+\frac{y^{2}}{2}\geq 1+\frac{y^{2}}{2} $ then we took its inverse)
Now since the integral we got can be computed, $ \int_{0}^{x}{\frac{y^{2}}{\left(1+\frac{y^{2}}{2}\right)\sqrt{1-\frac{y^{2}}{x^{2}}}}\,\mathrm{d}y}=\pi x\left(1-\frac{1}{\sqrt{1+\frac{x^{2}}{2}}}\right) $, we get that : $$ \left|\int_{0}^{+\infty}{\mathrm{e}^{-y}\,\mathrm{d}y}-\int_{0}^{x}{\frac{\mathrm{e}^{-y}}{\sqrt{1-\frac{y^{2}}{x^{2}}}}\,\mathrm{d}y}\right|\leq\int_{x}^{+\infty}{\mathrm{e}^{-y}\,\mathrm{d}y}+\frac{\pi}{x}\left(1-\frac{1}{\sqrt{1+\frac{x^{2}}{2}}}\right)\underset{x\to +\infty}{\longrightarrow}0 $$
Which means $$ \int_{0}^{x}{\frac{\mathrm{e}^{-y}}{\sqrt{1-\frac{y^{2}}{x^{2}}}}\,\mathrm{d}y}\underset{x\to +\infty}{\longrightarrow}\int_{0}^{+\infty}{\mathrm{e}^{-y}\,\mathrm{d}y}=1 $$
Hence $$ \int_{0}^{\pi}{x\,\mathrm{e}^{-x\sin{t}}\,\mathrm{d}t}\underset{x\to +\infty}{\longrightarrow}2 $$
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\lim_{x \to \infty}\int_{0}^{\pi}x\expo{-x\sin\pars{t}}\dd t & =
\lim_{x \to \infty}\int_{-\pi/2}^{\pi/2}x\expo{-x\cos\pars{t}}\dd t =
2\lim_{x \to \infty}\int_{0}^{\pi/2}x\expo{-x\cos\pars{t}}\dd t
\\[5mm] & =
2\lim_{x \to \infty}\int_{0}^{\pi/2}x\expo{-x\sin\pars{t}}\dd t =
2\lim_{x \to \infty}\int_{0}^{\infty}x\expo{-xt}\dd t
\label{1}\tag{1}
\\[5mm] & =
2\lim_{x \to \infty}\int_{0}^{\infty}\expo{-t}\dd t = \bbx{\large 2}
\end{align}
In line (\ref{1}), I used the
Laplace Method.


Excel stopped refreshing Olap cubes

Question: since yesterday I have a problem with OLAP Cubes.
They do process successfull and I can browse them in SSMS without any problem but normal users can't refresh the data via Excel.
Me as Admin I can refresh all excels without any problem and my collegue with the same privileges was able to do it only with 1 of 5 excels.
Any help here? After restarting of our server some people were able to refresh it yesterday but today this trick didnt work for us.
<code>Provider=MSOLAP.8;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=My_Cube;Data Source=My_Server;MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error;Update Isolation Level=2
</code>
Answer: The problem was new Excel update v2109. After downgrade to v2108 it's ok.

Excel stopped refreshing Olap cubes


Marginalizing probability

Question: Notes for my intro to probability class give a theorem which states the following:
P(A) = P(A ^ B) + P(A ^ ~B)

What would the proof for this look like given the basic probability axioms?
Here's a list of axioms I start off with:
0 <= P(A) <= 1
P(True) = 1
P(False) = 0
P(A v B) = P(A) + P(B) - P(A ^ B)
P(A) = 1 - P(~A)

Answer: From the set-theoretic equations
$$\eqalign {
A &= A \cap 1 \\
       &=A \cap (B \cup \sim B) \\
       &=(A \cap B) \cup (A \cap \sim B) \\
}$$
and
$$\eqalign {
(A \cap B) \cap(A \cap \sim B) &= (A \cap A) \cap (B \cap \sim B) = A \cap \varnothing = \varnothing
}$$
we apply the penultimate axiom to obtain
$$\eqalign {
\Pr(A) &= \Pr((A \cap B)\cup (A \cap \sim B)) \\
       &= \Pr(A \cap B) + \Pr(A \cap \sim B) - \Pr((A \cap B) \cap(A \cap \sim B)) \\
       &= \Pr(A \cap B) + \Pr(A \cap \sim B) - \Pr(\varnothing)
}$$
and then, observing $\Pr(\varnothing)=0$ by the third axiom, we are done.
This nicely illustrates the fact that most probability statements are really about sets (events).  That's why Venn diagrams can be so helpful in reasoning about probabilities.
Answer: First prove that $A=(A\cap B)\cup(A\cap B^c)$.
You may just draw a Venn diagram or do it formally, which means that you have to prove that $A\subset (A\cap B)\cup(A\cap B^c)$ and $(A\cap B)\cup(A\cap B^c)\subset A$.

For example, to prove the first inclusion you have to suppose that $\omega\in A$ and conclude that $\omega\in (A\cap B)\cup(A\cap B^c)$.
Now observe that $(A\cap B)\cap(A\cap B^c)=\emptyset$.
Here you may use the same Venn diagram as before or just reason that any $\omega$ in this intersection would be an element of both $B$ and $B^c$, which is not possible (a contradiction).
Finally, use the fact that the probability of the union of two disjoint events is the sum of their probabilities.
Comment: "Finally, use the fact that the probability of the union of two disjoint events is the sum of their probabilities."  This is not one of the "axioms" that the OP is given but needs to be deduced from the two that say `P(False) = 0;
P(A v B) = P(A) + P(B) - P(A ^ B)`  In other words, there is more work to be done for the proof "using axioms and substitutions" that the OP wants.
Comment: I understand the concept behind it, and I understand the proof with the Venn diagram, but is there a way to prove this using axioms and substitution?
Comment: What axioms are you beginning with?  (There is more than one set!)
Comment: Sorry, I'm new to this stuff! I'll edit the question with the axioms I'm given :)

Marginalizing probability