How do I require that a class into which a model is included implements certain methods?

Question: I have a Module named Coordinated that provides distance related methods to any model that implements the latitude and longitude methods.
module Coordinated
  ...
  def crow_flies_to(place)
    raise ArgumentError, "place does not implement latitude and longitude" unless is_coordinated?(place)
    Math.sqrt((latitude - place.latitude).abs**2 + (longitude - place.longitude).abs**2)
  end

  def is_coordinated?(place)
    place.respond_to?(:latitude) && place.respond_to?(:longitude)
  end
  ...
end

I'd like to test that classes into which Coordinated is included implement the required methods when the class is loaded. How do I do that?
Answer: You can use the included hook that runs when a module is included:
module M
  def self.included(klass)
    raise "Must implement 'foo'" unless klass.instance_methods.include?(:foo)
  end
end

class C; include M; end
#=> RuntimeError

class C
  def foo; end
  include M
end
#=> C

This has the drawback that the inclusion must happen after the methods are defined, since they must already exist when the hook runs.
Comment: This also means that you cannot use this mixin with objects which transparently delegate that functionality to another object instead of implementing it themselves. Which, of course, is powerful technique in object-oriented programming. In fact, depending on who you ask, the inability to distinguish between performing functionality yourself and delegating it to someone else is the *definition* of object-orientation. IOW: this solution makes it impossible to use object-orientation.
Comment: @JörgWMittag Oh I agree and think that doing this is a pretty nasty idea in the first place. A module shouldn't have to care if a method is implemented till it tries to use it. This will also break for things like methods that exist only via `method_missing`.


Precisão numérica no SQLite

Question: Sobre a precisão numérica no SQLite v3.20.0.
Veja a sequência de comandos abaixo e o resultado do .dump. O valor associado à declaração INSERT não é o mesmo valor obtido.
Insiro o valor 123456.789 e obtenho 123456.7890000000043. Como pode isso ocorrer?
<code>SQLite version 3.20.0 2017-08-01 13:24:15
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> CREATE TABLE Teste (Campo Number(9,3));
sqlite> INSERT INTO Teste Values (123456.789);
sqlite> SELECT * From Teste;
123456.789
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE Teste (Campo Number(9,3));
INSERT INTO Teste VALUES(123456.7890000000043);
COMMIT;
sqlite>
</code>
Answer: A matemática de ponto flutuante binário é assim. Na maioria das linguagens de programação (não somente no SQLLite), ele é baseado no padrão IEEE 754. Por exemplo, o JavaScript usa a representação de ponto flutuante de 64 bits, que é o mesmo que o dobro de Java. O ponto crucial do problema é que os números são representados neste formato, uma vez que um número inteiro tem uma potência de dois; números racionais (como 0,1, que é 1/10) cujo denominador não é uma potência de dois, não podem ser exatamente representados.
Seguem as referências: Wiki - Representação Binária de Float
Comment: Nestes casos o melhor é tratar sem casas decimais, ou seja sempre como inteiro, e no momento de exibir o dados, faz a divisão, incluindo as casas decimais que deseja. Ex: 123,45 = 12345/100
Comment: Mais Tem Como resolver isso?

Precisão numérica no SQLite


Easiest way to parse "querystring" formatted data

Question: With the following code:
string q = "userID=16555&gameID=60&score=4542.122&time=343114";

What would be the easiest way to parse the values, preferably without writing my own parser?  I'm looking for something with the same functionality as Request.querystring["gameID"].
Answer: Pretty easy... use the HttpUtility.ParseQueryString method.
Untested, but this should work:
var qs = "userID=16555&gameID=60&score=4542.122&time=343114";
var parsed = HttpUtility.ParseQueryString(qs);
var userId = parsed["userID"];
//  ^^^^^^ Should be "16555".  Note this will be a string of course.

Comment: Thanks!  Looks good, I'm having trouble decoding the horrible example they provided on the MSDN page though, once I have `var q = HttpUtility.ParseQueryString("?userID=16555&gameID=60&score=4542.122&time=343114");` how do I retrieve a specific value?
Comment: I can't find System.Net.HttpUtility net Core 1.0 framework
Comment: Seems like they removed it. Reference the answer here for a solution: http://stackoverflow.com/questions/29992848/parse-and-modify-a-query-string-in-net-core
Comment: The [Nancy](http://nancyfx.org/) library also includes `Nancy.Helpers.HttpUtility.ParseQueryString`.
Comment: Note that `ParseQueryString` fails is there is more than 1024 key-value pairs in the string.
Comment: @GSerg if you've got 1025 keys in a query string, I'd argue that you've got bigger problems
Comment: @ChrisShain Well, there is e.g. one Paypal API that returns transactions data as a huge url-encoded string of key-value pairs. It easily exceeds 1024.
Answer: You can do it  with linq like this.
string query = "id=3123123&userId=44423&format=json";

Dictionary<string,string> dicQueryString =
        query.Split('&')
             .ToDictionary(c => c.Split('=')[0],
                           c => Uri.UnescapeDataString(c.Split('=')[1]));

string userId = dicQueryString["userID"];

Edit
If you can use HttpUtility.ParseQueryString then it will be a lot more straight forward and it wont be case-sensitive as in case of LinQ.
Comment: And what happens when you have a query string like `a=1&a=2&a=3`? That is valid, as is `a=1;a=2;a=3`. Use `HttpUtility.ParseQueryString`. It handles these and other oddities.
Comment: This is a good solution if you need to parse query strings outside of the System.Web context.
Comment: That works in this specific case, but it's not a generic solution because it doesn't do percent-decoding.
Comment: Right @Francis Avila, then it will need more modification in query.
Comment: This preserves case, unlike ParseQueryString.
Comment: I came here because HttpUtility.ParseQueryString() performed the decoding. this solution here works for me.
Comment: @JimMischel to `.ToLookup` rather than `.ToDictionary` to handle "duplicate keys"
Answer: As has been mentioned in each of the previous answers, if you are in a context where you can add a dependency to the System.Web library, using HttpUtility.ParseQueryString makes sense.  (For reference, the relevant source can be found in the Microsoft Reference Source).  However, if this is not possible, I would like to propose the following modification to Adil's answer which accounts for many of the concerns addressed in the comments (such as case sensitivity and duplicate keys):
var q = "userID=16555&gameID=60&score=4542.122&time=343114";
var parsed = q.TrimStart('?')
    .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(k => k.Split('='))
    .Where(k => k.Length == 2)
    .ToLookup(a => a[0], a => Uri.UnescapeDataString(a[1])
      , StringComparer.OrdinalIgnoreCase);
var userId = parsed["userID"].FirstOrDefault();
var time = parsed["TIME"].Select(v => (int?)int.Parse(v)).FirstOrDefault();

Comment: Ignores single item arguments, which can sometimes also appear: `arg1&arg2&arg3`
Answer: If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the Uri extension method ParseQueryString found in System.Net.Http.
Note that you have to convert the response body to a valid Uri so that ParseQueryString works.
Please also note in the MSDN document, this method is an extension method for the Uri class, so you need reference the assembly System.Net.Http.Formatting (in System.Net.Http.Formatting.dll). I tried installed it by the nuget package with the name "System.Net.Http.Formatting", and it works fine.
string body = "value1=randomvalue1&value2=randomValue2";

// "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
string urlBody = "http://localhost/query?" + body;
NameValueCollection coll = new Uri(urlBody).ParseQueryString();

Comment: I did, I ended up just writing my own parser.
Comment: Not sure this works...Uri doesn't have a ParseQueryString method attached to it when I try this, my code:

var collection = new System.Uri(url).ParseQueryString();
Comment: @TrevorHart Did you make sure to add a reference to System.Net.Http and to add the System.Net.Http namespace?
Answer: How is this
using System.Text.RegularExpressions;

// query example
//   "name1=value1&name2=value2&name3=value3"
//   "?name1=value1&name2=value2&name3=value3"
private Dictionary<string, string> ParseQuery(string query)
{
    var dic = new Dictionary<string, string>();
    var reg = new Regex("(?:[?&]|^)([^&]+)=([^&]*)");
    var matches = reg.Matches(query);
    foreach (Match match in matches) {
        dic[match.Groups[1].Value] = Uri.UnescapeDataString(match.Groups[2].Value);
    }
    return dic;
}

Comment: Thanks!! Does it support single item arguments, as metioned by @jsuddsjr 's comment above?  _Ignores single item arguments, which can sometimes also appear: `arg1&arg2&arg3`_
Answer: For .NET Core there is Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery
var queryString = QueryHelpers.ParseQuery("?param1=value");
var queryParamValue = queryString["param1"];

Code snippet modified from trackjs.com:
Answer: System.Net.Http ParseQueryString extension method worked for me. I'm using OData query options and trying to parse out some custom parameters.
options.Request.RequestUri.ParseQueryString();

Seems to give me what I need.
Answer: HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:
// NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(queryString);

NameValueCollection nameValueCollection = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
   string[] parts = segment.Split('=');
   if (parts.Length > 0)
   {
      string key = parts[0].Trim(new char[] { '?', ' ' });
      string val = parts[1].Trim();

      nameValueCollection.Add(key, val);
   }
}


Spindump analysis instructions?

Question: I have a collection of spindumps focused on an app that need to be analyzed, however I'm not sure precisely how to analyze these.  I've seen some other developers who are able to quickly parse these either mentally or with software and come back to me with details on where hangs are coming to play and so forth and I'm hoping to understand how to properly analyze these.
Where does one go to properly analyze spindumps?
Comment: [Re: Useful Sampling results with no Symbols?](https://groups.google.com/d/msg/perfoptimization-dev/QmUB0Nd5asM/5EqAHC144wQJ) – Google Groups view of [a 2011 post to Apple's PerfOptimization-dev mailing list](http://lists.apple.com/archives/perfoptimization-dev/2011/Mar/msg00014.html).
Comment: I'm not a developer, but I often see people like me wondering about spindump analysis – hence the recent bounty.
Answer: Generally:

with a crash report, you get a stack trace
with spindumps, you get multiple stack traces over a period of time together.

There are two cases in which you might want to examine a spindump:

an infinite loop, probably calling the same function over and over
deadlock.

The first case can be seen from the spindump by many calls to the same function over and over. A good thing to use in such situations is Activity Monitor – take sample of a hung process there and you can view it in several useful ways, hiding unimportant frames, etc.
The second case can be viewed by different threads waiting on locks at the same time.
Here is a little example:
+ 2663 start  (in MyApp) + 52  [0x100001bb4]
+   2663 main  (in MyApp) + 39  [0x100001be7]  main.m:65
+     2663 NSApplicationMain  (in AppKit) + 869  [0x7fff8ea27cb6]
+       2663 -[NSApplication run]  (in AppKit) + 517  [0x7fff8ea83283]
+         2663 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]  (in AppKit) + 128  [0x7fff8ea8bed2]
+           2663 _DPSNextEvent  (in AppKit) + 685  [0x7fff8ea8c613]
+             2663 BlockUntilNextEventMatchingListInMode  (in HIToolbox) + 62  [0x7fff8dd53cd3]
+               2663 ReceiveNextEventCommon  (in HIToolbox) + 356  [0x7fff8dd53e42]
+                 2663 RunCurrentEventLoopInMode  (in HIToolbox) + 209  [0x7fff8dd540a4]
+                   2663 CFRunLoopRunSpecific  (in CoreFoundation) + 290  [0x7fff95dec6b2]
+                     2557 __CFRunLoopRun  (in CoreFoundation) + 1078  [0x7fff95decee6]
+                     ! 2556 __CFRunLoopServiceMachPort  (in CoreFoundation) + 195  [0x7fff95de7803]
+                     ! : 2556 mach_msg  (in libsystem_kernel.dylib) + 70  [0x7fff93630c42]
+                     ! :   2556 mach_msg_trap  (in libsystem_kernel.dylib) + 10  [0x7fff93631686]
+                     ! 1 __CFRunLoopServiceMachPort  (in CoreFoundation) + 199  [0x7fff95de7807]
+                     97 __CFRunLoopRun  (in CoreFoundation) + 728  [0x7fff95decd88]
+                     ! 97 __CFRunLoopDoObservers  (in CoreFoundation) + 369  [0x7fff95e11921]
+                     !   97 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__  (in CoreFoundation) + 23  [0x7fff95e119b7]
+                     !     97 __83-[NSWindow _postWindowNeedsDisplayOrLayoutOrUpdateConstraintsUnlessPostingDisabled]_block_invoke_01208  (in AppKit) + 46  [0x7fff8f05a971]
+                     !       90 _handleWindowNeedsDisplayOrLayoutOrUpdateConstraints  (in AppKit) + 738  [0x7fff8ea8f2ac]
+                     !       : 89 -[NSView displayIfNeeded]  (in AppKit) + 1830  [0x7fff8ea8fd73]

What this tells me, is that MyApp has gone through main, etc. and finally got into a function CFRunLoopRunSpecific, then __CFRunLoopRun – from there (2557) it called __CFRunLoopServiceMachPort, which called mach_msg and got into a trap at mach_msg_trap (calling a syscall) – when it got back, the stack trace returned to CFRunLoopRunSpecific, where __CFRunLoopRun was called, which then calls __CFRunLoopDoObservers, and so on.
Note that this isn't a spindump of any hanging process - you can sample this way any running process and view what functions were called during that sample. An infinite loop, however, will have a repeating calls to some function over and over again - there will be the same call tree over and over again. Of course, this can mean a simple for cycle, but that's where you can examine, if the for cycle isn't for some reason infinite. Unfortunately, these spin dumps are usually quite long, depending on what function you are calling, so it may take some time to examine
The + sign at the beginning of the row simply indicates a beginning of a line - lines without the + sign indicate a beginning of a new thread. The ! and : signs make a line, so it's easier for you to see subsequent calls - i.e. which calls are at the same level. Further, | character can be also used.
The numbers mean how long the app spent in that particular call - they are in the number of samples. The sampling works that the sampled app gets suspended every few millisecond and the stack frame is examined of each thread. If the app is still in the same function, the function gets +1.
Comment: How do you interpret the numeric headers for each line?  What are the symbols indicative of (+, !, :)? Is there no software mechanism that you can pass these through that help parse these more meaningfully?  I am primarily dealing with odd hangs and am attempting to isolate where these hangs are coming from. This is extremely valuable to understand as intimately as possible, but presently given the time differential I'm slightly out of context. Your answer makes sense given your example; I feel there is still a missing piece to properly interpreting these when I run into the problem again. Hmm
Comment: For readers without a software development background: please, is the example of an infinite loop, or a deadlock?
Comment: The + sign simply indicates a beginning of a line - lines without the + sign indicate a beginning of a new thread. The ! and : signs simply make a line, so it's easier for you to see subsequent calls - i.e. which calls are at the same level. Further, | character can be also used. The numbers mean how long the app spent in that particular call - probably in milliseconds, but that's not important.
Comment: The example above is not from a hanging app at all, you can examine this way running apps to figure out how are they working. An infinite loop, however, will have a repeating calls to some function over and over again - there will be the same call tree over and over again. Of course, this can mean a simple for cycle, but that's where you can examine, if the for cycle isn't for some reason infinite. Unfortunately, these spin dumps are usually quite long, depending on what function you are calling, so it may take some time to examine.
Comment: OK, now with that clarification there's an upvote from me. @CharlieMonroe maybe edit some of this commentary into your answer, if it doesn't change the essence – thanks.
Comment: Side note: my edit to the answer introduced a possible typo – *spin dumps* where previously the one word was *spindumps*.
Answer: I found this when searching the Mac Developer Resources for 'spindump'.
I've never seen one, but this TechNote referred to in the ReportCrash(8) manual page seems to show you how to read crash logs:
https://developer.apple.com/library/mac/#technotes/tn2004/tn2123.html
And ReportCrash(8) referred to Spindump(8), my apologies.
https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man8/ReportCrash.8.html
But apparently this doesn't help you out. I'll leave it up here just as well.
Hope this helps someone out somehow.
Comment: That's useful for crashes but not for spindump. Apple's [spindump(8) OS X Manual Page](http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man8/spindump.8.html) does not refer to ReportCrash(8).
Comment: And, the spindump page only describes the utility to manually trigger the sampling, nothing about the output.

Spindump analysis instructions?


PHP, JWT passthrough path and method

Question: I'm building an application via slim framework and it's slim-jwt-auth middleware.
I installed it, and it works fine but I'm a bit confused with the passthrough possibility.
My RequestPathRule:
new \Slim\Middleware\JwtAuthentication\RequestPathRule([
            "path" => ["/api"],
            "passthrough" => ["/api/auth", "/api/users", "/api/products", "/api/orders", "/api/streets",
                              "/api/reservations", "/api/feedbacks", "api/menu"]
        ])

And my RequestMethodRule:
new \Slim\Middleware\JwtAuthentication\RequestMethodRule([
            "passthrough" => ["POST", "GET"]
        ])

But it allows these methods to all endpoints. Actually, I want to let POST only to /api/auth, /api/orders, /api/reservations and /api/feedbacks, and GET for every endpoint except /api/users.
How is this possible?
Thank you in advance.
Answer: It would be interesting to see which are your routes, but basically in your current configuration your are saying:
1) DON'T Authenticate "/api/auth", "/api/users", "/api/products", "/api/orders", "/api/streets",  "/api/reservations", "/api/feedbacks" and "api/menu" (rest of endpoints under /api MUST be authenticated)
2) AND also dont authenticate whatever POST or GET request
some examples:

PUT /api/users NEVER will be authenticate since /api/users is in
RequestPathRule
GET /api/users NEVER will be authenticate since /api/users is in
RequestPathRule AND GET is in RequestMehtodRule
PUT /api/whatever ALWAYS will be authenticate since /api/users is
NOT in RequestPathRule AND GET is NOT in RequestMethodRule

Basically rules work like an OR comparison operator and in the right moment an endpoint is in RequestPathRule OR a request method is in RequestMethodRule the request will be not authenticated.
A better approach could be trying not to use RequestMethodRule as much as possible (generally you just include OPTIONS method) and play with different paths.
In a normal web application you will provide a public API path to your clients under /api and the only endpoint you don't generally authenticate is /api/login (or /api/auth in your example) the rest of the endpoint under /api are authenticated. If your provide another set of endpoints which you don't want to authenticate you provide another different path like /service and your don't include it as "path" in RequestPathRule. If you need a set of endpoint ALL authenticated you create all of then under a new path, let's say /admin and you include on path in RequestPathRule and you don't add any "passthrough" for them.
So the idea is play with different path and just add those methods under RequestMethodRule for specific use cases. Moreover, in that way you will have a better clear and organized API.
Looking at your endpoints I recommend you create different path for most of them, so instead of having "/api/auth", "/api/users", "/api/products", "/api/orders" I would suggest you to have "/auth", "/user", "/product", "/order"... and you can add a RequestPathRule and RequestMethodRule for every path.
To be honest, as the slim-jwt-auth middleware is thought, it's difficult to provide CRUD operations over same endpoint, let's say you have GET, POST, PUT and DELETE over /user and you want just authenticate POST, PUT and DELETE. For that case you could have 2 options:

create differen endpoint for each verb like: GET /user/all, POST /user/add, PUT /user/edit and DELETE /user/delete (which is a bad practice
Create or extend your RequestPathRule and RequestMethodRule callable with the only conditions that they must implement RuleInterface and adapt them to your needs (highly recommended)

If you choose the 2nd option you only have to add those callable to the rules option. Something like this:
$app->add(new \Slim\Middleware\JwtAuthentication([
"rules" => [
    new \My\Auth\Rules\RequestPathRule([
        "path" => "/",
        "passthrough" => []
    ]),
    new \My\Auth\Rules\RequestMethodRule([
        "passthrough" => ["OPTIONS"]
    ])
]
]));

Comment: Agreed. #2 is the best solution.

PHP, JWT passthrough path and method


A seguinte modelagem de banco de dados é nóia da minha cabeça?

Question: Criei essa modelagem (apenas uma ideia), de forma a não ter campos nulos/brancos.
Não revisei por completo. Podem haver campos que ficariam em branco. A tabela matriz foi a Entidades e através das necessidades de não haver campos em branco, as outras surgiram.
De certo devem haver campos desnecessários em algumas tabelas, como quem cadastrou/atualizou e quando essas acoes ocorreram. Gostaria que alguém que entenda de modelagem se tem cabimento minha ideia e onde isso que eu fiz me prejudicaria no desenvolvimento. Obrigado.
Comment: Não sei se vai garantir inexistência de brancos, mas não parece haver necessidade de nulos. Não sei se você tem um problema específico aí pra resolver. Pra mim parece tudo ok. Mas só olhando o modelo não dá para garantir que está tudo correto. Dizer se prejudicaria é mais complicado. Não ter nulos é algo interessante, mas não pode ser um objetivo em si. http://pt.stackoverflow.com/q/2296/101
Answer: Fora a nomenclatura adotada que eu não gosto, mas não é um problema, não parece ter erros dentro do requerimento da pergunta. Mas se não vai prejudicar em nada é mais complicado dizer, não sei como será usado.
Não dá para garantir só por isso que não haverá brancos, nem mesmo nulos, mas o modelo parece, até onde dá para entender, que ajuda evitar que existam nulos.
O que é uma boa, mas não se deve perseguir a todo custo.
O que eu achei estranho é a tabela de endereço que só pode ter um item por entidade. Ou seria interessante colocar o endereço na tabela principal, já que só tem um, ou se isto está errado, deveria tirar a coluna da tabela TEntidade que relaciona o endereço e colocar uma coluna em TEndereco que relacione com a entidade, assim permitirá vários endereços, que eu acho que é a intenção.
Tem tabela que parece sobrar, por exemplo TIE. Não vejo porque isso existe. Mas pode ter um motivo que não percebi.
Algumas coisas parecem soltas. Não vejo vínculos reais com TEntidadesTipos. Pode ser só um problema de nome de coluna, mas também não vejo vínculo com TSituacoes.
Posso ter deixado passar alguma coisa.
Coloquei no GitHub para referência futura.
Comment: hahah realmente essa nomenclatura, particularmente, me dá arrepios srr
Answer: Nomenclatura eh igual a escova de dentes neh pessoal? rs. Mas se houver um padrão gostaria de ler sobre.
Maniero
A ideia da tabela TENDERECOS eh não ter duplicados. Escritos de forma incorreta existirão, mas sempre haverão pessoas que corrigirão pra forma correta. Mas se escreverem Uashinton Soares no lugar de Washington Soares? Buscaremos pelo CEP ou via programação incluímos endereços que constem a segunda parte do nome ou amarre pelos CEPs do estado, com uma opção de mostrar todos.
A tabela TIE, inscrição estadual, não sei se todos os estados tem,
mas já vi CNPJs que não tem. Eu, como MEI, não tenho.
Ela existe pra não deixar campo branco/nulo em TPJ;
Acho que RG também deveria fazer de uma tabela a parte, pois eh um documento secundário.
TENTIDADESTIPOS são os tipos de entidades (fornecedor, cliente, consumidor, funcionário, terceirizado, etc);
TSITUACOES eh por conta da situação de uma entidade, pedido, compra.. pode estar ativa, bloqueada, cancelada,
pendente, fechada, aberta, em transito, entregue... essas coisas.
Comment: Existe um padrão chamado [EAV (Entity Attribute Value)](https://inviqa.com/blog/2010/10/21/the-eav-data-model).
Comment: [EAV - Wikpedia](https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model)
Comment: O link que você passou não se refere a uma nomenclatura de entidades/atributos e sim uma forma de estruturar as tabelas/atributos/valores, que eh interessante (e confuso). (y)
Comment: Na verdade é um anti-pattern, mas existe dentro dessa estrutura, um padrão de nomenclatura, [veja aqui](http://blog.fabianobento.com.br/2011/09/padroes-para-nomenclatura-em-um-banco-de-dados/) e [aqui outro exemplo](http://www.linhadecodigo.com.br/artigo/253/padroes-de-nomenclaturas-guia-de-consulta-rapida.aspx)


Bayesian meta analysis of residual standard deviation using BUGS

Question: I have a small number of studies where the same model was calculated and want to infer the typical standard residual deviation. I have the degrees of freedom, the sum of the squares SSR and the mean of the square of the residuals MSR, but not the residuals themselves. My current plan is to do a bayesian meta analysis using either WinBugs or jags using two steps:
1) Assume the residual standard deviation is really the same over all studies and just try to estimate it more precisely. Let's call the overall residual variance res.var
With this, I already run into practical problems with the BUGS modelling language. I wanted to model the residual sum of squares using a chi square distribution, but have problems scaling the data accordingly. My problem is what I wanted to use is that for each study
$$
\frac{SSR}{\text{res.var}} \sim \chi^{2}_{k}.
$$
But I have problem putting this into a bugs model. I tried to use
model
{
for (i in 1:N)
{
chisquare[i] <- sumsq[i]/res.var
chisquare[i] ~ dchisqr(df[i])
}
res.var~dunif(0,1)
}

but this gives an multiple definitions of chisquare error. I tried transforming the first definition of chisquare so that sumsq is on the left side, but data can not be put on the left side of a logical node. Any practical advice?
2) Should I get this model to run, I would also like to allow for some variation of the residual standard deviation over studies, due to there being at least some small differences in the study population not included in the meta analysis model but I am not certain what a good hyperdistribution for the variance could look like. Any pointers?
Comment: If this is still an active question for you, perhaps we can work out how to apply what I did for the Binomial example for yours?
Comment: It's still active. I was just gone for the weekend. I will take a look at your answer below later. Thanks!
Answer: Gauss it with ABC
Gauss it – start with the simplest version that has (most of) the elements of the real question.
ABC – Approximate Bayesian Computation – a direct two stage Monte-Carlo simulation where parameters are first drawn from the prior, then data is drawn using those parameters just drawn from the prior and only those draws that had exactly the same (or approximately) are kept. The distribution of parameters that are kept are a sample from the exact (approximate) posterior.
This can be quickly worked out for the linked k~ Bin(N,p) question (yours will require a generation of data that you only saw summaries of).

k~ Bin(N,p) question

Define a prior for N (preferably with no fixed upper bound but here probably OK)
Reps=10^6
N=sample(1:1000,Reps,replace=TRUE)
Draw possible k from Bin(N,k)
Pk=rbinom(Reps,N,prob=p) #recall p is known and k observed
Just keep draws where pk = k
Use that kept sample as an approximation of the posterior and say get a density estimate.
(If you just want likelihood - no prior - then take c * posterior/prior as an approximation of that)
For example say the observed k was 28, this cab be easily run in R and checked against the closed form likelihood which is simple case of Example 4 Integrated Likelihood Methods for Eliminating Nuisance Parameters http://www.stat.duke.edu/~berger/papers/brunero.pdf

R code that can be run

Reps=10^7
N=sample(1:1000,Reps,replace=TRUE)
possible_k=rbinom(Reps,size=N,prob=.1)
posterior_k=N[possible_k==28]
hh=hist(posterior_k)
lik=dbinom(28,1:1000,prob=.1)
lines(1:1000,lik/max(lik) * max(hh$counts))
Now write the bugs or jags code, first for the tiny simple version of the question, note the posteriors are approx. the same, and then scale up to real question.
Maybe do this in private and then destroy any evidence of having to do this warm up exercise.
(Recall that "people go Bats* crazy when they see others doing what they do for a living a different way" quote from the Moneyball movie.)
As for posterior probabilities, they are usually just formal and not of relevance to anyone. An exception would be the example by  Jim Berger at 2009 International Workshop on Objective Bayes Methodology on HIV Vaccine trial.
Really liked this from @Jason Aug 23'11

Bayesian methods are generative, in that they provide a complete "story" for how the data came into existence. Thus, they aren't simply pattern finders, but rather they are able to take into account the full reality of the situation at hand.
Answer: I solved the first technical issue on my own - the answer lies in the fact if X is Chi-Distributed with n degrees of freedom, then c*X is gamma distributed with $\alpha = n/2$ and $\beta = 1/2c$. So I just had to to write
sumsq[i] ~ dgamma(0.5*df[i],1/(2*res.var))

and then put a reasonable prior on it - the form of the prior did not matter much since due to the number of degrees of freedom the likelihood dominated the prior.
Answer: I have no idea what you are trying to do, but I can answer the technical question. I had exactly the same problem when redefining the node.
If sumsq[i]/res.var are known numbers, just compute the result in R and pass it as data into BUGS. That's all!
Regarding 2), I don't know if it helps in your case, but for uninformative prior for variance one usualy uses this:
tau <- 1/variance # normally, tau is used in dnorm etc.
tau ~ dgamma(0.01, 0.01)

Comment: Thanks, but that's the problem. res.var is what I want to infer. And I don't seek a prior for the variance, but rather an idea what to use as a distribution from which the individual study variabilites are drawn from.
Comment: @Erik - 1) so what about transforming the 1st statement as `res.var <- sumsq[i]/chisquare[i]` and specifying prior or res.var? 2) so maybe you need something like `dgamma(alfa, beta)`? I don't know, but my thoughts would go that way... This is philosophically wery difficult to say... It is a similar problem as in [this question](http://stats.stackexchange.com/q/14719/5509)


Centralizar texto dentro de imagem

Question: Preciso alinhar horizontalmente e verticalmente um texto dentro de uma imagem.
Algum de vocês sabe como posso fazer isso?
HTML

Texto que deve ser alinhado!

CSS
/* Não tenho a menor ideia do que fazer! */

Comment: Relacionada: https://pt.stackoverflow.com/q/162510/99718
Answer: Jovem só para te esclarecer, a tag  não precisa ser fecha, logo isso é errado  (Imagem é um elemento do tipo "Void" ele não pode ter nada dentro, outro exemplo é o <input> que também não tem tag de fechamento </input>)
Agora sobre a sua pergunta uma das opções que vc pode fazer é colocar a imagem dentro de uma
 que esteja com display:flex e usar as propriedades do flex para alinhar o que estiver dentro na horizontal com justify-content:center e na  vertical com align-items:center
Veja o exemplo:

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
body {
    display: flex;
    justify-content: center;
    align-items: center;
}
.holder {
    display: flex;
    justify-content: center;
    align-items: center;
}
.holder img, .holder p {
    position: absolute;
    font-size: 32px;
    font-family: sans-serif;
    text-align: center;
}

Texto que deve
ser alinhado!

Centralizar texto dentro de imagem


Sample Size and Sensitivity/Specificity

Question: 1,765 patients were given a positive/negative screening test for a disease.
N = 415 patients tested positive
N = 1,350 patients tested negative
Due to constraints, not all 1,765 patients were given the definitive disease diagnostic test; clinicians had to pick a sample size (95% CL, 5% MoE) from the positive and negative groups.
n = 200 patients tested positive
n = 300 patients tested negative
Does this mean that the True Positives (TP), FP, FN, and TN values have a +/- 5% MoE? So the 89% True Positives is 84 – 94%?
Comment: Hi all...any help would be greatly appreciated!
Comment: If this is a homework question, please add the `self-study` tag and [read its wiki](http://stats.stackexchange.com/tags/self-study/info)
Comment: Thanks for adding the tag. However, in addition to reading the tag wiki, you also needed to modify your question accordingly (as described in the guidelines there). The closure reason also outlines the problem.
Answer: This seems like a strange and expensive way to run a study.  Usually you would start with a group where you already know the disease state and run the screening test on them.
Here you start with the screening test and then sample that group to run the definitive test.  This is not disqualifying...just expensive.
Anyway, you had to have presumed some hypothesized sensitivity and specificity to have run the power analysis on each proportion.  These hypothesized values were almost certainly not realized.  But even if they were, the sensitivity and specificity values are conditioned on the column totals, not the row totals (which is what the power analysis was done on).  So the original values would not apply.

Sample Size and Sensitivity/Specificity


Prove that $\gcd(f(x),g(x)) = 1$.

Question: Let $F$ be a field, let $p , q$ be two coprime natural numbers and we consider the two polynomials
$$
f(X) = \sum_{i = 0}^{p - 1} X^{k i} \qquad \mbox{ and } \qquad g(X) = \sum_{j = 0}^{q - 1} X^{k j}
$$
in $F[X]$, where $k \in \mathbb{N}$. If $x$ is an arbitrary element in $F$, how can I show that $\gcd(f(x) , g(x)) = 1$?
Comment: If $F$ is a field, and $x\in F$, then aren't $f(x), g(x)$ just elements of $F$? Do you mean $\gcd(f, g)$ (alternatively $\gcd(f(X), g(X))$) instead?
Comment: Yes, if $x \in F$, then $f(x) , g(x)$ are in $F$. And I can alternatively show that $\gcd(f(X) , g(X)) = 1$ to end my proof.
Answer: Hint (for the polynomial $\gcd$): $\;X^{kp} = \left(X^{k}-1\right)f(X)+1\,$ and $\,X^{kq} = \left(X^{k}-1\right)g(X)+1\,$.
Since $\,p,q\,$ are coprime, there exist integers $\,a,b\,$ such that $\,ap-bq=1\,$, and it can be assumed WLOG that they are positive i.e. $\,a,b \in \Bbb N\,$. Then $\,X^{kap}=X^{k(bq+1)} = X^k \cdot X^{kbq}\,$, and therefore:
$$
\left(\left(X^{k}-1\right)f(X)+1\right)^{a} - X^k \cdot \left( \left(X^{k}-1\right)g(X)+1\right)^b = 0
$$
Expanding the binomials, $\,h(X) = \gcd\left(f(X),g(X)\right)\,$ would have to divide $\,1-X^k\,$, but both $\,f(X)\,$ and $\,g(X)\,$ are coprime with $\,1-X^k\,$.
Comment: Thank you very much by your anwers.
Comment: Expanding
$$
\left(\left(X^{k}-1\right)f(X)+1\right)^{a} - X^k \cdot \left( \left(X^{k}-1\right)g(X)+1\right)^b
$$
I got that there exists $h(X) \in F[X]$ such that
$$
(X^k - 1) h(X) = \left(\left(X^{k}-1\right)f(X)+1\right)^{a} - X^k \cdot \left( \left(X^{k}-1\right)g(X)+1\right)^b = 0\mbox{.}
$$
Why do you say that $\gcd(f(X) , g(X))$ would have to divide $1 - X^k$? And why are both $f(X)$ and $g(X)$ coprime with $1 - X^k$?
Comment: @joseabp91 See the detailed proof for $k=1$ [here](https://math.stackexchange.com/a/2890439/291201). The case $k \gt 1$ works out in an entirely similar way.
Answer: Perhaps this will help:
$$ 1+x+x^2+...+x^{n-1} = {x^n-1\over x-1}$$
and a fact that $$\gcd(x^n-1,x^m-1) = x^{\gcd(m,n)}-1$$
Comment: It is not valid for me, as my statement and the fact $\gcd(x^n - 1 , x^m - 1) = x^{\gcd(n , m)} - 1$ are clearly equivalent. Unless you help me to prove your statement.
Comment: I'm almost sure you can find a proove on this site. Perhaps even in my posts you can find it.

Prove that $\gcd(f(x),g(x)) = 1$.


Display Suite layouts not working for field collections Edit\Add forms

Question: Even though I have the Display Suite Forms module enabled and applied a layout to this specific field collection, it does nothing for the edit/add forms. If I apply a layout using manage display it works when viewing the appropiate view mode (for example the full view mode).
Does anybody have any idea or hints where I could start looking?
Comment: I've ran into the same issue today, did you find a solution?
Answer: Just had a similar problem with ds and heartbeat module. Maybe my solutions also works for this problem. Just enable the needed submodules in ds - that fixed the problem.


I am an aspiring worship pianist coming from classical. How do I get started?

Question: Hello to the Music StackExchange community!
Pardon me if my post is in the wrong place. I have studied classical piano since I was six years old, and it has been fifteen years since. I have taken RCM examinations for close to ten years now, and have now reached the ARCT Performer's level. Therefore, I have become accustomed to the styles of the great 19th-century masters like Brahms and Chopin.
But as the title of this post says, I am an aspiring Christian worship pianist, and have recently joined such a band at my church for about half a year as of this writing. During this time, my worship leader keeps on telling everyone to "focus on the worship". In a recent open worship session, I played and sang "10,000 Reasons" by Matt Redman. Here I was a soloist, much like how I play solo classical piano pieces. As I was the only one actually involved in leading the worship, I could spontaneously arrange the song (structure, chords, and the such) to my own liking.
I realize, though, being a worship musician rather than a worship leader, I would have to work as a team and learn to follow the actual leaders. This would require more advanced planning and a sense to closely observe and adapt to instant changes (for example, repeating a bridge section multiple times while building up to a climax).
I know that there are bound to be worship musicians and leaders among this community who could offer some advice to me and anyone else in my shoes. My question to you is this: How should I learn to get along with my bandmates and what should I do to prepare myself for the unexpected?
Answer: You've been there six months and now you're asking how to learn to get along with your band mates. Does that mean you feel like you're not getting on with them? Or am I reading too much in here?
I'd guess that with your musical background you've more technical knowledge and ability than some of your band mates. So first step is never ever flaunt that fact. It's not your show. Your job as a worship pianist is to serve the song. Your band mates will learn they can trust you if they realise you've got their backs - so whatever direction the music goes it never catches you off-guard. And no one ends up embarrassed.
They'll learn they can trust your musical judgement if you make good suggestions for introductions for songs, suggest countermelodies, turnarounds for between verses and so on.
Also, dip your headlights sometimes - think about textures and back off. Many worship songs work really effectively if there's some sort of progression from a quiet beginning to the ending with multiple repeat choruses and so on.
You ask as well about being prepared - best thing is to learn the music so thoroughly that you don't have to bury yourself in the sheet music. When you do this you can look up - you're free to look around the band and watch and read the leader like a hawk. So if the leader spontaneously decides to sing the chorus again, you're not taken by surprise. This also frees you up to dialog musically with other band members - communicate visually across the band and you can coordinate stabs, endings, whatever.
I posted a question elsewhere about Hand signals in a small ensemble - for exactly this scenario.


Como chamar fragments no DrawerNavigation?

Question: Criei um novo projeto no android studio e escolhi usar o navigationDrawer, criei minhas telas agora gostaria de chamá-las. Como faço pra implementar este método e alternar janelas no menu de uma aplicação usando o:
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Fragment fragment = null;
    if (id == R.id.servic) {
       fragment = new Cronograma();
    } else if (id == R.id.nav_camera)  {
        fragment = new Localizacao();
    } else if (id == R.id.nav_gallery) {
        fragment = new Sobre_aplicativo();
    } else if (id == R.id.nav_share) {
        finish();
    }

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.mainFrame, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

ACTIVITY MAIN
<?xml version="1.0" encoding="utf-8"?>

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

    <FrameLayout
        android:id="@+id/flContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

CONTENT MAIN:
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
    android:id="@+id/mainFrame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>

<ListView
    android:id="@+id/listView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true" />

APP BAR MAIN:
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />

ACTIVITY MAIN DRAWER
<?xml version="1.0" encoding="utf-8"?>

<group android:checkableBehavior="single">
    <item
        android:id="@+id/servic"
        android:icon="@drawable/servico"
        android:title="Serviços" />
    <item
        android:id="@+id/nav_camera"
        android:icon="@drawable/pref"
        android:title="A prefeitura" />
    <item
        android:id="@+id/nav_gallery"
        android:icon="@drawable/local"
        android:title="Localização" />

</group>

<item android:title="Informações">
    <menu>

        <item
            android:id="@+id/nav_share"
            android:icon="@drawable/dev"
            android:title="Sobre o aplicativo" />
        <item
            android:id="@+id/nav_manage"
            android:icon="@drawable/exit"
            android:title="Sair" />
    </menu>
</item>

Answer: O ideal é que o layout de sua activity tenha como um de seus elementos algo que sirva como "container", é muito comum usar um FrameLayout para esses casos.
Sendo assim, crie um método da activity que faça o seguinte:
String backStateName = fragment.getClass().getName();
        FragmentManager manager = getSupportFragmentManager();
        manager.popBackStackImmediate(backStateName, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(container (id do container), fragment);
        transaction.addToBackStack(backStateName);
        transaction.commit();

Esse método deve receber como parâmetro uma instância do fragmento que você quer abrir, Ex:
  if (id == R.id.nav_camera) {
       abreFragmento(new CameraFragment());
  }

Assim, o fragmentManager da sua Activity vai substituir o que está no container pelo fragment que você instanciou.
Extra:
Nesse método mostrado, o fragmentManager guarda os fragments que foram abertos em ordem, se você usar abreFragment(new OutroFragment()) sendo que outro fragment já está aberto, o mesmo entra em onStop() e você pode voltar para ele utilizando o método fragmentManager.popBackStack().
Comment: Joao estava fazendo assim:  `int id = item.getItemId();
        Fragment fragment = null;
        if (id == R.id.nav_camera) {
           fragment = new Cronograma();
        } else if (id == R.id.nav_gallery)  {
            fragment = new Localizacao();
        } else if (id == R.id.nav_manage) {
            fragment = new Sobre_aplicativo();
        } else if (id == R.id.nav_share) {
            finish();
        }`
So que a tela ta aparecendo por cima do menu.
Comment: Manda como ta o seu xml desse layout.


Como permitir duplicar valor de uma chave no SQL?

Question: Preciso que as chaves Numero_Processo e Numero_Revisao, possam receber valores que ja existem na tabela.
por exemplo:
Id = 1, Numero_Processo = 1, Numero_Revisao = 1
Id = 2, Numero_Processo = 1, Numero_Revisao = 2
Id = 2, Numero_Processo = 1, Numero_Revisao = 3

ou
Id = 4, Numero_Processo = 2, Numero_Revisao = 1
Id = 2, Numero_Processo = 2, Numero_Revisao = 2
Id = 2, Numero_Processo = 2, Numero_Revisao = 3

Em ambos os casos eu preciso repeti os valores Numero_Processo e Numero_Revisao.
Esses campos são chaves em outras tabelas com a tabela de Qualidade_Insp_Inj_Entrada na imagem abaixo .
Comment: Pelo que entendi na verdade você precisa utilizar uma chave composta (id, numero_processo, numero_revisao). Primeiro você precisa ver se está como `identity`  a sua chave atual.
Comment: @RovannLinhalis tem razão, não é uma chave primária obrigado por observar, remover o comentário que ficou sem propósito
Comment: Esse `id` também precisa repetir? Ele é a pk da tabela?
Comment: Uma chave estrangeira necessariamente precisa ser uma chave única na tabela de referência. Você precisará escolher uma outra chave na tabela que seja única (`id, numero_processo, numero_revisao`, por exemplo) e alterar a sua chave estrangeira para este novo registro único.
Comment: Meu Id é unico, não precisa repeti. Mas os campos Numero_Processo e Numero_Revisao eu preciso que seja chave e que aceite valores repetidos. Como fazer?
Comment: tem que ser chave estarangeira, e não chave primária, remova `PK_Numero_Processo` e `PK_Numero_Revisao`
Comment: *"Meu Id é unico, não precisa repeti. Mas os campos Numero_Processo e Numero_Revisao eu preciso que seja chave e que aceite valores repetidos"* @DanielleArrudatorres a tabela só pode ter uma chave primária, se o campo `ID` já é,  você pode usar os outros campos como chaves estrangeiras e repetir sem problema
Answer: O problema parece ser por estar repetindo o mesmo valor no campo Id e não nos campos Numero_Processo e Numero_Revisao.
Você realmente não pode ter mais uma PK, mas você pode ter uma PK composta.
Existem três possíveis cenários:

Você utiliza um Id diferente para cada linha e mantém a PK como está, neste caso ele iria aceitar.
Caso seja possível repetir o Id, mas nunca repetir a combinação dos três campos, neste caso faria uma PK composta.
ALTER TABLE [Qualidade_Insp_Inj_Processo] ADD CONSTRAINT [PK_Qualidade_Insp_Inj_Processo] PRIMARY KEY (Id, Numero_Processo, Numero_Revisao)
Modelar suas tabelas de uma forma diferente, neste caso seria necessário conhecer melhor o projeto para poder sugerir essas mudanças.

Valeu o/


Unable to connect to MySql Database on webserver

Question: I have some databases on my shared web server. It was all fine around 45 days back when my website is shifted to another server, all my data is shifted including databases. Now I cannot connect to my MySQL databases via external software (Visual Studio, Workbench etc). I can successfully connect to my databases via MyPHPAdmin provided to me via cpanel. The desktop applications are showing the following errors:

By reading some other questions on internet, I come to the point that it might be the firewall problem on webserver, it might block MySql default port 3306.
How can I go into the firewall of my webserver and allow my port, (if it is a real problem)?
I am using the default port of MySQL databases ie. 3306, I have already made my databases access globally by putting '%' in the remote access IP address.
Comment: If it's really a **"shared web server"**, then access to MySQL is usually forbidden for external connections for security and performance purposes. Plus, with shared web server the MySQL database will usually (well, in most cases) be located on separate server specially optimized for DB. I strongly suggest to contact your hosting company and ask for clarification if such connection is possible from outside network. very likely they have just disabled such possibility (firewall and/or mysql config)
Answer: Well depending on your contract and shared webserver you might be prohibited to access mysql from out side.
Ask the suport guys to add an entry to the firewall so that you can access it from outside.They will most likely add it or explain why they can't . i won't ask them for clarification as they might dodge that.
Hope this helps.
Comment: @ - Alex H But I was accessing my databases before the transfer of my website, when I asked the support guy to do so, he told me that he is not concenered with the databases. There is an other way to do so?
Comment: That would be the most straight - forward way to do it . If you have access to ssh you can always try to add an entry in the firewall for mysql port . Please have a look here , it has multiple examples http://ubuntu-commands.blogspot.ro/2008/11/how-do-i-enable-remote-access-to-mysql.html .
Comment: I tried SSH shell, it shows that "Shell access is not enabled on your account", What should I do?
Comment: Contact the support for your VPS :) and ask the modifications that you want from their side .


Paste syntax highlighted code from Komodo?

Question: I recently switched from using Vim in Puttytray on WindowsXP to Komodo on OSX.  One of the features I miss is Puttytray used to let you copy the colored text out of whatever is in your terminal and paste it as rich text on any application that accepts it (like your instant messanger). This makes it easier for me to discuss code with coworkers.
Is it possible to do similar with Komodo?
Answer: in the menu you will find under File / Print selected text to HTML. At that point you will have an html with the syntax coloring that maybe would be easier to copy somewhere.


BSD 50% interrupt utilization in irq0/clock

Question: On OpenBSD on an Atom 450, with HPET configured in the BIOS and not, also with Hyperthreading/ACPI on-off, nothing seems to make a difference.
Here's my vmstat -iz
<code># vmstat 2
 procs    memory       page                    disk traps          cpu
 r b w    avm     fre  flt  re  pi  po  fr  sr wd0  int   sys   cs us sy id
 0 0 0   3488  981792  429   0   0   0   0   0  35 295771   906   89  1 51 48
 0 0 0   3492  981788   12   0   0   0   0   0   0 278490    37   10  0 50 50
^C
# vmstat -iz
interrupt                       total     rate
irq0/clock                      12115      102
irq96/inteldrm0                     0        0
irq133/ppb0                         0        0
irq96/em0                           0        0
irq84/ppb1                          0        0
irq81/em1                           0        0
irq131/ppb2                         0        0
irq82/em2                           0        0
irq132/ppb3                         0        0
irq83/em3                           0        0
irq84/uhci0                        28        0
irq83/uhci1                         0        0
irq84/ehci0                         2        0
irq80/pciide0                     877        7
irq82/pciide1                       0        0
irq81/ichiic0                       0        0
irq130/com0                       451        3
irq129/pckbc0                       0        0
Total                           13473      114
</code>
The irq0/clock continues to go out of control, this is about 1minute after booting....
<code># vmstat -s
       4096 bytes per page
     252939 pages managed
     245456 pages free
        865 pages active
       1015 pages inactive
          0 pages being paged out
          1 pages wired
          0 pages zeroed
          4 pages reserved for pagedaemon
          6 pages reserved for kernel
     132529 swap pages
          0 swap pages in use
          0 total anon's in system
          0 free anon's
      17558 page faults
      17368 traps
   47204661 interrupts
       4703 cpu context switches
         14 fpu context switches
      17854 software interrupts
      37197 syscalls
          0 pagein operations
          0 swap ins
          0 swap outs
        144 forks
         13 forks where vmspace is shared
         14 kernel map entries
          0 number of times the pagedaemon woke up
          0 revolutions of the clock hand
          0 pages freed by pagedaemon
          0 pages scanned by pagedaemon
          0 pages reactivated by pagedaemon
          0 busy pages found by pagedaemon
       9096 total name lookups
            cache hits (67% pos + 1% neg) system 0% per-directory
            deletions 0%, falsehits 0%, toolong 0%
      0 select collisions
</code>
Any ideas to reduce the load, thanks.
Answer: This perticular problem was likely asperbated by the fact that OpenBSD's sysctl is anemic.  FBSD "poll" sysctl would of likely solved this much earlier.
The problem was due to a poorly written BIOS, specifically it's configuration and implmentation of a console/remote access serial port.  It was spinning like crazy and generating these interrupts, even if not connected etc...


Poisson arrival

Question: Users arrive according to Poisson process with rate $\lambda$. If every third user is removed, then do the remaining users form a Poisson process with rate $2\lambda/3$?
If every other user is removed, then do the remaining users form a Poisson process with rate $\lambda/2$? and so on..?
Comment: It depends on how the removal occurs: are you saying each user is removed independently with probability $1/3$ or that literally every third user is systematically removed?  If the latter is the case, then consider what that does to the patterns of inter-arrival times and recall that in a Poisson process the inter-arrival times must be independent.
Comment: I am saying that every other user is removed.
Comment: I believe the resulting process will not be Poisson after doing some research. Can anyone please verify?
Answer: whuber pretty much covered it already in his comment, but I'll give a slightly different way of thinking about it. I'll try to come back with a slightly longer one soon
Short answer:
The interarrival time is now exponential($\lambda$) for some users and Gamma(2,$\lambda$) for others (time to removed user, plus time from removed user to next user). It's therefore not a Poisson process.
[If the removals were random rather than every third user, however, it would be a Poisson process.]
Answer: No, deterministic deletion of arrivals (such as "delete every third arrival") does not leave a Poisson process, but random deletion does, e.g. for every
arrival, make a decision (independent of all past and future decisions) to
delete with probability $\frac{1}{3}$ and to not delete with probability $\frac 23$.
Then what is left after such random deletions is a Poisson process with rate
$\frac{2\lambda}{3}$.  Read, for example, the last paragraph of this answer.

Poisson arrival


Suddenly, all covariates and factors become very significant

Question: I am running a multinomial logistic regression model in R using the command multinom. My response variable, $y$, is a factor with three levels of length 40, 25 and 5 each level. I have several factors and covariates to model it, say $x_1,\ldots,x_n$.
At a first step, I wrote $y\sim x_1+x_2$ in the multinom function. As a result, I obtained some "usual" p-values for the levels of $x_1$ and $x_2$: 0.05, 0.61, 0.92... Then I added a third factor/covariate, $x_3$: $y\sim x_1+x_2+x_3$. Suddenly, nearly all p-values were exactly 0, even for levels of $x_1$ and $x_2$ that had not been significant before adding $x_3$.
What is the reason for that? If I keep adding more factors in the model, then all p-values become $0$.
I joined the second and third levels of $y$ (the ones of length 25 and 5) to have a dichotomic variable, so that I could use the glm function with family binomial. In this glm model, I started writting $y\sim x_1+x_2$, $y\sim x_1+x_2+x_3$, etc, and the problem I mentioned above did not appear.
So, is this a problem of the multinom function? Is this a problem of the third level of $y$, which has a very small size?
Edit: Here is an example:
y <- c(1, 1, 1, 1, 1 ,1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 2 ,2 ,2 ,2 ,2 ,1 ,1 ,2 ,3 ,2 ,1 ,2 ,1 ,1 ,1 ,2 ,1 ,1 ,3 ,2 ,1 ,1 ,1, 2, 1, 1, 2, 2, 2, 1, 3, 2, 1,1, 2, 1 ,1 ,1 ,1 ,2 ,2 ,2 ,2, 2, 2, 2, 1, 2, 3, 1, 1, 1, 1, 1, 2)
x1 <- c(1 ,2, 1, 1, 4 ,1, 1, 3 ,1 ,1 ,3 ,1, 1 ,1, 1, 2, 2, 4, 2, 2 ,1 ,2 ,1, 3, 2, 2 ,2 ,4 ,4, 1, 4, 1, 1, 3, 2, 1 ,1, 1, 2, 1, 1, 2, 2, 1, 1, 3, 2 ,1,1, 2, 4, 1, 1, 1, 2, 2, 4, 2, 1, 2, 2, 1, 1, 3, 1, 1, 1, 1, 1, 2)
x2 <- c(1 ,1 ,1 ,1 ,1 ,1 ,1 ,2 ,1 ,1 ,2 ,1 ,1 ,1 ,1 ,1 ,2 ,1 ,1 ,1 ,1 ,1 ,1 ,3, 2 ,1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 2, 1,1 ,2 ,2 ,1 ,1 ,1 ,3 ,1 ,1 ,2 ,1 ,1 ,1 ,1 ,1 ,2 ,1 ,1 ,2 ,1 ,1 ,1 )
x3 <- c(1530, 15120,   891,  1452 ,15000,  6498  , 400 ,47880,  4608,  8976 ,34040,  7980  ,1152,   637, 17820 ,25839,70875  ,1260 ,28210 ,18200,  2184,   936,  1056 ,90804 ,28290  ,6480 ,14040,   550,  8712,  2028 ,14000,  2640,2560 ,41184, 41984,  8448,  1200,  3136,  6090  ,7581,  4788, 10710,   396,  7260,  2816 ,29799 ,21793, 24960,6072, 23064,  4680 ,25296,  6160,   672, 16875, 35360, 10450, 43200, 17204 ,21576 ,17820,  6650,  5130,  4104,4104, 12768,  9504,  1188 ,23460 ,16500)
y <- as.factor(y)
x1 <- as.factor(x1)
x2 <- as.factor(x2)

library(nnet)

# Two explanatory factors:
model <- multinom(y ~ x1+x2)
summary(model)
stad <- summary(model)$coefficients / summary(model)$standard.errors
p_values <- 2 * (1 - pnorm(abs(stad),0,1))
p_values
> p_values
   (Intercept)          x12       x13        x14       x22       x23
2 8.350025e-05 1.315633e-05 0.9798046 0.06366562 0.6952859 0.9892148
3 9.169932e-01 9.957820e-01 0.9753906 0.99891637 0.9992514 0.9889991

# Three explanatory factors/covariates:
model <- multinom(y ~ x1+x2+x3)
summary(model)
stad <- summary(model)$coefficients / summary(model)$standard.errors
p_values <- 2 * (1 - pnorm(abs(stad),0,1))
p_values
> p_values
  (Intercept) x12 x13 x14 x22 x23          x3
2           0   0   0   0   0   0 0.004544893
3           0   0   0   0   0   0 0.700799167

Comment: Note that your coefficients are tending to infinity I suspect separation or the Hauck-Donner effect. Try searching this site for those terms.
Comment: How many observations are in your dataset?  I suspect your design matrix is not full rank.
Comment: @StatsStudent There are 40+25+5=70 observations.
Comment: Sorry I missed that.  Can you also state how many levels there are of each x value?  Some output would be helpful.
Comment: Could you maybe share your code with us? Just to make sure you have no typos?
Comment: @StatsStudent I edited the question.
Comment: @VasilisVasileiou I edited the question.
Comment: @mdewey Is there a way to solve this problem? For example, is it correct to just compare the models $y\sim x_1+x_2$ and $y\sim x_1+x_3$ and not take into account $y\sim x_1+x_2+x_3$? And why if I join levels 2 and 3 of y and perform a glm in R instead of a multinom the "perfect separation" problem does not appear?
Comment: That's more of an answer than I have time to write, but I'll point you to the questions tagged for the Hauck-Donner effect: https://stats.stackexchange.com/questions/tagged/hauck-donner-effect
Answer: Looks likely to be perfect separation. There's just not a lot of data in some of those blocks. And while you are fitting an additive model, which this plot doesn't quite capture, it does seem quite likely that adding that third variable is causing this. Note also how huge your estimates are. For more on perfect separation, see for example, Will the p value become useless in such case: logistic regression with perfect separation?
library(ggplot2)
d <- data.frame(y=y, x1=x1, x2=x2, x3=x3)
ggplot(d) + aes(x3, y) + geom_point() + facet_grid(x1~x2)

Comment: Thank you for your answer. Is there a way to solve this problem? For example, is it correct to just compare the models $y\sim x_1+x_2$ and $y\sim x_1+x_3$ and not take into account $y\sim x_1+x_2+x_3$? And why if I join levels 2 and 3 of y and perform a glm in R instead of a multinom the "perfect separation" problem does not appear?


Filtrar no where a maior data com LINQ

Question: Como eu passo no where dessa linq a max datatransacao, ou seja, desejo trazer o resultado mas pela maior data.
var resultado = (from ci in webDB.T_Controle_Importacao
                             where ci.CNPJ == cnpj
                             let dd = EntityFunctions.DiffDays(DateTime.Now, ci.DataTransacao)
                             select dd >= 45 ? 3
                                  : dd >= 15 ? 2
                                  : 1).Take(1);

Answer: Você pode ordenar a query de forma que o objeto com a maior data apareça na frente, e depois pegar o primeiro registro:
var resultado = (from ci in webDB.T_Controle_Importacao
                                 .OrderByDescending(ci => ci.DataTransacao)
                 where ci.CNPJ == cnpj
                 let dd = EntityFunctions.DiffDays(DateTime.Now, ci.DataTransacao)
                 select dd >= 45 ? 3
                      : dd >= 15 ? 2
                      :            1
                )
                .Take(1);

Note que ao fazer isso, é recomendável que você tenha um índice na coluna que armazena a data no banco de dados, de forma que a ordenação não fique lenta demais.
Answer: Ordene para trazer a maior data com orderby campo descending
var resultado = (from ci in webDB.T_Controle_Importacao
                    where ci.CNPJ == cnpj
                    let dd = EntityFunctions.DiffDays(DateTime.Now, ci.DataTransacao)
                    orderby ci.DataTransacao descending
                    select dd >= 45 ? 3 : dd >= 15 ? 2 : 1).Take(1);

Filtrar no where a maior data com LINQ


In SAPUI5 List Report Application, the updated value does not reflect until reload the list

Question: In my SAPUI5 List Report Application project, from the List view, when I navigate to the detailed page (General Information), click Edit and change one of the value in a drop-down (which has a value Help) and click Save, it does not update the description. It updates only the code.
eg; When I change the confirmation Status from "(P) Paid" to "Initial" and save, it updates as "Paid". Note that "Paid" is the description and "P" is the code. So I can see the "P" has removed, but "Paid" text still there.
Also when you go back to the previous screen (List view) then the Confirmation Status of the list shows "Paid". But if you click the "Go" button and then the List refreshes and show the status shows as "Initial" which is correct.
Refer below screenshots.
Figure 1: Here I change the Status from "(P) Paid" from "Initial".

Figure 2: This is what I see after save.

Figure 3: List view did not update too.

Figure 4: If you click the "Go" button, then you will see the correct output.

Any idea why it does not update?
Note that I have created a SAPUI5 List Report Application project using Project From Template option in my web IDE.
Also, I have set the "refreshAfterChange" property as true in the manifest.json under "models". But it does not help.
"": {
            "dataSource": "mainService",
            "settings": {
                "defaultBindingMode": "TwoWay",
                "defaultCountMode": "Inline",
                "refreshAfterChange": true
            }
        }

Answer: ExtensionAPI.refreshAncestors() might solve your issue. See official documentation for more information.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Use oModel.refresh(); to force the update after changing data.


How to set width to Input text field in bootstrap under class

Question: In the below layout, the last text field(UserName) alone not in correct size. I tried many ways, but nothing works. pls share any idea. my code is

Login Help

                            <form role="form">

                                            <input type="radio" name="userPwd" id="userpwd1" value="option1" checked>Forgot Username

                                            <input type="radio" name="userMailMob" id="mail1" value="option1" checked>Email

                                            <input type="radio" name="userMailMob" id="mob1" value="option1">Mobile

                                            Email Address

                                            <input class="form-control col-lg-offset-3" placeholder="E-mail" name="email" type="email" autofocus>

                                            <input type="radio" name="userPwd" id="userpwd2" value="option2">Forgot Password

                                            <input type="radio" name="pwdMailMob" id="mail2" value="option1">Email

                                            <input type="radio" name="pwdMailMob" id="mob2" value="option1">Mobile

                                            Email Address

                                            <input class="form-control col-lg-offset-3" placeholder="E-mail" name="email" type="email">

                                                Username
                                                <input class="form-control col-lg-offset-3" placeholder="Username" name="uname" type="text">

                            </form>

Comment: @Torean The OP didn't indent their code, I've fixed it in an edit.
Comment: Did you want the text fields horizontally next to the lables or leave everything as is and just have the fields all the exact same (have the last field the same as the ones above it)?
Comment: Row and col-lg-12 are 100% width with appropriate margins and padding.  You shouldn't use both on one element.  Instead nest cols inside rows.
Answer: If all you're concerned with is the size of the last input then change this:
You have col-lg-12 row with a col-lg-6 inside of it, remove the col-lg-6 and change the col-lg-12 row to col-lg-6 row.
That being said I've included two alternative layouts that use bootstrap default classes and standard layouts for forms that may help as you're mixing col-*-* with rows in the same div and that isn't how the grid is structured.
See working examples with your original code (*fixed) and two samples.

  Username
    <input class="form-control col-lg-offset-3" placeholder="Username" name="uname" type="text">

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

Login Help (Original)

          <form role="form">

                  <input type="radio" name="userPwd" id="userpwd1" value="option1" checked>Forgot Username

                    <input type="radio" name="userMailMob" id="mail1" value="option1" checked>Email

                    <input type="radio" name="userMailMob" id="mob1" value="option1">Mobile

                Email Address

                <input class="form-control col-lg-offset-3" placeholder="E-mail" name="email" type="email" autofocus>

                  <input type="radio" name="userPwd" id="userpwd2" value="option2">Forgot Password

                    <input type="radio" name="pwdMailMob" id="mail2" value="option1">Email

                    <input type="radio" name="pwdMailMob" id="mob2" value="option1">Mobile

                Email Address

                <input class="form-control col-lg-offset-3" placeholder="E-mail" name="email" type="email">

                Username
                <input class="form-control col-lg-offset-3" placeholder="Username" name="uname" type="text">

          </form>

Standard Form

            <form role="form">

                      <input type="radio" name="userPwd" id="userpwd1" value="option1" checked>Forgot Username

                      <input type="radio" name="userMailMob" id="mail1" value="option1" checked>Email

                      <input type="radio" name="userMailMob" id="mob1" value="option1">Mobile

                  Email Address
                  <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus/>

                      <input type="radio" name="userPwd" id="userpwd2" value="option2">Forgot Password

                      <input type="radio" name="pwdMailMob" id="mail2" value="option1">Email

                      <input type="radio" name="pwdMailMob" id="mob2" value="option1">Mobile

                  Email Address
                  <input class="form-control" placeholder="E-mail" name="email" type="email">

                  Username
                  <input class="form-control" placeholder="Username" name="uname" type="text">

            </form>

INLINE FORM

            <form role="form" class="form-horizontal">

                    <input type="radio" name="userPwd" id="userpwd1" value="option1" checked/>Forgot Username

                    <input type="radio" name="userMailMob" id="mail1" value="option1" checked/>Email

                    <input type="radio" name="userMailMob" id="mob1" value="option1">Mobile

                Email Address

                  <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus/>

                    <input type="radio" name="userPwd" id="userpwd2" value="option2" />Forgot Password

                    <input type="radio" name="pwdMailMob" id="mail2" value="option1" />Email

                    <input type="radio" name="pwdMailMob" id="mob2" value="option1" />Mobile

                Email Address

                  <input class="form-control" placeholder="E-mail" name="email" type="email" />

                Username

                  <input class="form-control" placeholder="Username" name="uname" type="text" />

            </form>

Answer:
Set the heights of input elements using classes like .input-lg and .input-sm.
Set the widths of elements using grid column classes like .col-lg-* and .col-sm-*.

bootstrap
Comment: Why not just reference [Bootstraps official site](http://getbootstrap.com/css/#grid)?
Comment: This was just a quick search, but I will change it.


Kohana 3.2 Rules Fail

Question: When defining rules, does the field name have to match the column name in the database?
I'm having a problem where if the field name and the column name don't match, the rules are displayed and nothing is saved to the database.
What works:
Database
user_id | username

Field
<?php echo Form::input('username', $username, array('id' => 'username')); ?><?php echo Arr::get($errors, 'username');?>

Model
class Model_User extends ORM {

    protected $_primary_key = 'user_id';

    public function rules()
    {
        return array(
            'username' => array(
                array('not_empty'),
            ),
        );
    }
}

Messages
return array(
    'username' => array(
        'not_empty' => 'You must provide a username.',
    ),
);

What doesn't work:
Database
user_id | username

Field
<?php echo Form::input('membername', $username, array('id' => 'username')); ?><?php echo Arr::get($errors, 'membername');?>

Model
class Model_User extends ORM {

    protected $_primary_key = 'user_id';

    public function rules()
    {
        return array(
            'membername' => array(
                array('not_empty'),
            ),
        );
    }
}

Messages
return array(
    'membername' => array(
        'not_empty' => 'You must provide a username.',
    ),
);

It seems if I change the field name to something other than username the rules function doesn't work correctly.
If I don't apply any rules, changing username to something else doesn't cause any problems with saving data to the database.
Answer: Mapping column names from your database to different internal names is not possible. The same column name is also used for setting rules, labels etc. I don't see why you would want to change the column names, it would be bad for a developers expectations. My advise is to rename your table columns in that case.
The only possibility Kohana ORM provides to control your table columns is to whitelist an array of column names that is to be used. Use this variable in your ORM module:
protected $_table_columns = array('column1','column2');

Comment: I was hoping this wasn't the case. My code works without the rules. My field names are different than the column name because all the info come from the same table, so they can't be called the same field name. It's an options table, so one row would be the site name and the next row would be the site description. The field names would be sitename and sitedescription instead of the name of the column the info comes from.
Comment: Seems like external validation is what I need to do.

Kohana 3.2 Rules Fail


How can i create a shortcut to close the Download bar in Google Chrome (Windows)

Question: I've done a bit of searching and from what i see there is no such shortcut. There is however this extension for Google Chrome that does this, it automatically closes the download bar after 5 seconds. However i generally avoid installing extensions. Is there any way to make such a shortcut? Something that seems so small and irrelevant can really make a difference. Thanks in advance.
Answer: there is a chrome extension called Always Clear Downloads.

User Reviews:
•First extension that clears the download bar and hides it afterwards.
•I have been looking for an extension that does this! Thank you. Works very well hiding the download bar after the download has completed. Saves a click.


One view per taxonomy vocabulary without a contrib module?

Question: What do I need to set in a D8 view, to have one view per taxonomy vocabulary without any contrib module?
Comment: Here is a gist of standalone custom code for achieving this:https://gist.github.com/markfullmer/3292ad93792d9530cacb7da5c42d1b21 . This is based on the more generic Taxonomy Views Integrator module.
Answer: Drupal 8 already uses the (now-builtin) Views for listing pages of content belonging to a certain taxonomy term.
That's a single view for all taxonomy terms:

You can edit the view and make necessary changes you need
http://example.com/admin/structure/views/view/taxonomy_term
Comment: Yes, but I want 1 views page setup per taxonomy vocabulary. So I can set different fields etc.
Comment: Well, by default that view uses the content row style with `Teaser` view mode, instead of `fields`. So if you add different fields to each vocabulary as desired, and update the `Teaser` view-mode with needed fields, you should be able to accomplish what you describe.
Answer: I don't know why anyone would have a "without a contrib module" requirement.
You can either do this with Page Manager, or you can write a custom module that alters the route and then dynamically calls a different view. Drupal 8 doesn't provide a feature to do this without additional modules/code
Comment: By the way I have found this project which was created to solve the purpose: https://www.drupal.org/project/tvi. But I have uninstalled it, since it seemed not to ready (errors). The route altering seems like a doable approach.


Can't differentiate between time signatures

Question: I know the general idea behind time signatures:
6:8 is 6 eighth notes in a bar, 3:4 is 3 quarter notes in a bar.
I also understand that in situations like these, while the two technically equal each other mathematically, they have different stressed beats.
However, I'm confused as to how these stressed beats are found. In other words, what if I was given a time signature like 12:8? 4:2?
I've heard the rule that in x:8 time, there are always groups of three, but what else do you have to go by?
Comment: http://music.stackexchange.com/a/2500/28
Answer: The simplest way to derive which beats are stressed in a given time signature is to look at how the notes are beamed or agogically accented.
For example, 6/8 is typically divided in a 3+3/8 grouping (as noted in other answers), however, it could also be grouped 2+4/8, 1+5/8, 4+2/8, and 5+1/8 for example. Each of these different divisions stresses a different beat in the measure, and must be grouped accordingly.  Through notation, you can distinguish groupings through how notes are beamed.
This grouping tactic is even more pronounced in asymmetric meters, like 5/8 and 7/8.  In these groupings the stresses must become lop-sided, so a 5/8 typically turns into a 2+3/8 or a 3+2/8.
If the time signature doesn't allow for beamed groupings (such as 7/4), then it is important to look at phrasing, and if possible, agogic accents. If in 7/4 I saw two half-notes followed by three quarter-notes, I would know that it had a 4+3/7 grouping.
Alternatively, look at phrase or slur markings to help you distinguish which beats begin / end phrases.  Look at other instruments (if available) in the score to see if another part can clarify the confusing grouping.  Listen to other recordings and see how others have phrased it.  Lastly, play through it and figure out which phrasing sounds good to you.
Answer: As so often in music, we're going to struggle to pin down a Theory of Everything.
No, I'm afraid a bottom number of 8 doesn't always imply Compound Time (3-groups) and one of 4 doesn't always imply Simple Time (2-groups).    6/4 is  Compound Duple - two dotted half beats.  (We use 3/2 for Simple Triple - three half-note beats.)   2/8 and 4/8 are alternatives to 2/4 and 4/4.   And here's one of Theory's dirty little secrets - although the textbooks don't mention it much 3/4 and 3/8 are often Compound Single - a one-in -the-bar fast waltz or a jig.
Today's composers will often choose 8/8 (rather than 4/4) when the music falls into irregular rhythmic groups, their alternative might have been to notate something like 2/8 + 3/8 + 3/8.
But, in Theory 101, you'll be pretty safe if you consider a time signature with top number 6, 8 or 12 to be Compound (3-groups), 2, 4 or 8 to be Simple (2-groups).   Top number 3 is tricky.  The textbook answer is probably Simple Triple - three 2-groups. But in real life it could well be Compound Single - one 3-group.
Answer: Some of the above answers have done a great job of breaking this questions down, so I'm going to keep it simple. The way I think about time signatures is about feeling.
For instance, if I'm playing in 3/4, then there are three pulses per bar made up of a quarter note for each pulse. If I'm playing in 6/8, then its two pulses per bar with each pulse made up of 3 8th notes. In 12/8, 4 pulses per bar made up of 3 8th notes per pulse.
To expand that, 5/8 is (depending on the accents) 2 pulses per par, one pulse containing 2 8th notes and one containing three 8th notes.
To extend that even further (if you are crazy like me):
19/16:
I would feel it in 3 groups:
1 group of 7/16 - so 3 pulses, 2 pulses of 2 16th notes, 1 of 3 16th notes,
1 group of 5/16 - 2 pulses, one pulse of 2 16th notes and one pulse of 3 16th notes,
and then another group of 7/16.
A lot of this depends on the piece of music of course, as a melody might not be easily subdivided into pulses, but again, these are common ones, and you will be able to feel a large number of tunes with these sort of ideas.
My suggestion is to listen to the music, break it up into recognisable pulses, then work out how the melody travels over them, and then go from there.
Good luck!
Answer: In 6/8, the unit of beat is the dotted quarter note, so you have two beats that are divided into triplets - that's to say that you would count the beats something like "One-two-three, two-two-three." It's duple (or two beat) time, but the beats themselves are divided by three. In 3/4 time, there are three quarter note beats to the bar, divided into two eighths apiece.
In 12/8 time, the unit of beat is also a dotted quarter note, so you have something with a beat pattern like 4/4 time (four beats to the bar, with a stress on the first beat and a lesser stress on the third), but each beat is divided into triplet eighths rather than duplets.
In general, if the number of beats (the top of the time signature) is divisible by three more than once (which means that time signatures like 3/4 and 3/8 don't apply here), you have a time signature where the unit of beat is equal to the three of the note values specified by the bottom of the time signature. Thus you can have a time signature of 15/16, which means you have 5 beats, each with a note value of a dotted eighth, or 6/4, which means two beats, each with a note value of a dotted half note.
Comment: I think "divisible by 3 more than once" usually means "divisible by 9"; I suggest "a multiple of 3". Even so, 3/8 can sometimes be '1 to a bar'. Also, 15/8 can also be 3 beats, each 5/8, e.g. Scriabin's prelude op. 11 no. 14. So it is necessary to look intelligently at the music to be sure.
Comment: Thank you, you are right about multiple of threes - I was struggling for the best way to exclude 1 x 3, because, properly speaking, *any* time signature can be one to the bar at a fast enough tempo, but they still have divisions within the bar. If every bar has a single note per bar, then someone is committing an atrocity of notation. (cont'd...)
Comment: The normal convention, I believe, is to take the lowest common denominator as the prevailing tuplet. The 15/8 case you mention would normally be written as 5 against 4 in standard triple time, and, indeed, I seem to recall a late Scriabin étude that did just that (against triplets in the left hand). I'd have to dig out my Dover edition of the preludes and études to be sure...
Comment: @Patrx2 Thank you! Best explanation so far (unfortunately since I'm a new member I can't vote up your answer), but I'm still a bit confused. I'm starting to understand individual time signatures that I've been working with like of course 12:8 and 6:8 but my original goal was to learn how to work with an **unknown** one. You said that being divisible by 3 two times (9) makes the "unit of beat is equal to the three of the note values specified by the bottom of the time signature." But then you used 15/16 as an example...And what if I was given a time signature like 12:4 or 11:2?
Comment: And I believe I also saw you mention the lowest common denominator. So in let's say, 6:4 time, it would be 6 quarter notes (crotchets?), but with 2 (common denominator) as the unit of the beat, therefore making it 3 groups (triple?) of 2 quarter notes...? Again thank you, sorry if these questions seem pitiful!
Comment: Last thing! Of course when given an odd time signature like 5/4, the common denominator would be 1. And surely it would not usually be one group of five quarter notes. But I remember seeing divisions of 2/4 and 3/4. Is this usually how it works when the time signature is odd?
Comment: @cbarkachi - 5/4 is usually split 2 and 3, or 3 and 2. 7/4 3 and 4, or 4 and 3. Sometimes 2,2 and 3. Other related questions here hold answers which go deeper.
Comment: Quarter note = crochet, yes. Sorry, I normally use British terminology, but I adapted my answer for an American milieu. For a time signature of 6/2 (rather rare), you would have 2 groups of 3 minims, so the unit of beat would be the dotted semibreve. For 12/4, you would have 4 groups of 3 crochets, so the unit of beat would be the dotted minim.

For time signatures like 5/4 and 7/8, the unit of beat is the note value at the bottom of the signature, but the beats are grouped as if there were two or three bars of different meter put together. (Cont...)
Comment: That means that 5/4, say, can act like a bar of 3/4 followed by a bar of 2/4, or vice versa, precisely as Tim said. You distinguish which division is being used by looking at the context.
Answer: NO!
6/8 is not six groups of quavers it is compound duple time with each bar consisting of a dotted crotchet. If you group six quavers together it implies 3/4 time.

12:8?
  Here you have compound Quadruple time with each beat consisting of a dotted crotchet
4:2?
  Here you have four groups of minims

Now let us think critically of what a time signature is. Time signatures at is very root try to explain to you the amount of time or notes that the bars of the music should have.
There is two numbers but what do they mean I can hear you ask? Well the first number tells us how many groups of notes we have and the second tells us what each group consists of.
So let us take 2/4 time as an example. The first number tells us the number of groups ie 2 and the second number tells us that the groups consist of crotchets ( 2 = minims 4 = crotchets 8 = quavers)
But wait there is more. There is a second type of Time signatures. They are called compound time signatures. No all these do is add dots to our groups but for the most part the same effect applies.
6/8 is compound duple time with groups of dotted crotchets. 9/8 is compound triple time with beats of dotted crotchets and so on and so forth.
Hope that helped.
Comment: Yes.  If 6/8 is "six eighths in the bar" so is 3/4.  But in fact 3/4 is "three quarter-notes in the bar", 6/8 is "two dotted quarters in the bar".  Convention, as much as arithmetic.


C++0x: conditional operator, xvalues, and decltype

Question: I am reposting a comp.std.c++ Usenet discussion here because that group has become very unreliable. The last few posts I've submitted there have gone into the void, and activity has all but ceased. I doubt I've been banned and/or everyone else just lost interest. Hopefully all interested people will find this discussion, and there will be a general migration. Maybe then they will appoint a new moderator.

Hello!
With my current interpretation of draft N3126 w.r.t. the conditional
operator and xvalues, I expect the following assertions to hold:
 int i = 0;
 int& j = true? i : i;
 int&& k = true? std::move(i) : std::move(i);   // #2
 assert(&i == &j); // Holds since C++98
 assert(&i == &k); // Should this hold as well?

5.16/4 says:

If the second and third operands [to
  the conditional operator] are
  glvalues of the same value category
  and have the same type, the  result is
  of that type and value category [...]

Though, it doesn't clearly say that the resulting glvalue refers to
one of the objects the glvalue operands referred to -- or is this
implied because otherwise it would return a prvalue? Using GCC 4.5.1
in C++0x mode the second assertion fails. The reference k seems to
refer to some temporary object. Can somebody clarify whether the
comiler is allowed to create such a temporary in case both operands
around the colon are xvalues of the same type?
I'm currently assuming GCC is buggy and/or not up-to-date with respect
to xvalues.
The followup question is: Wouldn't it be nice to be able to detect the
value category of an expression? If we ignore the conditional operator
we can detect the value category of an expression with decltype. But
what is
 bool xvalue = std::is_rvalue_reference<
   decltype( true ? std::move(i) : std::move(i) ) >::value;

supposed to yield? Using GCC 4.5.1, the xvalue variable is initialized
with false. Is this conforming to the current standard draft?
TIA,
Sebastian
Comment: You can also e-mail Pete Becker (email@example.com) with typographical and editorial errors (like a spelling error). The whole defect reporting process is too confusing, IMO. It'd be nice if the committee had Bugzilla or Trac or something that made it easy to report issues (of course, they'd probably say the correct way to submit defects is to join the committee, but the $1,200/year fee is a bit steep for that privilege).
Comment: @MSalters:  I meant that half-jokingly; every time I've interacted with committee members they have been very helpful.  Anyway, in general, if someone wanted to formally participate, they'd have to join; for those in the US, the fee for joining INCITS J16 is $1,200/year.  I know that if I wanted to and had the time to participate, I could probably do so through my employer, but many people don't have that option.  Of course, having a high barrier to entry probably keeps the noise level down, which is usually a good thing.
Comment: There are supposedly [five moderators](http://www.comeaucomputing.com/csc/faq.html).  Have you tried contacting them (email@example.com)?
Comment: I think you mean [comp.std.c++], as implied by your link. Yes it does have some lag time but I think you may have just encountered a recent Google blackout. Did you post via Google Groups?
Comment: @Alf: I do post by Google Groups, but wouldn't that affect all groups? There is virtually no activity at comp.std.c++ since September, not so for the unmoderated groups.
Comment: From here c.l.c++ has 30 postings for my local "today", c.s.c++ has two (one of them from "SG", which seems to be you), and another five messages for earlier from other people this month.
Comment: @sbi: I'm David Krauss on comp.lang.c++ (and real life); this post is community wiki because I'm reposting on someone else's behalf. `comp.lang.c++` is unmoderated, so it has more activity because there is no moderator asleep at the wheel. `comp.std.c++` has seven messages for October vs. dozens for September because the moderator has all but quit. I don't know why or how he manages to let such a small, yet nonzero, trickle through.
Comment: Since `comp.std.c++` is a semi-official channel for submitting defect reports, I've created the `c++-defect` tag to correspond to that sort of thing. Maybe there can be a process for forwarding questions to the committee once they've been vetted.
Comment: @James: No, I'm not the boss of them and I'm not an activist, at least not within the ISO committee framework (until if and when they recognize me, I suppose). If they don't want to do their job, and if the community can get by without them, they're free not to do it. But it's plainly apparent they're not.
Comment: Fair enough.  For what it's worth, there are instructions on how to submit a library defect on the [LWG defects page](http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html) basically saying just to send an e-mail Alisdair Meredith, LWG chairman (Howard Hinnant, who was LWG chairman until September, said he hadn't gotten a notification from the newsgroup moderators in a few years).  For language defects, the CWG defects page just refers to the comp.std.c++ FAQ for how to submit a defect; I suppose it couldn't hurt to e-mail Mike Miller to see what the best way to get defects to them is.
Comment: @James: Yep. For that matter, I've sent 3 emails to Alisdair in the past month with no reply. Probably because they consist of a minor spelling correction, a dangling reference correction, and a request to specialize `std::tuple_element` and `tuple_size` on `bitset`. So I don't worry too much. But submitting a detailed two-page answer to `comp.std.c++` seems a lot like just feeding someone's spam filter.
Comment: @James McNellis: You can't join the committee directly; ISO's members are the national organizations (in your case, INCITS(USA)) and national organisatsions usually have company memberships. Your profile suggests you work at Microsoft, which has already paid the INCITS fee and is active within the ISO committee.
Answer: I think GCC 4.5.1 is nonconforming wrt §5.16/4. Have you filed a bug report?
Anyway, I think it is conforming with that ternary operator code. decltype is defined by §126.96.36.199/4:

The type denoted by decltype(e) is
  defined as follows:

if e is an unparenthesized id-expression or a class member access
  (5.2.5), decltype(e) is the type of
  the entity named by e. If there is no
  such entity, or if e names a set of
  overloaded functions, the program is
  ill-formed;
otherwise, if e is a function call (5.2.2) or an invocation of an
  overloaded operator (parentheses
  around e are ignored), decltype(e) is
  the return type of the statically
  chosen function;
otherwise, if e is an lvalue, decltype(e) is T&, where T is the type
  of e;
otherwise, decltype(e) is the type of e. The operand of the decltype
  specifier is an unevaluated operand
  (Clause 5).

decltype works by fetching the appropriate declaration and returning the desired type from it. It has little intelligence with respect to non-overloaded operators. Perhaps another point

otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e

would be in order, particularly since, as written, xvalues get treated as prvalues. Furthermore, your expression corresponds exactly to the definition of std::common_type (§184.108.40.206/3).
One straightforward workaround (to coin a phrase :vP ):
template< typename T1, typename T2 >
struct common_type_and_category {
    typedef typename std::conditional<
        std::is_same< T1, T2 >::value,
        T1,
        typename std::common_type< T1, T2 >::type
    >::type type;
};


Find a recurrence relation for a quinary string with NO consecutive zeros

Question: For n ≥ 0 let a(n) be the number of quinary strings (only contain digits among 0 . . . 4) of length n and do not contain the string 00. Find a recurrence relation and give initial conditions for the sequence a0 , a1, ...
Completely confused with this question, how do I go about find a recurrence relation for a quinary string?
Answer: Let a string be called valid when it has your property. Let $a_n$ denote what you mentioned. Let $c_n$ denote the number of $n$ digit quinary strings without $00$ with the additional condition that the string does not have a $0$ at the end. Let $b_n$ denote the number of $n$ digit quinary strings without $00$ with the additional condition that the string has a $0$ at the end. It is easy to see that $a_n=b_n+c_n$. Also, one has these relations:
$$b_{n+1}=c_n$$
$$c_{n+1}=4a_n=4(b_n+c_n)$$
The first one comes from the fact than any valid string with no $0$ at its end can be extended to a valid string with a $0$ at the end by appending a $0$. For the second one, if we have any valid string then we can append one of $1,2,3,4$ at its end to get a valid string without a $0$ at its end. Using this, we get $c_{n+1}=4(c_n+c_{n-1})$ and $b_{n+1}=4(b_n+b_{n-1})$ and on adding we get $a_{n+1}=4(a_n+a_{n-1})$.
Comment: Thanks for the quick answer, Manan! Unfortunately, I am still a bit confused with your explanation...
Comment: A) In the first part of your answer you say a(n) = b(n) + c(n). So an example of that would be 140230 = 1402 + 30. B) Then, I am also confused with the second relation c(n+1) = 4a(n)... where does the 4 come from?
Comment: We need to find $a_n$. First, we break $a_n$ into two parts $b_n$ and $c_n$. $b_n$ counts the number of $n$ digit valid strings with a $0$ at the end, and similarly no zero at the end for $c_n$. We are not breaking up the string itself. We are just counting valid strings with complementary properties and then adding up to get the total number of valid strings.
Comment: A string contributes to $c_{n+1}$, that is, is of $n+1$ length and is valid without a $0$ at the end if and only if its last digit is not $0$ and the string formed by its first $n$ digits is valid. Now, the last digit has $4$ non zero choices, namely $1,2,3,4$ and the number of valid strings with $n$ digits is just $a_n$.
Comment: The recurrence is in https://oeis.org/A086347 .


How to calculate the width of the Windows CMD shell in pixels?

Question: I'm working on a Python shell script that is supposed to fill a percentage of the user's screen. The shell's width, however, is calculated in characters instead of pixels, and I find it difficult to compare them to the screen resolution (which is obviously in pixels).
How can I effectively calculate the width in characters with only the screen pixels while still being able to support both Windows and Linux?
For the sake of the question, let's assume none of the users have changed their shell settings from the default ones.
Answer: You cant but the default command prompt dimensions are 677, 343. The height being 677 and the width being 343, hope this helps.