Biased variation of $\chi^2$ statistic?

Question: I've found a variation of the $\chi^2$ statistic that looks like this:
$\chi^2 = \sum\limits_{i=1}^N\,\chi_i^2 = \sum\limits_{i=1}^N\,\frac{(\log m_{i}- \log n_{i})^2}{\sigma_{i}^2}$
where $\sigma_{i}^2=1/n_i$, $m_i$ is the modeled number of counts in bin $i$ and $n_i$ is the observed number (both are of course positive and integers) $log$ is the decimal logarithm.
If $m_i=0$ or $n_i=0$, the author assigns a very small value to avoid inconsistencies evaluating the $log$ function at $0$.
I understand that this parameter is biased in the sense that it will give more weight to $\chi_i$ factors where $n_i\neq0$; ie: it will pretty much disregard $\chi_i$ factors where $n_i=0$ (which will be replaced by a very small number, say $0.0001$) thus allowing the model to assign almost any number $m_i$ to that bin.
See here for an example of $\chi_i$ when $n_i=0$ (replaced by $0.0001$) and here to see the behavior of $\chi_i$ when $n_i=1$.
Clearly for what I see in the case where $n_i=1$ the values of $\chi_i$ are much bigger than those obtained by the same parameter when $n_i=0$ (replaced by $0.0001$)
I see this as a prove that the statistic is biased. Am I correct here?
Comment: I think there is a confusion of concepts about "bias" here.  Bias is a quality of a statistic, which is an estimate of a parameter.  You can only talk about a statistic being biased if it is an attempt to estimate a parameter and can be shown to on average get it wrong.  I don't see what parameter your statistic is trying to estimate.
Comment: I'm trying to estimate the best fit of several models to a given observation. Different models will have different $\chi^2$ values, where the minimum value is the best fit. Maybe "biased" is the wrong word, I mean this statistic will give more weight to a certain part of a histogram than to another (even though this 'unevenness' will be the same for all models)
Comment: I edited the question to correct what I think is a discrepancy between what you had written and what shows in the paper to which you link. Feel free to roll back if I got that wrong.
Answer: Although the authors use the $\chi^2$ symbol for that formula, it's not the  $\chi^2$ statistic used, say, for evaluating hypotheses about contingency tables. The authors minimized $\chi^2$ from that formula to optimize model fits and to compare optimized fits among models, rather than to evaluate against a null hypothesis.
They chose to work in a log scale for counts because: "In linear scale, the regions with maximum density would dominate the $\chi^2$ value resulting in an unsatisfactory overall fit."
The effect of $\sigma_i^2=1/n_i$ in the denominators is effectively to weight each term by the number of observed counts in bin $i$, $n_i$,
$$\chi^2 = \sum\limits_{i=1}^N\,\chi_i^2 = \sum\limits_{i=1}^N\,\frac{(\log m_{i}- \log n_{i})^2}{\sigma_{i}^2} = \sum\limits_{i=1}^N\,n_i(\log m_{i}- \log n_{i})^2,$$
for 0 weight on a term when $n_i=0$. That might completely avoid the problem of taking the log of $n_i=0$ for such a term, although I can't be sure that's how the authors proceeded in practice. The modeled counts $m_i$ aren't necessarily integers (even in standard $\chi^2$ statistics), and I suspect that they never were exactly 0.
If there were nevertheless issues with taking the log of 0, that is often faced in practice and discussed on this site. See this page and its links for places to start. For an optimization weighted toward bins with large numbers of observed counts, like in this paper, the choice of what to add before taking the log probably didn't matter much.
Comment: @Gabriel I think that Kjetil Halvorsen is the one who revived this question, by asking you (in a recent but now-deleted comment) to provide the citation that you added yesterday. Glad that I could help with an answer once I saw it revived.
Comment: I'd forgotten about this question, thank you Ed!

Biased variation of $\chi^2$ statistic?


How to implement the Mac-style Windowshade feature for Windows

Question: I always liked the WindowsShade utility on the Mac. Is there some sample code on how to do the same thing in VB.Net or C#.Net for Windows.
I have implemented it myself for a single app, but I would like to have it work for any window..
Answer: To do it for any window would require hooking into the message processing for the entire system which is tricky business: http://www.codeproject.com/KB/cs/netwin32hooks.aspx
But you don't need to write this yourself, unless you really want to. It's already been written, check it out: http://www.palma.com.au/winroll/
Comment: But is there any open source solution in C#? I happen to be looking for the same thing.


Bijective functions between involutions and subset of natural numbers

Question: I have a problem with permutations (involutions): If I have the set
$$S=\{1,2,\dots,26\}$$
how can I find a function $f$ that assigns any $n$ from a subset of the natural numbers (lets call it $N$) a unique involution $\sigma$ of $S$?
Also how can I find a function $g$ that does the inverse, so that $f(g(\sigma))=\sigma$ and $g(f(n))=n$?
Im searching for a method that allows me to compute the involution from $n\in N$ as well as compute $n$ from the involution.
Comment: if you want a bijection between a subset $N\subset\Bbb N$ and the involutions of $26$ symbols, you are counting them.
Comment: I don't think it's possible to construct such functions in the standard mathematical context. I think your only option is to explicitly find all the involutions and say "Ok, this is involution 1, this is involution 2" and so on.
Comment: Permutations or involutions? An involution has to give the identity when applied twice, a general permutation doesn't.
Comment: the next permutation is an involution $\sigma=(1,2)(3,4)(6,7)$ : )... i think that the question is: how many involutions exists in $26$ symbols?
Comment: @Chappers: I mean involution
Comment: @janmarqz: No im not searching the total number of involutions. Im searching a way to assign (calculate) a number to any involution and the other way round. Eg. 0 -> (1,1)(2,2)(3,3)...(id), 1 -> (1,2)(2,1)(3,3)...(1 and 2 swapped) and so forth
Comment: do you know that $(1,2)(2,1)=id$ ?
Comment: @janmarqz Ok maybe I wasnt proper saying what I want, sorry english is not my mothers tongue :) I dont want to count them, Im searching for two functions f and g. f takes a number and returns a involution of S. g takes a involution of S and returns a number. g(f(n))=n.
Comment: ok, meanwhile you rearrange your question, check this http://mathworld.wolfram.com/PermutationInvolution.html
Comment: @OriaGruber thats unfortunate. Anyways thanks for the quick answer :)
Comment: Well, I can give you a bijection, although the set onto which it maps is rather unpleasant to describe...
Comment: @Chappers :) Well I rather thought of a nice compact function...
Comment: @janmarqz I fixed my question, i hope its clear now what I'm searching. Hope for a helpful answer :)
Comment: do you know already how many permutation-involutions over $\{1,2,...,26\}$ are there?
Comment: automatic calculation with the recurrence $a(n+1)=a(n)+na(n-1)$ (from http://oeis.org/A000085) and with $a(0)=1$ and $a(1)=1$ going to give you the total of  $a(26)=532,985,208,200,576$
Comment: @janmarqz yes, thats correct. Thats why I tried to find a solution for smaller sets, but I cant find a pattern that could make up for an algorithm :/
Answer: I'm going to take permutations of $S'=\{0,1,\dotsc,25\}$ because it's easier on the notation. Let the set of involutions on this set be $J$.
Take the integers in base $26$. Let $\sigma$ be an involution on your set. Define an integer in the following fashion: take
$$ g(\sigma)=\sum_{n=0}^{25} \sigma(n) 26^n $$
This gives you a 26-digit number in base $26$, which uniquely corresponds to the permutation $\sigma$, because different permutations have $\sigma(n)$ different for some $n$, and hence one of the digits in their images under $g$ is different. It's also clear how to extract a permutation from this representation: $\sigma(n)$ is the coefficient of $26^n$.
Okay, that's the easy bit. What is the set we're mapping to? Well, it's the subset of $\{0,1,2,\dotsc,26^{26}-1\}$ where all the digits are different in base $26$, and the $n$th digit is $m$ if and only if the $m$th digit is $n$ (i.e. if we have $n 26^m$ in the above expansion, we also have $m 26^n$) (It's easy to see why since we need $\sigma^2=\text{id.}$ Yeah, it's not a very nice set to describe.
Comment: Thanks! I will think about that tomorrow, good night :)


Generate a column of type 'double' in migration - Ruby on rails

Question: I need to create a column of type double in my database, I understand that in ruby there is no double type and that to simulate this type of value I have to use :scale and :precision
How can i solve this?
Comment: What database are you using?
Comment: I am working with mysql
Comment: Doesn't `t.decimal :column_name, precision: 4, scale: 3` work for you?
Answer: You can specify the precision and scale in your migration.
class AddCostToBookings < ActiveRecord::Migration
  def change
    add_column :bookings, :cost, :decimal, precision: 10, scale: 2
  end
end

Precision defines the precision for the decimal fields, representing
  the total number of digits in the number.
Scale defines the scale for the decimal fields, representing the number of digits after the decimal point.


Como verificar se após selecionado um arquivo o mesmo ainda existe no diretório em JavaScript

Question: Na minha aplicação utilizo como framework de javascript o angularJS, e para fazer a seleção dos arquivos utilizo o seguinte button:
 <md-button class="md-accent md-raised button-arquivo-margin"
                   ng-disabled="vm.controladorRequisicao.requisicaoSolicitada"
                   aria-label="Arquivo(s)">

                <input class="input-selecao"
                       im-file-change="vm.metodos.selecionarArquivos($event, arquivos)"
                       type="file"
                       multiple />

                Arquivo(s)

 </md-button>

onde im-file-change="vm.metodos.selecionarArquivos($event, arquivos)" é somente uma diretiva que obtém os arquivos do event do input e realiza o bind com meu model.
Após seleciona os arquivos os mesmo são exibidos em uma tabela conforme demonstrado abaixo:

Porém estou tendo um problema de má usabilidade do sistema, no qual as pessoas estão movendo ou excluindo os arquivos antes de fazer o envio para API, assim fazendo com que ao tentar fazer o envio dos arquivos ocasione um problema ...
E fiz as verificações a requisição não chega a ser completada então somente um undefined da requisição ...
Gostaria de saber se é possível de alguma forma consistir se os arquivos existem na pasta. Pois assim antes de realizar o envio eu verificaria se os arquivos existem na pasta e caso não exista poderia informar ao usuário que os arquivos foram movidos ou excluídos da pasta corrente.
Answer: Conseguir resolver meu problema da seguinte forma.
Quando os arquivos são movidos ou excluídos da pasta onde os mesmo foram selecionados, no event.target.files do input de seleção e bind do model com o angularJS, o size dos arquivos selecionados fica zerado, conforme pode se observar na imagem abaixo:

Sendo assim criei um método simples que sempre irá consistir o tamanho dos arquivos antes do envio dos mesmo:
function _consistirArquivos(arquivos) {
        var verificadorArquivosIncosistentes = false;
        for (let i = 0; i < arquivos.length; i++) {
            var arquivo = arquivos[i];
            if (arquivo.size == 0) {
               verificadorArquivosIncosistentes  = true;
               break;
            }
        }
        return verificadorArquivosIncosistentes
};


apache config for auto domain directory

Question: I edit /etc/hosts file to add domains. I add new virtual host for new domain.
So I can easily develop.
What I want now is to have apache conf to

if there is a virtualhost domain definition follow
if not, look for /var/www directory, if there is dir follow
if there is not, redirect to /var/www/nerkn

Can apache conf make it?
1)Example domain example.com

there is no example.com in virtualhost
there is a directory named /var/www/example.com so server there

2)Exampple domain ex2.com

there is no ex2.com in virtualhost
there is no directory named /var/www/ex2.com
serve from /var/www/nerkn
Answer: Mod_vhost_alias, where nerkn defined as default virthost
VirtualDocumentRoot d:/Sites/%0/web
VirtualScriptAlias d:/Sites/%0/cgi-bin

define base location of bare minimum (my config)
while adding <VirtualHost dcweb.e-city.net.ru:80> allow redegine-add vhost-specific details
Comment: wonderful **ln -s nerkn new-site**
Comment: it only solves 2nd bu its ok. Thank you
Comment: it **work most times** for me in 1st mode - I just copy skeleton to the new site-location and have site ready without restart of apache

apache config for auto domain directory


Scrape text after every  - BeautifulSoup

Question: I want to scrape this URL
http://deals.whotels.com/W-Guangzhou-3126/tnc/1680/24900/en
I have to get each and every Terms & Conditions
I have got the HTML markup in test
test = terms_and_conditions_soup.select(".popBodyText")[0]
for tes in test.findAll('br'):
    print(tes.extract())

But this only prints
s.
I can get all the terms like terms_and_conditions_soup.select(".popBodyText p")[0].text but I don't want like that.
Even I see no logic to scrape those Terms.
Answer: The terms and conditions are simply lines of text delimited by
 breaks. You can get all the text with newlines in between with the .get_text() method:
terms_elements = terms_and_conditions_soup.select(".popBodyText")[0]
terms = terms_elements.get_text('\n', strip=True)

or you could loop over the .strings or .stripped_strings generators:
terms = list(terms_elements.stripped_strings)

If you only wanted the bulleted lines, select for those:
terms = [t.lstrip('\u2022 ') for t in terms_elements.stripped_strings
         if t.startswith('\u2022')]

I removed the bullet from the selected lines too.
Demo of the latter approach:
>>> import requests
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(requests.get('http://deals.whotels.com/W-Guangzhou-3126/tnc/1680/24900/en').content)
>>> terms_elements = soup.find(class_='popBodyText')
>>> [t.lstrip('\u2022 ') for t in terms_elements.stripped_strings if t.startswith('\u2022')]
['Offer valid at W Guangzhou only.', 'Offer is valid for stays booked by December 30, 2014 and stays completed from December 30, 2014 to January 1, 2015.', 'Limited number of rooms available.', 'Minimum stay of 2 nights is required & must stay over December 31, 2014.', '15% service charge and tax is not included in the package and subject to change without any notice.', 'Breakfast to be consumed at the Kitchen Table restaurant on departure day. Guest will be eligible for the breakfast based on number of persons booked overnight. Additional persons will be charged at the restaurant according to retail price.', 'NYE dinner buffet to be consumed at The Kitchen Table on December 31, 2014 only. Two guests per room will be eligible for the dinner buffet, and additional guests will be charged at the restaurant according to retail price. Prior reservations for the additional guests are required.', 'Free access to the FEI NYEcountdown party on December 31, 2014 is limited to a maximum of 2 adults only per room. Guests under 18 years old will not be allowed. The tickets will not be sold to general public or any external guests. Please collect the passes at time of check in.', 'Alcoholic beverage service is restricted to those 18 years or older (with valid identification).', 'Massage treatment in the package is limited to 60min AWAY Spa Signature Massage only. Spa treatment cannot be cumulated & valid during stay only. Prior reservation is recommended for the Spa treatment. This is to ensure space availability and the hotel will not be held responsible for any unconsumed portion of the package.', 'All package components are not transferable and must be consumed during stay. If any portion is not consumed, they will not be refundable or exchangeable in cash.', 'Extra services & amenities not part of the package will be charged per consumption & will be on guest's own expense.', 'All package amenities are per room/per night and will be presented upon arrival unless otherwise noted.', 'This offer is only available if booked via Starwood distribution channels. Offer will not be applicable if booked through third party distribution channels, travel agents or any other external websites.', 'Offer not applicable to groups nor is it combinable with other special/discounted rates.', 'Starwood Hotels & Resorts Worldwide, Inc. reserves the right to cancel this promotion at anytime without notice.', 'Not responsible for omissions or typographical errors. Void where prohibited by law. Not to be combined with offers or promotions.', 'Any unused portion/s of the package is not transferable or exchangeable for cash/credit.', 'Starpoints, SPG, Starwood Preferred Guest, Sheraton, Four Points, W, Aloft, Le Meridien, The Luxury Collection, Element, Westin, St. Regis and their respective logos are the trademarks of Starwood Hotels & Resorts Worldwide, Inc., or its affiliates.']

Comment: I wanted to iterate over all the bullets.

`for terms in terms_elements.strings: print(terms.lstrip('\u2022'))`

This is all I wanted ... and many many thanks to you sir...

Scrape text after every  - BeautifulSoup


What's the best way to define this native interface for .NET consumption?

Question: I have a library whose functionality I want to eventually expose to .NET.  The method I want to expose has the following signature:
void DoSomething(std::list<SomeStruct>& someList);
The variable someList gets populated by DoSomething.
I know how to export from the library already.  My main question is what would a ".NET friendly" interface look like for this function?  I'd assume that std::list is a bad idea if I want to use C# with P/Invokes.
What other options are there?  As the caller, I won't know the size of the buffer that I should pass in ahead of time.  Also, as the caller, I'd rather not make multiple calls to the function with small fixed-sized buffers nor would I want to pass in a super large buffer.
What's the best practice for this case?
Comment: You cannot expose C++ classes to managed code through pinvoke.  Only C++/CLI would work in a scenario like this.  You are still copying list elements, that's unavoidable unless it is a simple type.  A struct is not simple.
Comment: Thanks @HansPassant -- I'm OK with not using the STL list class and working with a (native) dynamically allocated array instead.  How is that approach regarded?  Is it too mistake prone (with respect to freeing memory on the managed side)?   Would such an interface pass the "laugh" factor?
Comment: You are asking an entirely different question from the one you posted here.  Edit or re-ask.
Answer: You can define a struct for use in the pinvoke call. Decorate it on native and mnaged sides, so that the packing is the same on each side. As for the variable sized out parameter, you could use ::GlobalAlloc to allocate an array that can then be deallocated in C#. Pass out an item count as well. In C#, the Marshal type has various methods to use to work with a GlobalAlloc'd array.
Comment: I'll flesh this out with some detail when I get to work tomorrow, unless somebody else gives a better answer.
Comment: Thanks.  I can pick up the pieces from there... but I'm wondering how "standard" is this approach?
Comment: Well, sorry for totally forgetting about this, but good to know it was useful to some extent. As to "standardicity", I'm really not sure!


SSRS BIDS Expression to pick visibility based on AD GROUPS

Question: I have a box with the text 'Dill Down Facility Available' (see screenshot)
When the report is run I only want certain people to see this box.
The people I want to see this box are contained in 19 different ADGROUPS
There will be others who run this, but I need them to see everything bar the yellow box.
If I right click the box and go to:
TextBoxProperties > Visibility > Show or hide based on an expression,
I am able to enter an expression.
The one ive written in the screenshot allows me to pick 1 individuals AD name in the following format:
DOMAINNAME\ADNAME

However, if I put an ADGROUP name instead of the ADNAME, it does not work, and instead everyone can see the yellow box.
As the expression contains
User!UserID

I believe this may be stopping my ADGROUP name working as its looking for a USER, although this would not explain why it then allows anyone to see this box.
Can anyone provide the expression to allow either:
a) 1 group name
b) multiple group names
Thanks.
Answer: SSRS does not have this functionality built in, you'll need to use a Custom Assembly and reference it in your project.
See: http://support.microsoft.com/kb/920769


Qual as vantagens e desvantagens de usar o Heroku para sua aplicação?

Question: Principalmente em ambiente empresarial
Comment: Depende. Como é a sua aplicação? Quais são seus requisitos? Você precisa dar detalhes, senão as respostas vão ser basicamente "eu gosto" ou "eu não gosto" do heroku.
Answer: Sua pergunta está um tanto ampla. Gostaria de saber sobre as vantagens e desvantagens do Heroku sobre outros ambientes de PaaS (Platform-as-a-Service)? Gostaria de saber quais as vantagens e desvantagens de ter sua aplicação na nuvem? Ou que tipo de aplicações se beneficiam da nuvem?
Imaginando que sua pergunta seja a primeira opção, ou seja, quais as vantagens do Heroku sobre outros serviços de PaaS, no caso de JAVA, nesse caso sem dúvidas seria a maior vantagem a ferramenta user@server:~$ heroku, um pacote de software que permite iniciar e criar aplicações, setar a integração contínua GIT, deployar, abrir a aplicação, adicionar add-ons... muitos recursos úteis.
Heroku também possui um mercado de add-ons interessante, o que simplifica o processo de desenvolvimento. Por exemplo, digamos que você gostaria de adicionar uma datastore... um banco de dados PostgreSQL, por exemplo. Muito como instalar um novo plug-in em um site Wordpress, você somente tem de acessar o Heroku Marketplace e clicar em um serviço de banco de dados. Essa integração pré-concebida reduz as horas-homem dos desenvolvedores, que não tem de criar a ponte entre o serviço de datastore e a aplicação em questão.
Em fim, o Heroku é uma ferramenta que, em certo ponto, simplifica o processo de desenvolvimento, oferecendo grande valor para aplicações que devem ser desenvolvidas rapidamente. Um concorrente, o Google App Engine, não oferece as mesmas comodidades de forma tão simplificada.


Why do LaTeX documents have a whacking great big space at the top?

Question: I am extremely new to LaTeX but have noticed that in the examples I have seen of LaTeX documents that there is always a massive number of empty lines at the top of the compiled pdf file. Nobody seems to say a word about this! Is this some kind of academic convention?
Here is an example:
\documentclass[]{article}
\usepackage{graphicx}

\title{Here is my title}
\author{Kevin Wright}

\begin{document}

\maketitle

\begin{abstract}
    This is my abstract stuff
\end{abstract}
hello $\sqrt{x+y-10}$

\end{document}

Comment: Oh, you mean the output instead of the latex file. Then this boils down to a pure design question, maybe better ask at https://graphicdesign.stackexchange.com
Comment: Can you give an example? I can't remember having seen a document with excessive empty lines at the top.
Comment: I've added an example .tex file with the issue.
Comment: I wouldn't consider one or at most two empty lines in a row as massive number. Most people will put them in their document to make them more readable and separate logical blocks in the code.
Comment: It looks like about 15 or 16 lines to me.
Comment: (personally I would add _more_ empty lines to your example code. Before the packages and after the abstract)
Comment: Where do you see 15 or 16 empty lines?
Comment: I can only see two
Comment: Just to clarify; Do you mean in the DVI/PDF output?
Comment: Yes, thats what I mean
Answer: Yes, by default the article class uses a lot of whitespace above the title of the paper. If you use a separate title page about 60 points of it.
With regard to the space on top of a regular page,
add \usepackage{layout} to your example, and just before the \end{document} add:
\section{Layout}

\layout

Now process and view the document and you will see exactly what the space on top of the page is made up of.
If you want to modify that, have a look at e.g. the geometry and fancyhdr packages.


Calcular valores em jQuery

Question: Tenho três campos:
<input type="number" id="product_quantity" name="product_quantity" placeholder="Quantidade">

<input type="text" id="buying_price" name="buying_price" placeholder="Valor Total" value="" class="form-control autonumber" data-a-sign="R$ " data-a-sep="." data-a-dec=",">

<input class="form-control autonumber" data-a-sign="R$ " data-a-sep="." data-a-dec="," name="others_price" id="others_price" placeholder="Outras Despesas" type="text">

Preciso fazer o seguinte. Ao digitar o campo product_quantity, aparecer na div embaixo. return_qty_product - se a caso preencher o campo others_price deverá somar ao outro valor e dividir pela quantidade
Feito isto, preciso dividir o valor total, pela quantidade.
Exemplo: 500 unidades, o total da compra foi R$ 500,00
O resultado deverá ser 1. Na div results!
Como posso fazer isto em jQuery?
Edit:
Eu tentei fazer assim:
$("#product_quantity").keyup(function(){
    $(".product_quantity_return").html($("#product_quantity").val());
});

$("#buying_price").keyup(function(){
    var price = $("#buying_price").val();
    var price_return = price.replace("R$ ", "");
    var price_return_b = price_return.replace(",", "");
    var calc = price_return_b/$("#product_quantity").val();
    //alert(calc)
    $(".buying_price_return").html(calc.toLocaleString("pt-BR", { style: "currency" , currency:"BRL"}));
});

Mas o cálculo dá numero exato... Na calculadora eu fiz R$ 699,00 / 250 unidades - 2.79... mas arredondou para 2.80
Answer: Na verdade o resultado de 699/250 é 2.796. O .toLocaleString irá considerar apenas 2 casas decimais, mas se a terceira casa for maior ou igual a 5, é feito um arrendondamento para maior no valor da segunda casa decimal, logo 79 + 01 = 80.
Se você quer os exatos 2,79 como resultado, você precisa trabalhar em cima de string, pegando o valor antes e depois do ponto que separa as decimais.
Como você está usando máscara, deve fazer 2 replaces: um pra remover os pontos e outro para trocar a vírgula pelo ponto, isso para que o valor fique no formato que o JavaScript trabalha:
var price_return_b = price_return.replace(/\./g, "").replace(",", ".");

Primeiro você deve converter o resultado em string com .toFixed(3) para pegar apenas 3 decimais depois do ponto. Isso até poderá arrendondar a 3ª casa decimal caso a 4ª seja maior ou igual a 5, mas não alterará a 2ª casa, que é o que interessa:
var calc = (price_return_b/$("#product_quantity").val()).toFixed(3);

Em seguida pode usar o método .substr para pegar o valor antes e depois do ponto e depois concatenar:
calc = calc.substr(0, calc.indexOf(".")) + calc.substr(calc.indexOf("."),3);

Depois é preciso converter a string em float:
calc = parseFloat(calc);

Na questão do evento keyup, é melhor usar o evento input que irá atualizar o valor até quando você clicar nas setas com campo tipo number. Porém, a máscara já usa esse evento no campo, então você pode usar os dois eventos ao mesmo tempo nos 3 campos:
$(""#buying_price, #product_quantity, #others_price"").on("keyup input", function(){...

E você já pode remover esse código:
$("#product_quantity").keyup(function(){
    $(".product_quantity_return").html($("#product_quantity").val());
});

A função ficará assim:
$("#buying_price, #product_quantity, #others_price").on("keyup input", function(){

   $(".product_quantity_return").html($("#product_quantity").val());

    var others = $("#others_price").val();
    var others_return = others.replace("R$ ", "");
    var others_return_b = others_return.replace(/\./g, "").replace(",", ".") || 0;

    var price = $("#buying_price").val();
    var price_return = price.replace("R$ ", "");
    var price_return_b = price_return.replace(/\./g, "").replace(",", ".") || 0;
    var calc = ((parseFloat(price_return_b)+parseFloat(others_return_b))/$("#product_quantity").val()).toFixed(3);
    calc = calc.substr(0, calc.indexOf(".")) + calc.substr(calc.indexOf("."),3);
    calc = parseFloat(calc);
    //alert(calc)
    $(".buying_price_return").html(calc.toLocaleString("pt-BR", { style: "currency" , currency:"BRL"}));
});

Exemplo:

$("#buying_price, #others_price").maskMoney({
    prefix: "R$ ",
    decimal: ",",
    thousands: "."
});

$("#buying_price, #product_quantity, #others_price").on("keyup input", function(){

   $(".product_quantity_return").html($("#product_quantity").val());

    var others = $("#others_price").val();
    var others_return = others.replace("R$ ", "");
    var others_return_b = others_return.replace(/\./g, "").replace(",", ".") || 0;

    var price = $("#buying_price").val();
    var price_return = price.replace("R$ ", "");
    var price_return_b = price_return.replace(/\./g, "").replace(",", ".") || 0;
    var calc = ((parseFloat(price_return_b)+parseFloat(others_return_b))/$("#product_quantity").val()).toFixed(3);
    calc = calc.substr(0, calc.indexOf(".")) + calc.substr(calc.indexOf("."),3);
    calc = parseFloat(calc);
    //alert(calc)
    $(".buying_price_return").html(calc.toLocaleString("pt-BR", { style: "currency" , currency:"BRL"}));
});

<input type="number" id="product_quantity" name="product_quantity" placeholder="Quantidade">
<input type="text" id="buying_price" name="buying_price" placeholder="Valor Total" value="" class="form-control autonumber" data-a-sign="R$ " data-a-sep="." data-a-dec=",">
<input class="form-control autonumber" data-a-sign="R$ " data-a-sep="." data-a-dec="," name="others_price" id="others_price" placeholder="Outras Despesas" type="text">

Comment: Então é isso mesmo, porém, se eu adicionar a quantidade e o valor, dá certo, se eu alterar a quantidade, não dá certo... o que pode ser?
Comment: Ainda tem falha... vamos suporte que eu coloque no campo quantidade 10, e no campo valor total 10,00, o retorno deveria ser 1,00. até ai funciona, se eu trocar a quantidade pra 20, o preço médio retorna 50,00.
Comment: Fiz o mesmo teste aqui no executar, e dá certo, mas quando eu volto o campo anterior, ele refaz o calculo
Comment: Aí dá a diferença
Comment: http://prntscr.com/lpssqw
Comment: O problema está em eu alterar a quantidade... ele modifica também o resultado, oque deveria mesmo, mas me parece que ele multiplica..
Comment: Deve ser porque o campo do valor tem uma máscara... vou dar uma olhada aqui
Comment: O problema é o seguinte... eu tenho dois campos, e um adicional. Quando eu preencho a quantidade, ele puxa a quantidade no retorno, até ai, ok.. porém, o calculo só funciona se eu alterar por segundo a quantidade, incluir o valor primeiro e por segundo a quantidade
Comment: Então, deve ser a máscara que tá subvertendo isso... vc tá usando máscara no campo do valor, não tá?
Comment: estou sim, vou tirar a masc pra ver
Comment: o problema são as casas decimais... eu fiz o código sem levar em consideração isso, vou arrumar
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/86525/discussion-between-andre-baill-and-sam).

Calcular valores em jQuery


Differences between Mann-Whitney U and chi-square tests for if two-samples come from same distribution

Question: In a textbook, it introduces the chi-square goodness of fit test to test independence between two variables (organized in a contingency table), which can also be used to test if m samples are likely to come from the same distribution by using one dimension as samples and the other as values/bins.
Then in another chapter, it introduces the Mann-Whitney test, which seems to do the same thing. Both are nonparametric and chisquare can be applied to continuous distribution by discretizing the bins.
I am confused that they seem to do the same thing, so for the purpose of testing if two populations are the same (distribution and parameters), what're their differences?
Comment: which can also be used to test if m samples are likely to come from the same distribution by using one dimension as samples and the other as values/bins. please elaborate!
Comment: my bad, say values [-5, -3] [-3 -1] [-1 1] [1 3]...as bins (X) and samples 1 2 3...m as Y in a contingency table, then we can test if all m samples are likely from the same distribution as if testing for indifference between X and Y. Then in a later chapter, I read the Mann-Whitney test which seems to do the same thing for 2 samples, hence my question.
Comment: I found the following! https://ned.ipac.caltech.edu/level5/Wall2/Wal4_3.html
Comment: Mann-Whitney test, which seems to do the same thing. what do you mean?
Comment: if two populations are the same (distribution and parameters), what're their differences ? could you post a glimpse of your data ?
Answer: The Wilcoxon Mann-Whitney two-sample rank sum test tests whether observations from one group tend to be bigger than observations from another group.  It is used for ordinal or continuous response variables Y and not for the case where Y is binary or represents unordered categories.  But if Y were binary the p-value from the Wilcoxon test, though not very accurate, would not be far from the p-value from a $2\times 2 \chi^{2}$ Pearson test.  The same is true when doing a two-sample $t$-test on binary Y.  So tests of association have a strong relationship to tests of group differences.
The one-sample $\chi^2$ goodness of fit test is altogether different.  It measures the distance between observed category frequencies and the theoretical frequencies that would be observed had Y come from a specific parametric distribution.
Comment: What you say seems to be in-line with https://ned.ipac.caltech.edu/level5/Wall2/Wal4_3.html. Right?


How do you determine the hazard rate function for a uniformly distributed variable X ~ Uni(0,a)?

Question: Suppose we have a uniformly distributed variable X ~ Uni(0,a).  Then the probability density function
$$f_X(x) = \begin{cases}\frac{1}{a} & \text{ if } 0 <x < a \\ 0 & \text{ else }\end{cases}$$
and the cumulative distribution function
$$F_X(x) = \begin{cases}0 & \text{ if } x \leq0 \\ \frac{x}{a} & \text{ 0 < x< a } \\ 1 & x \geq a \end{cases}$$
The formula for the hazard rate function is:
$\lambda_X(t)= \frac{f_X(t)}{1-F_X(t)} = $
$$ \begin{cases}0 & \text{ if } x \leq0 \\ \frac{1}{a-x} & \text{ 0 < x< a } \\ \frac{0}{1-1} & x \geq a \end{cases}$$
The part that I'm confused about is the last case $x \geq a$ of the hazard rate function because I'm getting a divide by zero error.  How do I correct this?
Comment: Note that as $x \to a$, the hazard rate is increasing without bound towards $\infty$. This is standard for all random variables with bounded support. So there is nothing to correct. In fact, I am surprised that you don't get a "divide-by-zero" error for values of $x$ very close to $a$.
Answer: You don't correct that.
The hazard function is indeed undefined above the supremum for the random variable's support.


Pass foreach loop in function

Question: Just wondering if we can do something like below:
I want to pass foreach loop in function as attribute.
<?php

TestMethodForEach( foreach($_POST['activity'] as $activityID){ $activityID; } );

?>

How can I achieve this functionality in php?
Here is my real code:
<?php

 $accountServices->RL_ChangeInActivities(
                            new IhcStructRL_ChangeInActivities(
                                new IhcStructChangeActivity(
                                '00000000-0000-0000-0000-000000000000',
                                $accountID,
                                $_POST['serviceID'],
                                '1',
                                'IhcStructChangeActivity',
                                'teset,etsagad, asdfasd',
                                    new IhcStructArrayOfAccountActivity(
                                            new IhcStructAccountActivity(
                                                '00000000-0000-0000-0000-000000000000',
                                                'activityID 1',
                                                $accountID,
                                                'IhcStructAccountActivity',
                                                'ActivityNumber'
                                                )
                                        )
                                )
                        )
                    );

  ?>

Actually i want to repeat this object IhcStructArrayOfAccountActivity.
You will see ( ActivityID 1 ) in this object (new IhcStructAccountActivity) so i have more then 5 activity ID or may be more, doesnt matter. so how can i repeat this object dynamically so this should appear like
 <?php

new IhcStructArrayOfAccountActivity(
new IhcStructAccountActivity(
'00000000-0000-0000-0000-000000000000',
'activityID 1',
$accountID,
'IhcStructAccountActivity',
'ActivityNumber'
)
)

 new IhcStructArrayOfAccountActivity(
new IhcStructAccountActivity(
'00000000-0000-0000-0000-000000000000',
'activityID 2',
$accountID,
'IhcStructAccountActivity',
'ActivityNumber'
)
)

 new IhcStructArrayOfAccountActivity(
new IhcStructAccountActivity(
'00000000-0000-0000-0000-000000000000',
'activityID 3',
$accountID,
'IhcStructAccountActivity',
'ActivityNumber'
)
)

 ?>

Hope you understand now.
Comment: Why would you want to do that? What's the behavior you're looking for?
Comment: You've already written the code, why not just run it and answer your own question?
Comment: Yes bro i belive it doesnt making any sense but is there any way like this? actually i want to repeat the value in xml.
Comment: Do the old Reverse-a-roo for the same result
Comment: I have update the code, please have a look now.
Answer: <?php
    foreach ($_POST['acitivity'] as $activityID) {
        TestMethodForEach($activityID);
    }
?>

Or array_walk will do the thing.
Answer: The right code is :
<?php  foreach($_POST['activity'] as $activityID) {
        TestMethodForEach($activityID;);
       }
 ?>

i hope that is what you're looking for

Pass foreach loop in function


How to solve a problem with different results in SAS and R due to a number representation issue

Question: I have a huge dataset in SAS and I'm trying to reproduce it in R.
I will focus on just a single column with BMI score.
In SAS, this is numeric column with 8.2 format.
In R - it is a numeric column which is then rounded to 2 decimal places by round(x, 2).
The formula for BMI is: weight/((height*0.01)**2)
When I'm comparing both datasets by typing sas==r, I'm getting all TRUE's but just one case...
SAS: 34.38
R: 34.37
Let's have a look at this case and see raw values:
Weight:  88
Height: 160
Result in SAS: 34.375
Result in R: 34.375
Looks the same, but for R this is not true:
<code>> 88/((160*0.01)**2) == 34.375
> [1] FALSE

> options(digits = 22)
> 88/((160*0.01)**2) == 34.375
[1] 34.37499999999999289457
</code>
When I'm trying to round, it gives:
<code>> round(88/((160*0.01)**2), 2)
[1] 34.36999999999999744205
</code>
so
<code>> options(digits=7)
> round(88/((160*0.01)**2), 2)
[1] 34.37
</code>
I tried to play with mpfr library - without success.
I tried something like this:
<code>> round(as.numeric(format(round(88/((160*0.01)**2), 3), nsmall = 3)), 2)
[1] 34.38
</code>
but when applied to the entire dataset this ruins other cases.
I changed the format in SAS to see more decimal digits and what I see is exactly: 34.37500
I'm going to give up... Is there any way to make both results exactly the same?
I can see that SAS and R share the same number representation issue, for instance 1-0.9 <> 0.1, and 0.01 is not 0.01 but
<code>> options(digits=22)
> 0.01
[1] 0.01000000000000000020817
</code>
For my dataset, SAS and R agree in 99.99% with this one exception...
Any help, advice? :) Perhaps there is some options I could set, or a smart woarkound?
The output can be character. I'm exporting it to CSV, so I don't care about it.
Comment: @Aksakal You are talking only about data storage formats.  Internally SAS uses IEEE floats: see www2.sas.com/proceedings/sugi29/235-29.pdf.  It sounds like your first comment "no..." is just speculation. (BTW, I'm quite familiar with BCD--I used to write Assembly language programs on IBM mainframes.)
Comment: @whuber, my guess is that SAS, like some other systems such as Oracle, use binary-decimal format, instead of IEEE 754 floating point when reals are specified as w.d format like NUMERIC 8.2. See e.g. https://en.wikipedia.org/wiki/Binary-coded_decimal this is from IBM era when SAS was developed
Comment: @whuber, yes, it was speculation. I found the specification here: http://support.sas.com/documentation/cdl/en/lrcon/67885/HTML/default/viewer.htm#p0ji1unv6thm0dn1gp4t01a1u0g6.htm SAS on WinTel uses IEEE with 80 bits, and IBM FP on mainframes My R 64bit seems to use the standard IEEE 64 bit precision, not the extended one
Comment: Is there any problem with rounding to slightly greater precision in `R` and then rounding again?  *E.g.*, `round(round(88/((160*0.01)**2), 3), 2)`.
Comment: @whuber, no in this case the issue is in 0.01^2, it's machine precision larger than 0.0001
Comment: @Aksakal The issue is how SAS converts floats into decimal encoded values for storage in its database. We are, in effect, trying to reverse-engineer that process. The double-rounding procedure is one guess concerning what SAS does. What evidence do you have that SAS is doing something different?
Answer: The bad news is that IEEE floating-point numbers such the one you use in R is generally not going to be exactly the same as NUMERIC 8.2 in SAS. The number will match in cases where the results are integer.
The floating point numbers will appear to match only due to the implicit conversion. For instance, how do you compare the numbers in SAS and R? You have to get them into one system, SAS or R, then there will be some kind of conversion involved either when you read the data or when you compare them. So, this implicit conversion will hide the difference between data formats, but the difference will still show up in some cases.
In your case, look at this example to see how to get the numbers to be the same, sort of:
<code>   > height=160
> weight=88
> x=weight/(height**2*0.0001)
> x
[1] 34.375
> round(x,2)
[1] 34.38
> options(digits=22)
> round(x,2)
[1] 34.38000000000000255795
> round(x,2)
[1] 34.38000000000000255795
> options(digits=5)
> round(x,2)
[1] 34.38
</code>
UPDATE:
It appears that SAS on Windows/Intel will use x86 extended precsision format for floating point, i.e. 80 bits real numbers. On the other hand, R appears to use IEEE 754 standard format, i.e. 64bit floating point. I might be wrong on this one, but that's what I see on my computer:
<code>> .Machine$double.xmax
[1] 1.797693e+308
</code>
If R was using 80 bit reals, then I'd expect that to be $1.18×10^{4932}$.
Thus, it's impossible to guarantee that SAS and R on Windows/Intel will exactly match in every case by tweaking the code in general. If you have a large data set it's likely that whatever trick you use would fail in one case or another.
Therefore, you have to write the code in such a way that it doesn't matter whether the numbers match exactly or not.
Comment: @Bastian, there's no common rule. The only thing is that if you rely on the number of decimal digits somehow, then when using binary internal formats you run into issues usually. In this case 0.01 brought my attention.
Comment: The first time, it must be `round(x,20)`, right? Strangely, `options(digits=22)` didn't change anything on my R system, so I could not reproduce it.
Comment: @HorstGrünbusch, sorry, I skipped a few lines in my post, added them back.
Comment: Dear Aksakal, thank you very much for this explanation. After applying this smart form of the formula, the mentioned case has been fixed, but other one has been broken...

What is interesting - again, ALL but ONE cases agree. Now the incorrect result is for the following input data:
Comment: data: weight: 56, height: 160. SAS raw = 21.875 (00), R raw: x <- 56/(160**2*0.0001). x == 21.875 [1] TRUE. After rounding (22 digits):  round(x, 2) [1] 21.87999999999999900524, (7 digits): round(x, 2) [1] 21.88. But SAS rounded: 21.87. So now the SAS result is less than R one.
Comment: BTW, thank you very much for showing me the trick with powers in the formula. It helped me a lot, without "dirty workarounds". Is there a common rule your solution follows?


Locking/unlocking mutex inside private functions

Question: Imagine you have a big function that locks/unlocks a mutex inside and you want to break the function into smaller functions:
#include <pthread.h>

class MyClass : public Uncopyable
{
public:
    MyClass() : m_mutexBuffer(PTHREAD_MUTEX_INITIALIZER), m_vecBuffer() {}
    ~MyClass() {}

    void MyBigFunction()
    {
        pthread_mutex_lock(&m_mutexBuffer);

        if (m_vecBuffer.empty())
        {
            pthread_mutex_unlock(&m_mutexBuffer);
            return;
        }

        // DoSomethingWithBuffer1();

        unsigned char ucBcc = CalculateBcc(&m_vecBuffer[0], m_vecBuffer.size());

        // DoSomethingWithBuffer2();

        pthread_mutex_unlock(&m_mutexBuffer);
    }

private:
    void DoSomethingWithBuffer1()
    {
        // Use m_vecBuffer
    }

    void DoSomethingWithBuffer2()
    {
        // Use m_vecBuffer
    }

private:
    pthread_mutex_t m_mutexBuffer;
    std::vector<unsigned char> m_vecBuffer;
};

How should I go about locking/unlocking the mutex inside the smaller functions?
Should I unlock the mutex first, then lock it straightaway and finally unlock it before returning?
void DoSomethingWithBuffer1()
{
    pthread_mutex_unlock(&m_mutexBuffer);
    pthread_mutex_lock(&m_mutexBuffer);
    // Use m_vecBuffer
    pthread_mutex_unlock(&m_mutexBuffer);
}

Comment: If m_vecBuffer is empty you return and never unlock the mutex?
Comment: After your edit: your "fix" is not the right solution. Use an RAII guard object.
Comment: I already use ScopedLock RAII class in my real code but thanks gx_ for pointing that out anyway.
Answer:
How should I go about locking/unlocking the mutex inside the smaller functions?

If your semantics require your mutex to be locked during the whole MyBigFunction() operation then you can't simply unlock it and relock it in the middle of the function.
My best bet would be to ignore the mutex in the smaller DoSomethingWithBuffer...() functions, and simply require that these functions are called with the mutex being already locked. This shouldn't be a problem since those functions are private.

On a side note, your mutex usage is incorrect: it is not exception safe, and you have code paths where you don't release the mutex. You should either use C++11's mutex and lock classes or boost's equivalents if you are using C++03. At worst if you can't use boost, write a small RAII wrapper to hold the lock.
Answer: In general, try to keep the regions of code within each lock to a minimum (to avoid contention), but avoid to unlock and immediatly re-lock the same mutex. Thus, if the smaller functions are not mutually exclusive, they should both use their own indepdenent mutices and only when they actually access the shared resource.
Another thing that should consider is to use RAII for locking and unlocking (as in C++11 with std::lock_guard<>), so that returning from a locked region (either directly or via an uncaught exception) does not leave you in a locked state.


Bank system with accounts that use dictionary to store it but it only reads the first account

Question: I'm creating a bank system with accounts but if I put 2 accounts or more the 2nd account can't be read and doesn't work in logging in only the first one that works
accounts = []
names = [item.get('fullname') for item in accounts]
customers = int(input("Number of customers: "))
while customers != 0:
    fullname = str(input("Input Fullname: "))
    while fullname in names:
        print('Name already exist')
        fullname = str(input("Input Fullname: "))
    else:
        pass
    pins = str(input("Please input pin of your choice: "))
    while len(pins) != 4:
        print ('Error. Only 4 digit allowed')
        pins = str(input("Please input pin of your choice: "))
    else:
        pass
    balance = int(input("Please input a value of deposit to start and account: "))
    account = [{"fullname": fullname, "pins": pins, "balance": balance}]
    accounts1 = account.copy()
    accounts.append(accounts1)
    print(accounts)
    customers -= 1
for i in range (len (accounts)):
    if name == accounts[i]['fullname'] and pin == accounts[i]['pins']:
        print('Your current balance is {} PHP'.format(accounts[i]['balance']))
    else:
        print("Account not found")
        break

I think it's because the array will have double bracket after appending
Comment: Please update the indentation of your code. Python is very sensitive to indentation, as are python programmers.
Comment: `account` should be a `dict`, not a `list` with a single `dict`. There's also no reason to append a copy of the dict to `accounts`, since `account` is a brand-new `dict` with no pre-existing references to it.
Comment: What I am saying is that if your code were really what you have posted then you would get errors about your indentation.
Comment: Welcome to SO! Please take the [tour], read [what's on-topic here](/help/on-topic), [ask],
and the [question checklist](//meta.stackoverflow.com/q/260648/843953),
and provide a [mre] that people can paste into their environments to replicate your problem. Also, include full stack traces if you get any errors, and _fully describe the problem!_  "It doesn't work" is not an acceptable description.
Comment: Im sorry kinda new to this
Comment: Please also fix your syntax (there is no `:` at the end of your `for` statement for example). This code cannot be run/tested as is.
Comment: Did you mean to add: `customers -= 1` at the end of your `while` loop?
Comment: yah i forgot to add it
Comment: Oh, but was that in your original code? Is that a fix for your problem?
Comment: yah its actually long code and that's the only last problem i have
Answer: The original code had multiple errors including a wrong indentation and the missing but referenced names list.
One - at least kind of okayish working - solution based on your code is:
accounts = []
names = [] # add the names list
customers = int(input("Number of customers: "))
while len(accounts) != customers:
    fullname = str(input("Input Fullname: "))
    while fullname in names:
        print('Name already exist')
        fullname = str(input("Input Fullname: "))
    else:
        pass
    pins = str(input("Please input pin of your choice: "))
    while len(pins) != 4:
        print('Error. Only 4 digit allowed')
        pins = str(input("Please input pin of your choice: "))
    else:
        pass
    balance = int(
        input("Please input a value of deposit to start and account: "))
    account = {"fullname": fullname, "pins": pins, "balance": balance}
    accounts.append(account)
    names.append(fullname)
    print(accounts)

# Authenticate before staring the loop

name = str(input("Authenticate: Input your full name: "))
pin = str(input("Authenticate: Input your pin: "))
balance = None

for account in accounts:
    if name == account['fullname'] and pin == account['pins']:
        balance = account['balance']
        break

if balance == None:
    # then we had no match - otherwise it should be some integer
    print("Account not found")
else:
    print('Your current balance is {} PHP'.format(balance))


API Google Não aparece na minha pagina

Question: Ola, estou tentando inserir o google maps num site MVC que o Visual Studio 2012 já disponibiliza para teste. Tirando só a parte do maps e colocando num aspx avulso, ele gera o mapa bonitinho do jeito que preciso mas quando jogo ele em uma div dentro da pagina "contact" ou qualquer outa pagina do MVC ele não aparece. Alguém sabe me explicar o porque ou o que tenho que fazer para esse mapa aparecer na div certinha.

<%@ Page Title="Contact" Language="VB" MasterPageFile="~/Site.Master"" > AutoEventWireup="true" CodeFile="Contact.aspx.vb" Inherits="Contact" %>

<hgroup class="title">

Telefones

</hgroup>

Contatos:

        Principal:
        +55 (31) 3218-1500

        Horário de plantão:
        +55 (31) 9-9236-0601

Email:

        Suporte:
        email@example.com

        Comercial:

        Aleandro - email@example.com

        Robert - email@example.com

        Christiano Cassio - email@example.com

        Gerentes:
        Leandro - email@example.com
        Frederico - email@example.com

Endereço

        R. Álvares de Azevedo, 103 - Colégio Batista, Belo Horizonte - MG, 31110-290

Answer: o elemento definido aqui como map-canvas
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

não está definido em nenhum lugar na sua view. Além disso, não parece que o método initialize está sendo chamado em nenhum lugar.
Se não for problema, coloque todo o conteudo do método initialize dentro de
$(document).ready(function(){});

porque desta forma vai ser executado sempre que a view terminar de carregar ;)
Comment: Coloquei uma   e codigo dentro do $(document).ready(function(){ jQuery }); mas não funcionou :/ . tem outro lugar para colocar ou eu que não to sabendo chamar ele nessa div?
Comment: Consegui colocar fazer aperecer depois que setei em um div, foi só colocar o atributo no css "position: absolute;"

API Google Não aparece na minha pagina


Different behavior between iOS 4.3 and 5.0 with UIDatePicker code execution

Question: I have a perplexing problem in trying to sort out different behavior of the same code on an iPhone 4S running iOS 5.0 and an iPad running iOS 4.3.
The view controller code is associated with a view with a date picker to enter a date of birth. Via Interface Builder the date picker is associated with the received action "Value Changed" directed toward the view controller method -(IBAction)birthDate: (id)sender:
-(IBAction)birthDate: (id)sender {

//Code here executed when date of birth entered. Should not be executed when view loads.

}

It is very important in the app that this code NOT be executed when the view loads. I have demonstrated with a breakpoint insertion that this code does not execute when the view loads with iOS 5.0, but does execute when the view loads with iOS 4.3, causing a real problem with the program (the default birthdate becomes interpreted as an entered birthdate). I very much would appreciate advice on how to prevent the IBAction code from executing in iOS 4.3 unless the user changes the default date of birth. I also am very curious as to why this difference in behavior should exist. Thanks in advance.
Answer: This is a documented change to UIPickerView's behaviour in iOS 5.0 (Release Notes)
One way to get around it on iOS 4.3 would be to have a BOOL that is set to YES at the beginning of loadView and NO at the end.
Your value changed method birthDate: could then check that this BOOL value is NO before handling the change.
-(void)loadView
{
    isViewLoading = YES; // isViewLoading is a BOOL ivar
    // load view
}
-(void)viewDidLoad
{
    // what ever else
    isViewLoading = NO;
}
-(IBAction)birthDate:(id)sender
{
    if (isViewLoading) return;
    // handle change
}

Comment: Thanks for the code. Unfortunately, same problem still occurs with iOS 4.3. With this code and sequential breakpoints placed, the sequence of execution when the view loads is loadView, then viewDidLoad, then the method birthDate (with the boolean NO at that point). Any additional suggestions I could try?
Comment: try -(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; }
Comment: Excellent! The execution sequence of viewDidLoad, then birthDate, then viewDidAppear works perfectly now with the boolean scheme you suggested, running iOS 4.1, 4.2, 4.3, and 5.0. Thanks for the great help.


How to apply a Views filter to show fields if a radio button is not FALSE?

Question: I have a custom field that is a radio button (from CiviCRM), and I made it available as a filter by implementing hook_views_data().
I'd like to apply a filter to show fields if the radio button is set to true; in other words, if not == false.
I feel like this should be possible without using the Views PHP module, but I have hit a wall.
Answer: Often these kind of things come back to deciding how best to bend your requirements to suit the available logic. If I understand correctly, you have a radio button with the value of true, but no other options.
My immediate thought is to change it from a radio to a checkbox and set a default value as false (unchecked).
That way you just need to check for if true or if false and you don't need to concern yourself with if not false which does get tricky.
Comment: Thanks. This is a good idea in hindsight. Actually the radio button has 2 options: "yes" and "no". Even setting a radio button default or making it "required" would fix future data entries. Unfortunately, the form and data already exist, so changing it would be a pain. It might be the least painful option though...


Convergence of Exponential Function of Sequence

Question: If $x_n$ is a sequence such that $x_n \neq 0$, and $x_n \rightarrow 0$, then prove:
$$\lim_{n \rightarrow \infty} \frac{\exp(x_n) - 1}{x_n} = 1.$$
where $\exp()$ is the exponential function. I was wondering if I would be able to use the fact that if $x_n \rightarrow 0$, then $\exp(x_n) \rightarrow 1$ in this proof, but I'm skeptical of using that because the numerator would approach $0.$ I just need a bit of guidance/maybe a hint. Thanks in advance!
Comment: Can you use a taylor series expansion? If you could then expanding the exponential would make the answer very obvious.
Comment: @VividKraig We haven't "covered" Taylor series in my Real Analysis class yet, so I don't think I'd be able to use it here.
Answer: It is a direct consequence of the basic limit
$$\lim_{t\to 0}\frac{e^t-1}{t}=1 $$
together with the sequential definition of a limit of a function which applied to the limit above gives you the precise statement that has to be shown.
Answer: Observe that : $$ \left(\forall x\in\left[-1,1\right]\right),\ \left|\mathrm{e}^{x}-1\right|=\left|x\right|\int_{0}^{1}{\mathrm{e}^{xt}\,\mathrm{d}t}\leq \left|x\right|\int_{0}^{1}{\mathrm{e}^{t}\,\mathrm{d}t}=\left|x\right|\left(\mathrm{e}-1\right) $$
If $ \left(x_{n}\right)\in\mathbb{R}^{\mathbb{N}} $ such that $ x_{n}\underset{n\to +\infty}{\longrightarrow}0 $, then $ \left(\exists n_{0}\in\mathbb{N}\right)\left(\forall n\geq n_{0}\right),\ \left|x_{n}\right|\leq 1 $
Using the same trick : $$ \left(\forall n\geq n_{0}\right),\ \left|\frac{\mathrm{e}^{x_{n}}-1}{x_{n}}-1\right|=\left|\int_{0}^{1}{\left(\mathrm{e}^{x_{n}t}-1\right)\mathrm{d}t}\right|\leq\int_{0}^{1}{\left|\mathrm{e}^{x_{n}t}-1\right|\mathrm{d}t}\leq\left|x_{n}\right|\frac{\mathrm{e}-1}{2}\underset{n\to +\infty}{\longrightarrow}0 $$
Thus $$ \lim_{n\to +\infty}{\frac{\mathrm{e}^{x_{n}}-1}{x_{n}}}=1 $$
Comment: thanks! I was wondering if this applies in general to a sequence $x_n$ such that $x_n \neq \alpha$, and $x_n \rightarrow \alpha$, so that:  $\lim_{n \rightarrow \infty} \frac{\exp(x_n) - \exp(\alpha)}{x_n - \alpha} = \exp(\alpha).$
Comment: @John David factor out $ \exp{\alpha} $, denote $ y_{n}=x_{n}-\alpha $, then apply the previous result.


Using _.some | _.any properly for lo-dash or underscore

Question: I'm trying to see if any of the days are '01-01' ( the beginning of the year )
_.some(a.days, function(day){ console.log(day.date.format('DD-MM')) }, "01-01")

Produces this array of dates in my console :
01-01
02-01
03-01
04-01
05-01
06-01
07-01

So then I run without the console.log like so .. :
_.some(a.days, function(day){ day.date.format('DD-MM') }, "01-01")

And it returns :
false

Strange, eh? What do you think I'm doing incorrectly?
Comment: Btw if anyone came here inadvertently looking for the difference between 'some' and 'any', they are aliases and do the exact same thing.
Answer: You've misunderstood what the last argument to _.some is. The documentation shows that it is the context, or scope, under which the iterator function runs, but it seems like you're trying to use it as a value for equality testing.
You'll need to explicitly execute the equality test yourself.
_.some(a.days, function(day) {
    return day.date.format('DD-MM') === "01-01";
});

Answer: You appear to be misunderstanding how to use _.some(). Consult the documentation and you'll see that your function needs to return true or false, and the last argument will be used as this in tat function.
You need to do this instead:
_.some(a.days,function(day){ return day.date.format("DD-MM") == "01-01";});

Comment: Thank you thank you thank you. This is absolutely correct. I could only choose one though so I went with the underdog :(


Displaying array results of query in another file

Question: I am refreshing my memory on OOP and learning how to apply it to PHP with a focus on separation of concerns (MVC).  For practice, I found and edited some code online.  The function query() returns data from my MySQL database.  Here is that class file:
<code> <?php
    // ClassPractice.php

    class ClassPractice {
        public function __construct($host, $user, $pass, $name) {
            $this->host = $host;
            $this->user = $user;
            $this->pass = $pass;
            $this->name = $name;
        }

        protected function connect() {
            return new mysqli($this->host, $this->user, $this->pass, $this->name);
        }

        public function query($query) {
            $db = $this->connect();
            $result = $db->prepare($query);
            $result->execute();
            $result->bind_result($username);

            while ( $row = $result->fetch_object() ) {
                $rows[] = $row;
            }

            return $rows;
        }
    }
 ?>
</code>
There was no example of how this class was instantiated in another file, so I did that myself and called the query() method from this file:
<code>    <?php
       // index.php

       include('ClassPractice.php');

       $class = new ClassPractice('host', 'user', 'password', 'database');

       $results = $class->query("SELECT username FROM user");

       // Display formatted results of query here

?>
</code>
Since the rules of MVC dictate that the view must be handled separately from the model and controller, I would like to display the results of the query() method with this file.  I've researched this endlessly, but haven't found anything specific to what I'm trying to do.  Normally, I would assign the method call to a variable and then manipulate or display the variable as needed.  This does not appear to be an option in this case.  I tried assigning the query in the method call to an array variable and also using a foreach method to display the results.  So far nothing has worked.
Comment: EDIT: Assigned call to query() method to variable $results in index.php.
Answer: your code is wrong, change 'the while' for this line
<code>while ( $result->fetch() ) {
$rows[] = $row;
}
</code>
Comment: I had tried that, too, but I guess my foreach was incorrect.  I changed my while loop and fixed my foreach loop and it works now.  Thanks!


Example of quotient mapping that is not open

Question: I have the following definition:
Let ($X$,$\mathcal{T}$) and ($X'$, $\mathcal{T'}$) be topological spaces. A surjection $q: X \longrightarrow X'$ is a quotient mapping if $$U'\in \mathcal{T'} \Longleftrightarrow q^{-1}\left( U'\right) \in \mathcal{T} \quad \text{i.e. if } \mathcal{T'}=\{ U' \subset X' : q^{-1}\left( U' \right) \in \mathcal{T} \}$$
and the properties:

$q$ is a bijective quotient mapping $\Leftrightarrow$ $q$ is a homeomorphism
In general, $q$ quotient $\not \Rightarrow q$ open.
If $U \in \mathcal{T}, q(U)\subset X'$ is open if $q^{-1}\left( q\left( U \right) \right) \in \mathcal{T}$ but not in general.

I could not find an example of quotient mapping for which $q^{-1}\left( q\left( U \right) \right)$ is not open. I would understand the idea better if you could show me one.
Answer: Consider $\mathbb{R}$ with the standard topology. On $\mathbb{R}$, consider the equivalence relation
$$x\sim y \iff (x = y \lor \{x,y\} \subset \mathbb{Z}),$$
and let $(X',\mathcal{T}')$ the quotient space $\mathbb{R}/{\sim}$. By definition, $\pi \colon \mathbb{R}\to X';\; x \mapsto [x]_\sim$ is a quotient map, but that map is not open:
If $U \subset\mathbb{R}$ is an open set containing an integer, then $\pi^{-1}(\pi(U)) = U\cup \mathbb{Z}$ is in general not open.
Comment: Yes, we have $\pi^{-1}(\pi(A)) = A\cup \mathbb{Z}$ or $\pi^{-1}(\pi(A)) = A$, and when $A$ is closed, so is $A\cup\mathbb{Z}$.
Comment: I would say it is closed. Would you agree?
Answer: Here is a "visual" example:
Wrap the unit interval $[0,1]$ around the unit circle $S^1$ by identifying $0$ and $1$. The interval $[0,1/2) $ is open in $[0,1]$, but its image in $S^1$ is not open.
Comment: Why the image isn't open? Can you explain?
Comment: @Sourav Ghosh Because its preimage in $[0,1]$ is not open. (Recall that if $p:X\to Y$ is a quotient map of topological spaces, then a subset of $Y$ is open if and only if its preimage in $X$ is open.)
Comment: OK. $f^{-1}f{[0, \frac{1}{2})}=[0, \frac{1}{2}) \cup\{1\}$
Comment: Can you please explain how is it a quotient mapping? Thank you in advance.
Comment: @Rajdeep It is a closed map by https://math.stackexchange.com/questions/1728663/continuous-map-on-compact-hausdorff-spaces-is-closed, and a continuous, closed, surjective map is a quotient map https://math.stackexchange.com/questions/3981375/a-surjective-continuous-and-closed-map-is-a-quotient-map.
Answer: Let $X$ be a Hausdorff space, and let $a,b$ be a pair of distinct points. Stipulate that $\{b\}$ is not open. Define $f:X\to X\setminus\{b\}$ by $f(z)=z$ if $z\ne b$ and $f(b)=a$. There is a unique topology we may assign the codomain such that $f$ is a quotient map, let's endow that topology on $X\setminus\{b\}$.
Then, pick disjoint neighborhoods $U\ni a,V\ni b$, and note that $f^{-1}(f(U))=U\cup\{b\}$. This set is not open; for, if it were open, then there would be a neighborhood of $b$--call it $W$--contained in $U\cup\{b\}$. So, $\{b\}=(W\cap V)\cap(U\cup\{b\})$ is open, a contradiction.
Answer: Consider a space with three points $a,b,c$ and open sets
$\varnothing, \{a\},\{a,b\},\{a,b,c\}$. The projection that identifies $a$ and $c$ is not open (or closed, for that matter.)
Comment: What does it mean for a projection to identify points?
Comment: @Muno I mean the map  $\{a,b,c\}\to \{0,1\}$ that assigns $a$ and $c$ to $1$ and $b$ to $0$, and where $\{0,1\}$ is given the quotient topology.
Answer: Partition $X=ℝ$ (under the usual topology) into two equivalence classes $(-\infty, 0]$ and $(0,\infty)$ to get a two-point quotient space $X'$ (called the Sierpiński space) and let $q:X\to X'$ be the canonical projection mapping that takes each element of $ℝ$ to its equivalence class.  Then $q$ is a quotient mapping that satisfies $q^{-1}(q((-\infty,0)))=(-\infty,0]$.
Answer: An open map is:
for any open set in the domain, its image is open
A quotient map only requires:
for any open preimage in the domain, its image is open
A quotient map may not be an open map because there may exist a set such that it is open but is not a preimage, i.e., the preimage of the image of an open set may not be the open set itself.


taking the contrapositive of this statement?

Question: Statement: If every right triangle has angle defect equal to zero then the angle defect of every triangle is equal to zero
Taking the contrapositive do i have this correct? : There exists at least one triangle whose angle defect is not zero such that not every right triangle has an angle defect equal to zero.
Answer: You're close. It should be:

If there exists at least one triangle whose angle defect is not zero then there exists a right triangle whose angle defect is not zero.
Answer: You are close: but you need to replace "such that" to indicate implication: If -then...So you could correctly write:

If there exists at least one triangle whose angle defect is not zero, then not every right triangle has an angle defect that is equal to zero.

since "not every right triangle has an angle defect equal to zero" is equivalent to "there exists a right triangle whose angle defect is not equal to zero".
Comment: If you were to write a proof of your original statement, using proof by contradiction, yes, exactly!
Comment: but the contrapositive requires "then there exists a right triangle whose angle defect is not equal to zero."
Comment: one last thing. For contradiction would it be "Assume to the contrary that there exists a triangle whose angle defect is not equal to zero?"
Comment: This deserves a thumbs up! +1
Comment: user60887 - does this help?


Nested for-loop, searching files

Question: I have two files:
filetest.txt
============
SSISPACKAGE1.dtsx
SSISPACKAGE2.dtsx
SSISPACKAGE3.dtsx
SSISPACKAGE4.dtsx
SSISPACKAGE5.dtsx
SSISPACKAGE6.dtsx
SSISPACKAGE7.dtsx
SSISPACKAGE8.dtsx

filetest2.txt
=============
\\central_test_server\SSIS_Packages\Daily.bat
\\central_test_server\SSIS_Packages\Weekly.bat
\\central_test_server\SSIS_Packages\Monthly.bat
\\central_test_server\SSIS_Packages\Quarterly.bat
\\central_test_server\SSIS_Packages\SemiAnnually.bat
\\central_test_server\SSIS_Packages\Annually.bat

What I need is to cycle through filetest.txt, then search the files identified in
filetest2.txt for the filename and output to a file the results.  I am trying to identify in well over 100 bat files where each of about 100 SSIS Packages are running.
I'm doing this in Windows batch, have tried about 20 various approaches without success - any help would be greatly appreciated.
Comment: what do you mean with `identify`? Can't find a link pattern between the files.
Answer: The following command search the strings contained in filetest.txt in each one of the files contained in filetest2.txt:
findstr /G:filetest.txt /F:filetest2.txt

EDIT: Example added
I first created four text files with the help text for set, for, cmd e if commands, then I executed the example below (the language of my OS is Spanish):
C:> type wordList.txt
retardada
entorno

C:> type fileList.txt
set.txt
for.txt
cmd.txt
if.txt

C:> findstr /G:wordlist.txt /F:filelist.txt
set.txt:Muestra, establece o quita las variables de entorno de cmd.exe.
set.txt:  variable  Especifica el nombre de la variable de entorno.
set.txt:Escriba SET sin parámetros para ver las variables de entorno actuales.
set.txt:de la variable en el entorno actual.
set.txt:que no sea numérica, se tratará como variable de entorno cuyo valor se
set.txt:que no está definida en el entorno actual, se usará el valor cero. Esto
set.txt:permite hacer operaciones aritméticas con los valores de variables de en
torno
set.txt:de asignación requiere un nombre de variable de entorno a la izquierda d
el
set.txt:La sustitución de variables de entorno ha sido mejorada así:
set.txt:expandirá la variable de entorno PATH, sustituyendo cada repetición de
set.txt:expandirá la variable de entorno PATH, y usará solo los 5 caracteres
set.txt:de entorno agregado al desplazamiento o longitud especificados.
set.txt:retardada. Esta compatibilidad está siempre deshabilitada de forma
set.txt:La expansión de la variable de entorno es útil para tratar con las
set.txt:La expansión de la variable de entorno retardada permite usar un
set.txt:tiempo de ejecución.  Si la expansión de la variable retardada está
set.txt:dinámicas de entorno que se pueden expandir pero que no se
for.txt:    enumerará los nombres de variable de entorno en el entorno actual.
for.txt:                   de entorno de PATH y expande %I al nombre totalmente
for.txt:                   de la variable de entorno no es definido o no se
for.txt:                   entorno de PATH para %I y se expande a la letra de
cmd.txt:/V:ON   Habilita la extensión de variables de entorno retardada con !
cmd.txt:/V:OFF  Deshabilita la extensión de variables de entorno retardada.
cmd.txt:La expansión de variables de entorno retardada NO está habilitada de for
ma
cmd.txt:entorno retardada para una invocación particular de CMD.EXE con los
cmd.txt:retardada para todas las invocaciones de CMD.EXE en una sesión de inicio
 de
cmd.txt:Si la expansión de variables de entorno retardada está habilitada, se pu
ede
cmd.txt:entorno en tiempo de ejecución.
if.txt:nombre de variable de entorno y vuelve como verdadero si se define la
if.txt:variable de entorno.
if.txt:de ERRORLEVEL, siempre y cuando no exista ya una variable de entorno con
el
if.txt:variable de entorno con el nombre CMDCMDLINE, en cuyo caso obtendrá su va
lor.
if.txt:actual CMDEXTVERSION, siempre y cuando no exista ya una variable de entor
no

The output include the name of each file the search pattern was found in; if /N switch is added, the output also include the number of each line where the search pattern was found in.
Comment: The search pattern is in filetest.txt, the files to search are in filetest2.txt.  What is posted was the first thing I did and did indeed get results, but could not surmise which files the search pattern was found in, only that it was found.
Comment: `findstr` output _do_ show the file names where the search patterns was found! See the edit in my answer above. Please, explain your concerns in a clearer way and don't use confusing terms (like "identify" that I still don't know what means).
Comment: When I run what you have above, I do not get the filename where the string was found (ie, for.txt:), just the text that was found on the particular line.  What you have above is exactly what I'm looking for, but can not get it with even the simplest command, as you've outlined.  I have done the usage of the /M switch as well with this command, but get only the filenames and not which string was found in them.
Comment: More Info, in cmd window, I put 'ver' and received:  Microsoft Windows [Version 6.1.7601]
Comment: Type `findstr /?` and check if the displayed help includes /F and /G switches
Answer: @ECHO OFF
SETLOCAL
(
 FOR /f "delims=" %%a IN (filetest.txt) DO (
  ECHO ===================== looking FOR %%a =====================
  FOR /f "delims=" %%s IN (filetest2.txt) DO (
   FINDSTR /m /i /l /c:"%%a" "%%s"
  )
 )
)>newfile.txt
GOTO :EOF

This should produce a file newfile.txt containing the required data.
If the real data in filetest.txt contains strings that are conducive to being a filename, then
@ECHO OFF
SETLOCAL
FOR /f "delims=" %%a IN (filetest.txt) DO (
 FOR /f "delims=" %%s IN (filetest2.txt) DO (
  FINDSTR /m /i /l /c:"%%a" "%%s"
 )
)>"%%a.new"
GOTO :EOF

may be preferred.

Nested for-loop, searching files


Retrieving last record of a table inside inner join

Question: I have these three tables:
products
+----+--------+
| id | QRCode |
+----+--------+
|  1 | 1000   |
|  2 | 1001   |
+----+--------+

prices
+----+---------+------------+
| id | price   | product_id |
+----+---------+------------+
|  2 | $100001 |          1 |
|  3 | $100002 |          1 |
|  4 | $90001  |          2 |
|  5 | $90002  |          2 |
+----+---------+------------+

colors
+----+--------+-------------+
| id | color  | product_id  |
+----+--------+-------------+
|  1 | ffffff |           1 |
|  2 | f2f2f2 |           1 |
|  4 | aaaaaa |           2 |
|  5 | a3a3a3 |           2 |
+----+--------+-------------+

I would like to merge these three in a way that returns:

group_concat colors based on product_id
retrieves last record of each grouped price

This is the desired output:
+--------+----------------+-------------+-------------+
| QRCode |    colors      |    price    | product_id  |
+--------+----------------+-------------+-------------+
|  1000  | ffffff, f2f2f2 |   $100002   |      1      |
|  1001  | aaaaaa, a3a3a3 |   $90002    |      2      |
+--------+----------------+-------------+-------------+

Things I tried:
The query below returns product_id of last record of each grouped price
SELECT product_id FROM price where id IN
                                        (SELECT max(id) FROM price
                                         GROUP BY product_id)

Then I tried to put query above in this query as a subquery
SELECT products.QRCode, priceSubQ.price, GROUP_CONCAT(colors.color) as colors FROM products
INNER JOIN colors on colors.product_id = products.id
INNER JOIN ( /* I put query above here */ ) as priceSubQ ON priceSubQ.product_id = products.id
GROUP BY products.id

What am I doing wrong?
Comment: Try `ORDER BY` in conjunction with `DESCEND` and then `LIMIT`
Comment: Tip: Don't store '$'
Comment: @ansi_lumen could you explain it in more detail?
Comment: @Strawberry I Don't, thought it would help better understand my question
Comment: @Sajad It doesn't. See: [Why should I provide an MCVE for what seems to me to be a very simple SQL query?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query)
Answer: I came across this link which helped me understand the problem
Changed inner query to:
SELECT product_id FROM ANY_VALUE(price) where id IN
                                    (SELECT max(id) FROM price
                                     GROUP BY product_id) group by product_id

solved my problem.
Answer: Something like the following should work (not tested)..
SELECT
    products.QRCode,
    priceSubQ.price,
    GROUP_CONCAT(colors.color) as colors
FROM
    products
    LEFT JOIN colors
        ON colors.product_id = products.id
    LEFT JOIN (
        SELECT
            MAX(p1.id) as p1maxId,
            p2.price AS price,
            p2.product_id AS product_id
        FROM
            prices p1
            INNER JOIN prices p2
                ON p1.p1maxId = p2.id
        GROUP BY
            p1.product_id
    ) AS priceSubQ
        ON priceSubQ.product_id = products.id
GROUP BY
    products.id

Comment: @J A I tested it... didn't work, couldn't retrieve last row of price table, found my answer, thanks anyway
Comment: @Sajad: Glad you found your solution. Why not post the solution it here so that others can benefit from it? Cheers


Display data fields based on checkbox selection in SAP ABAP

Question: Below is simple code where I want to display location based on checkbox selection.
Eg: id p_pune is selected at seletion screen then after WRITE command my output should be as below
EMPID  NAME  LOCATION
 1       A     PUNE

Code:
TYPES: BEGIN OF ty_emp,
       empid TYPE i,
       name TYPE char5,
       location TYPE char6,
  END OF ty_emp.

  DATA: wa_emp TYPE ty_emp,
        it_emp TYPE TABLE OF ty_emp.

  DATA: gd_ucomm TYPE sy-ucomm.

  wa_emp-empid = 1.
  wa_emp-name = 'A'.
  wa_emp-location = 'Pune'.
  append wa_emp to  it_emp.

CLEAR wa_emp.
   wa_emp-empid = 2.
  wa_emp-name = 'B'.
  wa_emp-location = 'Mumbai'.
append wa_emp to  it_emp.

CLEAR wa_emp.
  wa_emp-empid = 3.
  wa_emp-name = 'C'.
  wa_emp-location = 'Delhi'.
append wa_emp to  it_emp.

CLEAR wa_emp.
  wa_emp-empid = 4.
  wa_emp-name = 'D'.
  wa_emp-location = 'Noida'.
  append wa_emp to  it_emp.

CLEAR wa_emp.

PARAMETERS: p_pune AS CHECKBOX USER-COMMAND c1,
            p_mumbai AS CHECKBOX USER-COMMAND c2,
            p_delhi AS CHECKBOX USER-COMMAND c3,
            p_noida AS CHECKBOX USER-COMMAND c4.

Comment: It's not clear what issue you have. Is it about how to use `IF`, how to use the debugger, etc. ? Please show what you tried, and ask a question about a precise problem. Have a [tour](https://stackoverflow.com/tour) to see how to ask questions. Thank you.
Answer: You can try this:
IF p_pune = abap_true.

  READ TABLE it_emp INTO wa_emp INDEX '1'.

  WRITE:/ wa_emp-empid, wa_emp-name, wa_emp-location.

ENDIF.

IF p_mumbai = abap_true.

  READ TABLE it_emp INTO wa_emp INDEX '2'.

  WRITE:/ wa_emp-empid, wa_emp-name, wa_emp-location.

ENDIF.

IF p_delhi = abap_true.

  READ TABLE it_emp INTO wa_emp INDEX '3'.

  WRITE:/ wa_emp-empid, wa_emp-name, wa_emp-location.

ENDIF.

IF p_noida = abap_true.

  READ TABLE it_emp INTO wa_emp INDEX '4'.

  WRITE:/ wa_emp-empid, wa_emp-name, wa_emp-location.

ENDIF.

When you check multiple checkboxes, it will display multiple locations.
If you want to display only one location, I suggest you use RADIO BUTTON instead of CHECKBOX.
Comment: Will it work for more then 2 records of same location? Thanks in advance
Comment: Did not quite understand your question. You want to display multiple locations for the same checkbox , or multiple checkboxes to display the same location? For both questions the answer is yes.
Answer: You could convert the boolean values of the parameters to a location, using the COND statement. Then you can loop over the internal table with LOOP AT and use it's WHERE condition to filter out the location you need.
TYPES:
  BEGIN OF employee,
    empid    TYPE i,
    name     TYPE char5,
    location TYPE char6,
  END OF employee,
  employees TYPE STANDARD TABLE OF employee WITH EMPTY KEY.

DATA(employees) = VALUE employees(
  ( empid = 1 name = 'A' location = 'Pune'   )
  ( empid = 2 name = 'B' location = 'Mumbai' )
  ( empid = 3 name = 'C' location = 'Dehli'  )
  ( empid = 4 name = 'D' location = 'Noida'  )
).

PARAMETERS: pune   AS CHECKBOX,
            mumbai AS CHECKBOX,
            dehli  AS CHECKBOX,
            noida  AS CHECKBOX.

START-OF-SELECTION.

DATA(wanted_location) = COND char6(
  WHEN pune   = abap_true THEN 'Pune'
  WHEN mumbai = abap_true THEN 'Mumbai'
  WHEN dehli  = abap_true THEN 'Dehli'
  WHEN noida  = abap_true THEN 'Noida'
).

LOOP AT employees INTO DATA(employee)
  WHERE location = wanted_location.

  WRITE:
    employee-empid,
    employee-location,
    employee-name.

  NEW-LINE.
ENDLOOP.


FullCalendar não aparece barra de navegação

Question: Estou usando o plugin FullCalendar, ele lista eventos corretamente mas somente não exibe a barra de navegação. no console não aparecem erros de javascript. Olhando o Inpecionar Elemento observei que os botões são gerados mas ainda sim ficam invisiveis.
Não encontrei nenhum erro no css, em conjunto estou utilizado o tema bootstrap Admin Light Dashboard da Creative Tim.
Se alguém puder dar uma força agradeço.
$(document).ready(function() {
    $('#calendar').fullCalendar({
        header: {
            left: 'title',
            center: 'month,agendaWeek,agendaDay',
            right: 'prev,next,today'
        },
        defaultDate: '2017-11-12',
        navLinks: true, // can click day/week names to navigate views
        editable: true,
        eventLimit: true, // allow more link when too many events
        events: [
            {
                title: 'All Day Event',
                start: '2017-11-01',
            },
            {
                title: 'Long Event',
                start: '2017-11-07',
                end: '2017-11-10'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2017-11-09T16:00:00'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2017-11-16T16:00:00'
            },
            {
                title: 'Conference',
                start: '2017-11-11',
                end: '2017-11-13'
            },
            {
                title: 'Meeting',
                start: '2017-11-12T10:30:00',
                end: '2017-11-12T12:30:00'
            },
            {
                title: 'Lunch',
                start: '2017-11-12T12:00:00'
            },
            {
                title: 'Meeting',
                start: '2017-11-12T14:30:00'
            },
            {
                title: 'Happy Hour',
                start: '2017-11-12T17:30:00'
            },
            {
                title: 'Dinner',
                start: '2017-11-12T20:00:00'
            },
            {
                title: 'Birthday Party',
                start: '2017-11-13T07:00:00'
            },
            {
                title: 'Click for Google',
                url: 'http://google.com/',
                start: '2017-11-28'
            }
        ]
    });

});

Comment: Poste o código para obter maior ajuda!
Answer: Estás a incluir as libs necessárias? Verifica abaixo.

$(document).ready(function() {
$('#calendar').fullCalendar({
        header: {
            left: 'title',
            center: 'month,agendaWeek,agendaDay',
            right: 'prev,next,today'
        },
        defaultDate: '2017-11-12',
        navLinks: true, // can click day/week names to navigate views
        editable: true,
        eventLimit: true, // allow more link when too many events
        events: [
            {
                title: 'All Day Event',
                start: '2017-11-01',
            },
            {
                title: 'Long Event',
                start: '2017-11-07',
                end: '2017-11-10'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2017-11-09T16:00:00'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2017-11-16T16:00:00'
            },
            {
                title: 'Conference',
                start: '2017-11-11',
                end: '2017-11-13'
            },
            {
                title: 'Meeting',
                start: '2017-11-12T10:30:00',
                end: '2017-11-12T12:30:00'
            },
            {
                title: 'Lunch',
                start: '2017-11-12T12:00:00'
            },
            {
                title: 'Meeting',
                start: '2017-11-12T14:30:00'
            },
            {
                title: 'Happy Hour',
                start: '2017-11-12T17:30:00'
            },
            {
                title: 'Dinner',
                start: '2017-11-12T20:00:00'
            },
            {
                title: 'Birthday Party',
                start: '2017-11-13T07:00:00'
            },
            {
                title: 'Click for Google',
                url: 'http://google.com/',
                start: '2017-11-28'
            }
        ]
    });
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.3.0/fullcalendar.min.css" rel="stylesheet"/>

Comment: Os links não funcionaram, mas sua ajuda me abriu os olhos para revisar o CSS do FullCalendar. Adicionei a propriedade display:block e tudo voltou ao normal.


Does dust hurt acoustic guitar?

Question: I usually play guitar regularly, and I always put it on its stand but sometimes due to college work I can't play for a few weeks in between. And what happens is a layer of dust accumulates on my guitar. Does dust hurt acoustic guitar? Its wood the sound? Any things I should be worried about?
Comment: I'd be more concerned about children or animals knocking it off. Or direct sunlight on it for hours. Once it's in its case, there's no need to dust or polish it before playing. Dust won't affect it, but why leave it out? How much effort is involved in using the case? Does it even have a case? If not, why not?
Comment: If you care about your guitar,  you won't think of keeping it in the gig bag as "inconvenient."  There are lots more things than just dust to worry about, such as solarization,   things getting dropped on it,  spilling a beer on it,....
Comment: I don't have children or animals in the house nor is it located where direct sunlight shines. I have a gig bag, but I leave it on the stand next to my study desk because I don't like the idea of putting away the guitar, even if I'm taking a break from it. Furthermore, putting it in the gig bag and getting it out can be quite inconvenient (Since I've put the gig bag in a plastic bag to avoid it accumulating dust as well, I'd have no idea how to clean it). But I take it that your answer is that, dust does not affect acoustic guitar?
Comment: I think someone who talks of spilling "a" beer, or  their primary concern is not dropping anything on the instrument. (being reckless enough to bring fluids or carry things recklessly around the instrument) don't get to talk about other people's "care" for theirs. If you are not going to be helpful and divert from the original question please don't comment at all. Thank you.
Answer: No - a bit of dust is not one of the things that will damage the guitar or affect the sound. Even if you left it sitting in a dusty house for years, and built up a thick layer of dust, I'd still be more concerned about humidity changes, temperatures, sunlight as @Tim mentioned etc.
Most of my guitars are not in cases (I do not have enough room to store them all in cases, so they are all on stands or hanging on walls) and all I do is brush off the dust if I come to play one I haven't picked up for a few weeks.
Comment: The problem for me isn't the guitars - all over seven walls - but their cases! The loft is literally full of them - along with several keyboard cases, spare amps, extra drums, etc. etc. Need to find a better storage idea... +1.
Comment: Yup - I have them in the attic and under beds. At least most of my amps and cabs are in the garage, my music room, and my daughter's room... But that's a good problem, right :-)
Comment: It's when your daughter keeps asking 'Dad, does every little girl have to sleep on 2 4x12s, or am I just special?'
Comment: Hahahahaha - in that case tell her she is very special and privileged :-)
Comment: @Tim  build a wall-sized box with giant glass doors & hang all your axes in that!
Comment: @DoktorMayhem, your answer is exactly what I was searching for endlessly. Thank you.

Does dust hurt acoustic guitar?


NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/internal/zzcce

Question: My project builds just fine, but when I try to run it, it runs but I get this error on the debugger terminal. Does anyone know how to fix it?
Error:
java.util.concurrent.ExecutionException: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/internal/zzcce;

build.gradle:
implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
    implementation 'com.android.support:design:28.0.0-alpha3'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.0'
    implementation 'com.google.android.gms:play-services-maps:+'
    implementation 'com.google.android.gms:play-services:+'
    implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
    implementation 'com.google.firebase:firebase-auth:+'
    implementation 'com.google.android.gms:play-services-auth:+'

Comment: I would suggest: 1. Include specific version of dependencies instead of using '+'.  2. Instead of using alpha versions, use stable ones.
Comment: The alphas came by default, I didn't add them, do you know the current versions?
Answer: Add this to your project build.gradle:
dependencies {
    classpath 'com.android.tools.build:gradle:3.1.2'
}

Comment: Version doesn't matter, I was saying make sure you add this in your project `build.gradle`


sqlite3, fmdb, build is failed

Question: I'm using sqlite3, fmdb glad to know that, but try to use, build upon get errors. I do not know why. Gcc4.2 compilation options are used. (or LLVM GCC4.2). I need a good solution.
Comment: Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 failed with exit code 1
Answer: For those of you that might have this problem. Remove fmdb.m from your project and it will compile fine.

sqlite3, fmdb, build is failed


Which strings should I use for DADGAD tuning on my acoustic guitar?

Question: I have recently switched to DADGAD tuning, before that I was using light tension strings ( 12 16 24 32 42 53 ).
But because of DADGAD, to compensate for the lack of tension on the neck, I wanted to switch to a mix of medium and light strings, puting higher tension strings on the ones that are lowered, resulting in ( 13 17 24 32 42 56 ), some friends playing DADGAD even used 14 and 18 for the two higher strings.
I wondered what you DADGAD players used?
And of course the economic side of it, buying one light set and one medium set and throwing away half the strings is not a very good solution, do you have any DADGAD-ready set to recommend?
Comment: I don't think we need a specific DADGAD tag at the moment, if we get more questions on this I'll be sure to add it back.
Answer: If you would like to get scientific about it, the D'Addario company has a chart discussing string tension and tuning and string gauges for alternate tuning schemes.
http://daddario.com/DAstringtensionguide.Page?ActiveID=2681
You can also download this PDF which explains the recommended tuning, pitches and tensions for every type and gauge of individual string that they sell.
http://www.daddario.com/upload/tension_chart_13934.pdf
D'Addario also sells a packaged set for acoustic guitar designed for DADGAD.
D'Addario Acoustic Guitar Phosphor Bronze True Medium DADGAD Tuning .013 - .056, EJ24

                     Diameter        Tension
                   -------------   ------------
    Item#   Note   Inches   Mm     Lbs    Kg
    -------------------------------------------
    PL013   E      0.013    0.33   27.4   12.42
    PL017   B      0.017    0.43   26.3   11.91
    PB024   G      0.024    0.61   30.2   13.38
    PB032   D      0.032    0.81   30.5   13.83
    PB042   A      0.042    1.07   29,9   13.56
    PB056   E      0.056    1.42   29.0   13.15
Comment: That link is dead but the set is still available here: https://www.daddario.com/products/guitar/acoustic-guitar/phosphor-bronze/ej24-phosphor-bronze-acoustic-guitar-strings-true-medium-13-56/ Also, the table here shows tension figures for EADGBE tuning where DADGAD tension figures would be more useful.  The new string tension calculator gives me (high to low) 21.76  20.89  30.06  29.93  28.93  22.03 (lbs)
Answer: This is obviously an extremely old post, but still worth answering for anyone who might be reading as this question still comes up when you Google "DADGAD strings":
A lot of players do play just fine with a normal set of standard 12s or 13s tuned to DADGAD (11s tuned down might feel a too floppy for an acoustic player, and I've found them a little more liable to break when strumming with a pick, and have never had any issue like that on 12s).
However, preselected sets tailor-made for DADGAD have become a bit more common, so you don't need to go out a create a custom set which can be more expensive, or worse, throw out a whole pack's worth of strings, which is the worst case scenario imo.
D'addario make a set of their regular phosphor bronze acoustic strings especially for DADGAD, called EJ24. Given how widespread the brand is, these seem to be quite readily available in music stores despite being a bit niche.
https://www.daddario.com/products/guitar/acoustic-guitar/phosphor-bronze/ej24-phosphor-bronze-acoustic-guitar-strings-true-medium-13-56/
The only other brand I see making them are these by Lowden, though I have no experience using them so I don't know what they're like.
https://shop-gb.lowdenguitars.com/products/lowden-strings-dadgad-13-56
Couldn't find many other similar sets out there myself, but I'm sure a few other brands may do them.
Comment: Any idea for a set for electric guitar?
Answer: When I played in DADGAD tuning, it was one of several tunings I would use, so it never crossed my mind to use different strings.  But if this is something you want to do, I'd suggest constructing your own custom set with single strings rather than buying two sets and discarding the extra strings.
Just Strings sells individual strings from a variety of manufacturers.  Maybe you can find the brand you like in this list from their site.
Comment: Try StringBusters.com in the UK
Comment: this is great link, Their prices are good too, and they sell single Elixir strings! Unfortunately, the shipment cost for Europe (40$) is prohibitive...