Why do we study real numbers?

Question: I apologize if this is a somewhat naive question, but is there any particular reason mathematicians disproportionately study the field $\mathbb{R}$ and its subsets (as opposed to any other algebraic structure)?
Is this because $\mathbb{R}$ is "objectively" more interesting in that studying it allows one to gain deep insights into mathematics, or is it sort of "arbitrary" in the sense that we are inclined to study $\mathbb{R}$ due to historical reasons, real-world applications and because human beings have a strong natural intuition of real numbers?
Edit: Note that I am not asking why $\mathbb{Q}$ is insufficient as a number system; this has been asked and answered on this site and elsewhere. Rather, why, in a more deep sense, are $\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q} \subset \mathbb{R}$ so crucial to mathematics? Would we be able to construct a meaningful study of mathematics with absolutely no reference to these sets, or are they fundamentally imperative?
Comment: The first question is *do* mathematicians study real numbers disproportionately?
Comment: You might be surprised by how few mathematicians study $\mathbb R$.  There are lots of areas of mathematics, and many of them don't have much to do with $\mathbb R$.
Comment: The OP may be interested in spending some time reading [this](https://www.dpmms.cam.ac.uk/~wtg10/reals.html) dialogue (or should I say trialogue?) concerning the real number system, written by Timothy Gowers of Field's medal fame. I'm not sure it entirely answers your question, but it's certainly related and it's probably worth a read.
Comment: @ASKASK: If one were in the mood, one could easily play devil's advocate and argue that, in fact, every feasible measurement in the real world is only a *rational* number, since measuring a real number would require "infinite precision". But there are already many discussions on the internet about this, so let's not get bogged down...
Comment: Concerning the recent edit: you appear to have changed the nature of the question. Before, you were (and in the title, you still are) asking specifically about real numbers. But in your edit, you are talking about the whole gamut: $\mathbb{N}\subset\mathbb{Z}\subset\mathbb{Q}\subset\mathbb{R}$. This is a very different question: you are essentially now asking "why is mathematics about numbers?", to which my only answer is, "what else are you expecting?" Numbers are crucial to mathematics because mathematics, as a subject, has been built around them; they are part of the definition of the word.
Comment: Real numbers, when viewed from an analytic standpoint, are very convenient to work with, and as their name suggests, they tend to reflect the real world in some sense -- every feasible one-dimensional measurement in the real world is a real number.
Comment: Some may consider your question naive, but I don't. There are all sorts of reasons, many coming from physics. The alternative, I guess, would be to try to do everything in rational numbers. But we don't have an Intermediate Value Theorem there, and I think that that's one of the most useful properties of the reals. (Others will have different opinions.)
Comment: Historical reasons in some sense, I suppose. I could imagine some kind of alien civilization that does not use integers at all and only does computations in the symmetric group, say, but it seems very unlikely.  It's hard to get very far without making some reference to a number - the order of the group, or the number of subgroups, etc.  Personally, I would guess numbers are inevitable as a starting point for math because they are simplest useful things that it's possible to study logically.
Comment: @ASKASK "and as their name suggests, they tend to reflect the real world..." Gauss, great mathematician, himself wouldn't agree with you. Complex numbers are present in everyday life same just as real numbers. **It is the misleading name "imaginary" that makes people think that they are useless.** Gauss proposed the name "lateral" instead of "imaginary". And I agree with him. **Imaginary numbers are everywhere, we just don't see them because we don't think they are real just because of its name "imaginary"** and the tortures we get with them first time we see them in Algebra II class.
Comment: Well, it is the unique (up to isomorphism) complete (no gaps; continuous) totally ordered (we can compare everything to everything else) field (we can do stuff like adding and un-adding, as well as multiplying and un-multiplying [by nonzero things!]; addition and multiplication get along)... and all of that sounds like what we'd like, from a nice number system!
Comment: not sure the mathematicians study $\mathbb{R}$ so much, I am convinced it is much more about $\mathbb{R}_{definable}$ and because it is boring to state everytime "definable" (and because mathematicians are not so good in logics and computer science) we do as if we were considering $\mathbb{R}$, even if we are not (and sometimes it leads to paradoxes)
Comment: @WillR ah I misused the word "feasible". I think "theoretical" would have been a better word choice
Comment: With the edit, it seems almost like you want to ask about the importance of $\mathbb{N}$ rather than $\mathbb{R}$, since you seem to accept the reasons for passing from $\mathbb{Q}$ to $\mathbb{R}$ or $\mathbb{N}$ to $\mathbb{Q}$.
Comment: @WillR No, in my original question I made reference to 'subsets' of $\mathbb{R}$. Besides, isn't it already a given that $\mathbb{R}$ includes its subsets?
Comment: It's a given that $\mathbb{R}$ includes it's subsets, but studying $\mathbb{R}$ is very different to studying $\mathbb{Z}$ or even $\mathbb{Q}$ (and $\mathbb{N}$ is only a monoid under addition, so let's not even go there...). Also, "subsets of $\mathbb{R}$" is very vague: topologists might study "subsets of $\mathbb{R}$", but they would mostly be interested in things like connectedness and compactness, so they might not be so interested in the specific subsets to which you are referring.
Comment: @KKZiomek I agree with everything you've said, but I'd like to point out that nothing you said actually disagrees with anything I said. Both systems reflect the real world in different ways
Comment: @WillR Fair enough. If you believe "numbers are crucial to mathematics because mathematics, as a subject, has been built around them" then you have an answer to my question: historical reasons.
Comment: @JairTaylor You understand the gist of my question:) In fact, I had the "alien" analogy in mind as well.
Comment: Out of necessity.
Comment: @user1952009 I don't believe that's true at all. There *are* differences between real-analysis and analysis on the definable reals, and there *is not* that much work done on the definable reals. (Heck, there wasn't even a clear idea of what that would mean until after Turing and Church started working on it.)
Comment: @RobertIsrael I assume the question is regarding *analysis* rather than e.g. algebra, especially since it's tagged "real-analysis".
Comment: @KyleStrand : yes of course, but regarding the question of the OP, I couldn't avoid talking of the definable real numbers (aka the "real life"  numbers)
Comment: OP, my personal opinion (which is not quite rigorous nor evidence-based enough to work as an answer) is that this is ultimately due to the *assumption* (throughout all of mathematical history) that the Platonically "real" world is *continuous* in space, i.e., that it is well-modeled by the mathematical concept of the *continuum*. Further, I would opine that this is pure nonsense, given the [difficulty of defining uncomputable numbers](http://math.stackexchange.com/q/1266587/52057) and the [paradoxes arising from the continuum](https://en.wikipedia.org/wiki/Banach%E2%80%93Tarski_paradox).
Comment: @user1952009 I completely agree that the concept of "definable reals" is relevant to OP's question! I just don't agree that mathematicians typically "really" mean the "definable" reals when they're talking about the real numbers, or that mathematicians "aren't so good" at logic.
Comment: Re: the Intermediate Value Theorem and the implication that it *necessitates* acceptance of the standard Reals in order to have a set that behaves "sensibly" in analysis, see: http://mathoverflow.net/q/9000/70495
Comment: There are other fields which may be interesting to study such as the computable numbers or the surreal numbers. But I think many theorems about those fields will be easier to prove if you rely on proofs about the rational numbers.
Answer: I've often asked myself the same thing, and this is what I tell myself. $\mathbb R$ is (up to order-preserving field isomorphism) the only totally ordered, complete field. This is pretty big news, because these two nice structures lead to so many others we find useful to study in math. $\mathbb R$ (and more generally $\mathbb R^n$) is so great because a plethora of these fundamental "structures" studied in math are present in (at least some subset of) $\mathbb R$. When we learn of new concepts, it's natural (crucial) to seek examples, and we often find solace in the usual first stop -- $\mathbb R^n$.
Here's a poor-at-best survery of some of the aforementioned structures that $\mathbb R$ has.
Algebra

Group -- we can combine elements, i.e., $a + b$, invert them, i.e., $a^{-1}$.
Field -- we get more ways to combine elements, $+, -, \times, \div$.
Ordered field -- we get to do things like transitivity, i.e., $a < b \wedge b < c \implies a < c$, and "add inequalities", i.e., $a \leq b \wedge c \leq d \implies a + c \leq b + d$.
Vector space -- linear algebra's pretty important. Arrow-like addition is very physical.

Analysis

Completeness -- analysts love sequences... to converge. This allows for a lot of "take a sequence..." arguments which start with a probably-desired sequence that ends up being Cauchy.
Compactness -- we always want to exploit compactness in analysis, and $\mathbb R^n$ has a particularly nice characerization of it.
Hilbert Space -- we all love Hilbert space. Orthogonality is a useful tool. So is the spectral theorem.
Measure space -- measuring is very physical, and crucial for integrating! $\mathbb R$ is the natural setting for the famous Lebesgue measure, and all measures map into the "subset" $[0,\infty]$ of $\mathbb R$. For Riemann integration, the (Darboux) definitions hinge on the least upper bound property of $\mathbb R$.

Geometry

Metric Space -- we can measure distances $d(p,q)$ between points. This is very physical. The triangle inequality is here too, which is even more useful in normed spaces, where it reads $\|u + v\| \leq \|u\| + \|v\|$, because it leads to many useful estimates in analysis.
Manifolds -- things that by definition locally look like $\mathbb R^n$. Many "objects" that we deal with early in math are manifolds (we just didn't know it at the time).
All of the separation axioms (Hausdorff, regular, normal, ...).
All of the countability axioms (separable, Lindelof, ...).

Not shown (for the sake of space and the inevitable lack of completeness) is the interrelatedness between many of these properties for $\mathbb R$, which is another indispensable virtue of $\mathbb R$.
Comment: Absolutely. Manifolds are basically defined as "let's keep all the nice properties of $\mathbb{R}^n$".
Comment: Given a totally-ordered field, completeness is equivalent to the least-upper-bound property, and the Archimedean property follows from the least-upper-bound property.
Comment: [This similar question](http://math.stackexchange.com/questions/1066176/why-are-every-structures-i-study-based-on-real-number?rq=1) has a very good answer.
Comment: Isn't $\mathbb R$ the only totally-ordered complete *Archimedean* field?
Comment: Note that it's possible to define a somewhat-analogous concept of "computable completeness" that *does* apply to the computable reals, even though the traditional Dedekind (or equivalent) definition clearly *does not* apply: http://math.stackexchange.com/a/418011/52057
Comment: I knew I'd forget really important things to mention -- manifolds is a perfect example!
Comment: Manifolds are also defined over non-Archimedean fields. They just have slightly different properties.
Comment: Nice answer. As far as I understand $p-$adics are the only valuable alternatives to $\mathbb{R}$ as extensions of rationals, but they are not totally ordered. Is it correct?
Answer: There's no way to do justice to "Why is mathematics about real numbers?" within the length constraints of a Math.SE post, but here are some relatively philosophical observations and opinions (meant to be a bit provocative, in the spirit of answering a soft question).
First, as multiple people have commented, the real numbers are not universally regarded as the be-all/end-all number system. In The Road to Reality, for example, Penrose argues that complex numbers are more fundamental for physics.
Setting that aside, why do we count, and where did natural numbers, integers, and rational numbers come from? I'm not a historian, so everything below should be regarded as a parable, biased by modern mathematical training.
Counting (both the possibility and the ability) arises from the tension between variation and uniformity in the natural world:

Thanks to variation, there are "different types of thing": that piece of granite, that oak tree over there, the pine tree next to it.... If we look closely at the natural world, we find it to be made of unique objects, to occur in unique, irreproduceable events. In fact, the notion of "event" is our way of cutting the solid stream of existence into temporal and spatial chunks. As Heraclitus said, you cannot step in the same river twice.
Thanks to uniformity, there are recognizable "classes of things": rocks, trees, snowflakes, stars, sunrises.... No two rocks (or trees, or snowflakes...) are exactly alike. At the very least, they're "in different places" or "at different times" (otherwise they'd be identical).

Once the natural world is observed to contain classes of things, "counting" is a reasonable way to measure "how many/how much". In (a paraphrase of) Kronecker's famous quotation, The integers alone were created by God. All else [in mathematics] is the work of Man. To the contrary, the natural numbers (and therefore the integers) were created by us, as well, an abstraction for enumerating distinct objects similar enough to group together for some purpose.
To make a long story short:

An integer is a measure of additive comparison between two natural numbers. That is, it's a thing comprising a relationship between two other things. The standard construction of the integers in set theory merely formalizes this: An integer is an equivalence class of ordered pairs $(m_{1}, n_{1})$ of natural numbers, with $(m_{1}, n_{1}) \sim (m_{2}, n_{2})$ if and only if $m_{1} + n_{2} = m_{2} + n_{1}$.
A rational number is a measure of multiplicative comparison between two non-zero integers. The standard construction of the rationals blah, blah, blah.

It's unsurprising that both abstractions were invented: If two people have flocks of sheep (say), it's natural to ask "who has more sheep, and by how many?". It's natural to represent debts as negative integers. If a flock of sheep (well...) must be divided among several people, it's natural to ask "What is each person's portion?", and to use rational numbers to represent the answer.
The real numbers obviously arose many centuries later, under pressures of Archimedes' method of exhaustion (for which one needs numbers representing "limits of rational sequences"), and were formalized two millennia after that in order to put calculus on a solid logical footing.
I won't even touch the complex numbers, partly for last of time and space (heh), but mostly because Penrose (and many others) do so far more competently, with the depth the subject deserves.
Comment: There is some evidence that natural numbers are not a convention "created by us", by actually an *a priori* function of the brains of humans and some other animals. I've seen a video of Noam Chomsky hypothesizing that an evolutionary mutation was required to permit the brain to entertain limitless counting, and that language would be an extrapolated development after that.
Comment: You're not really addressing why, specifically, we use real numbers instead of some other extension of the rationals, which is, I think, the most important aspect of the question.
Comment: @Kyle: Fair enough. I was musing on why the natural, integer, and rational numbers arise naturally for humans, given the OP's clarification, "Note that I am *not* asking why $\mathbb{Q}$ is insufficient as a number system; this has been asked and answered on this site and elsewhere. Rather, why, in a more deep sense, are $\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q} \subset \mathbb{R}$ so crucial to mathematics? Would we be able to construct a meaningful study of mathematics with absolutely no reference to these sets, or are they fundamentally imperative?"
Comment: @Daniel: Interesting; thank you for the video link. Again, I was deliberately being a bit provocative in saying humans invented the natural numbers, but although Peano's axioms for the natural numbers are simple and close to everyday experience, I don't see that the natural numbers exist in a manner independent of human minds. Practically speaking (e.g., in terms of classical computation), I see no way to distinguish the infinite set of naturals from a sufficiently long interval $\{0, 1, 2, ..., N\}$. (Maybe this is a semantic issue with the meaning of "exist".)
Comment: See: https://www.youtube.com/watch?v=aNwWQyLWcYM&feature=youtu.be&t=33m25s
Comment: @AndrewD.Hwang Fair enough--I'm probably considering the leap from $\mathbb{Q}$ to $\mathbb{R}$ to be the "most important aspect of the question" due to my own personal bias against $\mathbb{R}$ (as is probably evident from my comments on the original question).
Comment: Dear Andrew: I hastily accepted another answer previously. Reading through the answers more carefully now, I feel yours best answers what I was trying to ask, so I have changed it. Thanks.
Comment: Actually when teaching physicists, you you can replace teaching of complex numbers with teaching of ordered pairs of real number and say which operations on ordered pairs of real numbers you're using. Then they'll still claim that they're using the real number system which works well for physics. Despite that, it might still be useful for being smarter for them to understand that the real number system is not the only system and we can specifically construct the real number system or we can specifically construct the hyperreal number system.
Answer: A nice property of real numbers is that they are complete: every Cauchy sequence converges.
In analysis, mathematicians like to study spaces that are complete. People study Banach spaces rather than ordinary normed spaces; study Hilbert spaces rather than ordinary inner product spaces. A space that is not complete does not have as nice properties as complete spaces.
Ever since Pythagoras' disciple discovered that $\sqrt 2$ is irrational, that was the beginning that signals that the rational numbers $\mathbb{Q}$ is not enough to represent all quantities.
However, there are some "problems" with the real numbers, and I know at least one professor (not to mention his name here) who does not believe in the real numbers. His reason, if I remember correctly, is that once you go deeper, a real number is not just a string of decimals: it is a equivalence class of Cauchy sequences. Not only is each Cauchy sequence infinite, each equivalence class is infinite (uncountable I think). This is the price to pay for dealing with real numbers.
Answer: It's also worth noting that this representative of is a strong bias towards analysis. An algebraist generally cares minimally about $\mathbb{R}$, generally field extensions of $\mathbb{Q}$ and $\mathbb{F}_p$ are far more interesting. The badly named so-called Real Numbers are very much unimportant in Combinatorics and Number Theory compared to other sets, but mathematicians spend much more time talking about the Real Numbers because there is a strong bias, both in collegiate education, and younger education, towards analytic topics over algebraic or topological ones.
Comment: I'm not sure I agree with this.  Even if the thing I'm really interested in is algebraic extensions of $\mathbb{Q}$, I will end up studying completions like $\mathbb{C}$ and $\mathbb{Q}_p$.  If I think I'm a combinatorialist, I might still end up using generating functions and doing countour integrals for asymptotics (e.g. to prove Stirling's approximation).  Perhaps the reals are over-emphasized in the standard curriculum, but they don't cleanly belong to "analysis", and I would think that the vast majority of mathematicians care about them in some form or other.
Comment: I mean, yes it comes up (I'm not saying it doesn't), but the idea of R as foundational is basically an analysis thing.
Answer: An amazingly large part of Riemann-Stieltjes integration theory, as given in Apostol's Mathematical Analysis, can be developed in the setting of rational number system. Completeness property of real number system is needed, only when we try to prove that every continuous function is integrable.
It's the existential proofs of various theorems in Mathematics, that are the things of real challenge. They take 90% energy of a mathematician. Applied mathematicians and theoretical physicists don't take bother in proving existential theorems, and thus, they save their 90% energy.
The whole edifice of Dedekind's construction of real number system is meant to prove: There exists a complete ordered field.
Answer: Because of settling on late 19th century and early 20th century formalization of the idea that R is supposed to represent. Plenty of people study variations on R that may look more like what for example physicists may be used to, like for example variations with infinitesimals.

Why do we study real numbers?


Logging out from IdentityServer quietly?

Question: I'm using OAuth2 from an IdentityServer 4 instance. Based on this example, I'm able to  login and call an API hosted by the server.
How would I perform a logout from OidcClient without showing a webview prompting the user to confirm the logout?
At present, I'm using the following code to logout, but the library still displays a webview with a logout prompt. I'd ideally want to just process the logout without showing any additional popups:
await _client.LogoutAsync(
    new LogoutRequest {
        BrowserDisplayMode = DisplayMode.Hidden,
    });

Answer: The LogoutRequest contains an IdTokenHint property for this. If you want to disable the logout-prompt, you'll need to set this as the id_token for the current user. See the OIDC spec for this here:

id_token_hint
RECOMMENDED. Previously issued ID Token passed to the logout endpoint as a hint about the End-User's current authenticated session with the Client. This is used as an indication of the identity of the End-User that the RP is requesting be logged out by the OP. The OP need not be listed as an audience of the ID Token when it is used as an id_token_hint value.

By providing the id_token with this request, the authority can be sure that the signout request itself is authentic and therefore deem that there is no need to prompt the user.
If you don't have the id_token, you'll need to request it when first authorising the user and then hold on to it for later use.


icCube - Synchronise and refresh The Data Source Tables [Fixed Period]

Question: On each time I update or change the data base, I must go to icCube server and clicked on

"Rafraichir les tables de la source de données "

I want to fix a period or have a solution to refresh the data source automatically.
Answer: Those features are part of the Enterprise version (Scheduler, XMLA commands for managing the server ... ).


"systemctl start service" when service already started

Question: I, what happen's precisely when you run systemctl start apache2 (or other service) while service already started ?
Can it cause trouble to start several hundred times a day apache2 service? (to prevent the service from shutting down) or can it use memory or be dangerous?
Comment: I think it executes the same code it would execute if it was starting it for the first time, which doesn't seem much safe if you have your service running and you want it to behave correctly while you call systemctl start.
Answer: Why don't you just use systemctl is-active to check whether it is running?
For example:
systemctl is-active --quiet apache2 || systemctl start apache2


Check existance of domain accounts with Powershell script

Question: Is there a Powershell cmdlet or script to query Active Directory if a given domain account (such as "myDomain\myUser") exists?
Answer: This is what we use to validate accounts. It relies of course on Import-Module ActiveDirectory and either a 2008 R2 DC, or a DC running ADWS:
function validateUser
{
    param(
    [string]$username
    )

    # If the username is passed without domain\
    if(($username.StartsWith("domain\")) -eq $false)
    {
        $user = Get-ADUser -Filter { SamAccountName -eq $username }
        if (!$user)
        {
            return $false
        }
        else
        {
            return $true
        }
    }
    elseif(($username.StartsWith("domain\")) -eq $true)
    {
        $username = ($username.Split("\")[1])
        $user = Get-ADUser -Filter { SamAccountName -eq $username }
        if (!$user)
        {
            return $false
        }
        else
        {
            return $true
        }
    }
}
$userCheck = validateUser -username smith02
if($userCheck -eq $true) { do stuff } else { user doesn't exist }

Comment: +1 for this one because it uses native powershell cmdlets.
Comment: My inbox seems to show a little bit more of your reply; something about streamlining it. If you still want to, please feel free to do so!
Comment: Hey robin. I did originally write that but then I realized i didn't quite have time to do it. Maybe tomorrow...
Answer: Old question, I know, but I feel I need to add this bit here because none of the previous answers use any form of error handling.
Also, if you need to support users from multiple domains, you will have to query the correct domain controller (or query the Global Catalog and specify the DN of a directory partition).
$Domainname = 'ABC'
$Username = 'Administrator'

Try
{
   $DomainController = Get-ADDomainController -DomainName $DomainName -Discover -ErrorAction Stop
   Get-ADUser -Identity $Username -Server $DomainController -ErrorAction Stop

   # user account exists
}
Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
{
   # no error, user account does not exist
}
Catch
{
   # Domain controller not found, domain unreachable, authentication failure or another error occurred
}

Comment: +1 for adding a response to my 6 year old question! :)
Answer: You can use the Directory Searcher .net object to do this.
Here is a very un-optomized code snippet from one of my utility scripts that has fallen by the wayside.
$AD = [ADSI]"<ldap_connection_string>"
$query = New-Object System.DirectoryServices.DirectorySearcher
$query.SearchRoot = $AD
$Users = $query.FindAll() | Where-Object {$_.properties.objectclass -eq "user"}

So you should be able to change the .objectclass to .cn or .name and then match against that.
Or don't be lazy like I am and read up on how to construct a proper query :)
Answer: I would grab the Quest AD Roles cmdlets - http://www.quest.com/powershell/activeroles-server.aspx - and user their Get-QADUser cmdlet with the -Identity parameter.
For example,
$username = "mydomain\myusername"

if (Get-QADUser -Identity $username)
{Write-Host "It's alive"}
else
{Write-Host "Account does not exist."}


How can I add a way to jump months using the calendar module

Question: I have a calendar being shown by month. How can I add an exposed filter or dropdown so users can jump ahead to any month and year?
Comment: Each month display has a predictable URL, eg: May 2016 might be domain.org/16/05/. Can you use a menu to just take them to the relevant URL?
Comment: What have you already tried? Views, Date, and BEF provide some of this ability out of the box (one solution here: https://www.drupal.org/node/2481343).
Answer: Add Below code for your calendar. Click This link for example
<code>$(function () {
  $("#datepicker").datepicker({
    changeMonth: true,
    changeYear: true
 });
});
</code>


What is the best data structure to use to store the large student list?

Question: I want to write a program to store the student list(every student has name,birth day, address,.....), I want to this program is good performance for searching student(such as find student with name == 'Peter' and address='NY'), and inserting new student into list, student list is very large. I don't know what is the best data structure to use. Thank for helping.
Comment: How large is large? And how good is good?
Comment: Is the data in a database? Is it in a flat file? Is it being returned from a web service? Do you have a programming language in mind?
Comment: Use a database with appropriate indexes.
Comment: it is not a website, it is a program is written in C to demo data structure.
Comment: If you are demoing data structures, then you should implement it several different ways, and then show advantages and disadvantages. There is no best, there's optimal, and whether it is depends...
Answer: Then you're talking about something like that:
These are advanced data structures that achieves the performance requirement you imposed.
http://en.wikipedia.org/wiki/B-tree

In computer science, a B-tree is a tree data structure that keeps data
  sorted and allows searches, sequential access, insertions, and
  deletions in logarithmic time. The B-tree is a generalization of a
  binary search tree in that a node can have more than two children.
  (Comer 1979, p. 123) Unlike self-balancing binary search trees, the
  B-tree is optimized for systems that read and write large blocks of
  data. It is commonly used in databases and filesystems.

http://en.wikipedia.org/wiki/Hash_table

In computing, a hash table (also hash map) is a data structure used to
  implement an associative array, a structure that can map keys to
  values. A hash table uses a hash function to compute an index into an
  array of buckets or slots, from which the correct value can be found.
Comment: Please, choose a anwser and vote up. Its the way to thanks. You're welcome!
Answer: Sounds you are on the way of "reinventing the wheel". What you request is database like stuff. You can consider some in-memory database solution, such as H2 or Derby.


Bad page display when search terms include char /

Question: I have an URL that display the results of a search. My .htaccess looks like this:
Options FollowSymLinks
Options -Multiviews
RewriteEngine On
Rewriterule ^search-(.*)-(.*)-(.*)-([0-9]+)$ basic.php?token=$1&service=$2&location=$3&pageNumber=$4
When service or location doesn't include any special char the query works perfectly, but if someone search something like c/ street Name or simply the search string includes \ (backslash) my application shows the search page but with no styles (only plain text and no button works).
I guess this is happening because the URL is like http://domain.com/search-token-lawyer-c/street%name and the / char is creating the trouble.
How can I  fix it?
Thank you in advance
Answer: Add in your basic.php html header code:
<base href="/">

Comment: Ok fixed, thanks for giving the hint.

I included
Comment: Now all searchs looks like the search page with no styles
Comment: Use absolute link for css file (or relative to root with `/directory/...`)


Get-AzureWebsite cmdlet returns no instances, but my site is live. How can I query and update it?

Question: I'm having trouble updating an Azure-hosted web application via Visual Studio Team Services. While trying to diagnose the problem, I seem to have run into some more fundamental problems with querying my Azure websites that I'm unable to work around.

I'm using Visual Studio 2015, Visual Studio Team Services and Azure hosting
to build and deploy a web application project. I've installed Azure
Powershell for management.
I've created a Web App project using ASP.NET MVC and checked it in to
my .git repository on VS Online.
Using the VS Team Services tools, I've created a build definition that
includes a deployment step to my Azure host. This build runs
automatically upon check-in and worked fine the first few times it ran -
the site deployed and was immediately available at
[mywebapp].azurewebsites.net.

Starting yesterday, the deployment step has failed at the following lines:
<code>Get-AzureWebSite -Name [mywebapp] -ErrorAction SilentlyContinue
New-AzureWebSite -Name [mywebapp] -Location North Europe
##[error]Conflict: Website with given name [mywebapp] already exists.
</code>
I ran Azure Powershell to see if I could get some more information, but I can't even seem to query the existing site (according to my Azure management portal the site is still running, and it responds when I navigate to its URL). Running the command:
<code>(Get-AzureWebsite -Name [mywebapp]).Instances.Count
</code>
returns zero instances, despite the fact that the site is running.
Can anyone recommend a way to get more verbose information about my Azure sites, or suggest a way to force the deployment step to overwrite the existing site? This is for development purposes, so I have no need to preserve anything from the existing deployment.
Comment: Can you make sure you are using the correct/right subscription?
Comment: And if you are you should then raise a support call with Microsoft on the Azure portal.
Answer: PowerShell is behaving as if you're in the wrong subscription...  What goes Get-AzureWebSite (no params) return - is you're site in the list?  Can also try:
<code>(Get-AzureWebSite [mywebapp]).Enabled
</code>
I don't think .Instances.Count is always populated (it's not on my sites).
Comment: Thanks! Simple errors are often the easiest to overlook - switching to the correct subscription fixed my issue. Sorry for the very late acknowledgement.


"Column 'Valor' no found." ao buscar saldo em query

Question: Estou construindo um simulador de caixa eletrônico, com as funcionalidades de Depositar, Sacar e Extrato estão funcionais. Porém, não estou conseguindo buscar o saldo.
Tenho o método emitirSaldo() que deve receber o valor calculado pela query. Segue o código:
public Extrato emitirSaldo(Extrato mod) {

    conex.conecta();
    conex.executeSQL

    ("SELECT (SELECT SUM(valor) FROM extrato where Transacao = 'Deposito') "
        + "- (SELECT SUM(valor) FROM extrato where Transacao = 'Saque')");

    try {

        conex.resultset.first();
        mod.setSaldo(conex.resultset.getString("Valor"));

        JOptionPane.showMessageDialog(null, "Saldo recebido.");

    } catch (SQLException ex) {

        JOptionPane.showMessageDialog(null, "Erro ao apresentar o saldo./nErro: " + ex);
    }

    conex.desconecta();

    return mod;

}

Esse método é chamado dentro do botão visualizar:
private void btnVisualizarActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    model = control.emitirSaldo(model);

    lblSaldo.setText(model.getSaldo());

}

Quando executo o programa, esta sendo apresentado o erro:

"java.sql.SQLException: Column 'Valor' no found."

Porém no banco de dados existe a coluna Valor:

Como posso realizar o cálculo do saldo e apresenta-lo no FormSaldo, ao clicar no botão Visualizar?
Answer: Acredito que sua query não vai retornar uma coluna chamada "valor". Substitua a linha:
mod.setSaldo(conex.resultset.getString("Valor"));

por
mod.setSaldo(conex.resultset.getString(1));

pois sua query irá retornar uma coluna com o resultado e essa coluna não tem nome. Esse "1" representa o índice dela.
Comment: Alternativamente é possível dar um *alias* para o resultado: `"SELECT ((SELECT SUM(valor) FROM extrato where Transacao = 'Deposito') - (SELECT SUM(valor) FROM extrato where Transacao = 'Saque')) AS resultado"` e `conex.resultset.getString("resultado");`


Induction powers of a matrix

Question: I'm trying to prove that if $A = AB-BA$, where $A,B$ are squared matrices, then
$$kA^k = A^kB-BA^k$$ for all $k$ in naturals.
I proceed by induction, but I can't arrange the expressions to conclude. Any hint?
Comment: I think you mean "square matrix," not "squared matrix."
Answer: Assume the result for $k$; then
\begin{align*}
(k + 1)A^{k + 1} &= A\left(kA^k + A^k\right) \\
&= A \left(A^k B - B A^k + A^k\right) \\
&= A^{k + 1}B - ABA^k + A^{k + 1}
\end{align*}
Now use the fact that
$$AB = A + BA$$
to deal with the final two terms.

Induction powers of a matrix


Does $o(|x-a|^n)$ approximation by a polynomial imply existence of derivatives?

Question: While reviewing the topic of Taylor expansion, I've noticed that while in all statements about the $n$th order Taylor  polynomial of $f:\mathbb R \to \mathbb R $, it's always assumed that $f\in C^n$, there is no mention of the 'converse'.
So what if all we know about $f$ is that $$f(x)=p(x)+o(|x-a|^n)$$ for some polynomial $p$ of degree $\leq n$.
Is there anything we can say about the existence of $f^{(n)}(a)$?
I assume that no, yet I couldn't think of any counterexamples.
Answer: Let $f(x)=|x-a|^{n+1}\mathbf 1_{\mathbb Q}(x)$. Then even the first derivative exists only at $x=a$ (if $n\ge 1$), so there isn't enough of $f$ to even define $f''$ anywhere.


Proof about sequence and subsequence

Question: I found the next exercise and its respective solution while studying calculus.

Let $(x_n)\in\mathbb{R}$ be a sequence. Suppose that every subsequence $({x_n}_k)$ has a "sub-subsequence" $({{x_n}_k}_j)$ that converges to $0$. Show that $\displaystyle\lim_{n\to \infty} x_n=0$

Proof:

Suppose that $x_n \not\to 0$. Then, there is an $\varepsilon _0>0$ such that, for every $N\in\mathbb{N}$ $$|x_n|\geq\varepsilon_0$$, for some $n\geq N$.

Then, it's possible to construct a subsquence $({x_n}_k)$ such that $|{x_n}_k|\geq\varepsilon_0>0$ for every $k\in\mathbb{N}$.

This subsequence $({x_n}_k)$ cannot have any subsequence that converges to $0$ (contradiction).

My questions are: Why can we affirm that it's possible to construct a subsequence $({x_n}_k)$ such that $|{x_n}_k|\geq\varepsilon_0>0$, for every natural number $k$? And why can we affirm that the subsequence $({x_n}_k)$ cannot have any subsequence that converges to $0$?
Answer: You have $\forall N\in\mathbb{N},\ \exists \ n\ge N\in \mathbb{N}$ s.t $|x_{n}|\ge \epsilon_0$
So for $N=1,\exists \ n_1\ge 1\in \mathbb{N} $ s.t. $|x_{n_1}|\ge \epsilon_0$
For  $N=n_1+1,\exists \ n_2\ge n_1+1>n_1\in \mathbb{N} $ s.t. $|x_{n_2}|\ge \epsilon_0$
Inductively we have $n_1<n_2<...$ and $|x_{n_k}|\ge \epsilon_0$
If $x_{n_k}$ had a subsequence $x_{nkl}\to0$ then for $\epsilon=\epsilon_0$ there would be an element of $x_{kn}$ with length $<\epsilon_0$ contradiction

Proof about sequence and subsequence


How to solve $\sum _{n=0}^{\infty }\:\frac{n^a}{n!}$ for any $a \geq 1$ in general?

Question: While doing a problem I encountered this summation
$$\sum _{n=1}^{\infty }\:\frac{n^2}{n!}=2e.$$
I used
$$\sum _{n=0}^{\infty }\:\frac{n}{n!}=e$$
and
$$\sum _{n=0}^{\infty }\:\frac{(n-1)^2}{n!}=e$$
these summations to obtain its value. Is there any more general way to do the problem, therefore a general solution for $\sum _{n=0}^{\infty }\:\frac{n^a}{n!}$ for any $ a \geq 1$?
Comment: I like this question. For integer $a$ it is quite easy to do it for individual values, I maybe you can get a general formula from this and try to prove that it holds for non integer values as well?
Comment: The pattern that I notice is this: $\sum_{n=0}^\infty n^a/n! = B_a \cdot e$ where $B_a$ is the $a$-th [Bell number](https://en.wikipedia.org/wiki/Bell_number).
Answer: After some playing around, I saw that it is connected to the Bell numbers. That wikipedia article also includes your sum:
$$\frac{1}{e}\sum_{n=0}^\infty \frac{n^a}{n!} = B_a$$
where $B_a$ is the $a$-th Bell number. This equation is called Dobiński's formula. Take a look at its wikipedia page. The proof is not very easy.
Answer: Recall that the definition of the exponential function is given by
\begin{equation}
e^x=\sum_{n=0}^{\infty}\frac{x^n}{n!}.
\end{equation}
The trick now is to note that if we differentiate and multiply by $x$, we get
\begin{equation}
x\frac{\mathrm{d}}{\mathrm{d}x}e^x=\sum_{n=0}^{\infty}\frac{n}{n!}x^n.
\end{equation}
If we do this again, we get
\begin{equation}
x\frac{\mathrm{d}}{\mathrm{d}x}\left(x\frac{\mathrm{d}}{\mathrm{d}x}e^x\right)=\sum_{n=0}^{\infty}\frac{n^2}{n!}x^n.
\end{equation}
In full generality, define $D=x\frac{\mathrm{d}}{\mathrm{d}x}$ to be this differential operation. Then we have
\begin{equation}
\sum_{n=0}^{\infty}\frac{n^a}{n!}=D^a(e^x)\bigg|_{x=1}.
\end{equation}
Since $\frac{\mathrm{d}}{\mathrm{d}x}e^x$, it is easy to show inductively that
\begin{equation}
D^a(e^x)=P_a(x)e^x
\end{equation}
for some polynomial $P_a(x)$, in which case we can write
\begin{equation}
\sum_{n=0}^{\infty}\frac{n^a}{n!}=P_a(1)e.
\end{equation}
Now to actually find the polynomials $P_a(x)$. We can act with $D$ on $P_a(x)e^x$ to obtain
\begin{equation}
P_{a+1}(x)e^x=D\left(P_a(x)e^x\right)=x\frac{\mathrm{d}P_a}{\mathrm{d}x}\,e^x+xP_a(x)e^x,
\end{equation}
and so the polynomial $P_a(x)$ is recursively defined by
\begin{equation}
P_{a+1}(x)=x\left(P_a(x)+\frac{\mathrm{d}P_a}{\mathrm{d}x}\right),
\end{equation}
with $P_0(x)=1$. The first few of these polynomials are given by
\begin{equation}
\begin{split}
P_0(x)&=1,\\
P_1(x)&=x,\\
P_2(x)&=x^2+x,\\
P_3(x)&=x^3+3x+x,\\
P_4(x)&=x^4+6x^3+7x^2+x,\\
P_5(x)&=x^5+10x^4+25x^3+15x^2+x.
\end{split}
\end{equation}
One can inductively show that the polynomials $P_a(x)$ satisfy (this can be left as an exercise)
\begin{equation}
P_{a+1}(x)=x\sum_{k=0}^{a}\binom{a}{k}P_{k}(x),
\end{equation}
so if we define $B_n=P_n(1)$, then we have $B_0=1$ and
\begin{equation}
B_{a+1}=\sum_{k=0}^{a}\binom{a}{k}B_k,
\end{equation}
which is the recursive definition of the so-called Bell numbers. Thus, we have
\begin{equation}
\sum_{n=0}^{\infty}\frac{n^a}{n!}=B_ae.
\end{equation}
Comment: Interesting. I like the first expression $\sum_{n=0}^{\infty} n^a/n! = D^a(e^x)|_{x=1}$ even more then the final expression with the Bell numbers.
Comment: Typo last equation. Should be $B_ae$.


How to access populated array in another sub in VBA, w/o arguments?

Question: I am so confused, and endless googling is so far defying me.
I have a sub that collected unique values in Column C into an array. Now that the array is created, I need to use it in a different sub so I can loop through the values.
I have tried passing it as an argument but then I can't figure out how to run the new sub that has arguments, i.e.:
Sub useArray(ByRef varArr() As String)

how in the world do I run useArray? And useArray should be the main sub, anyways, so I am just confused about how I could then run the main sub and use this array variable that has already been defined/populated.

I tried using my sub that gets the unique values as a function, but it doesn't pass the values in the array back to the main sub. At the end of the function AND in the main sub I have:
MsgBox varArr(1)

In the function, it returns the first value. Back in the sub it returns an error.
An assistance would save my sanity!
Comment: Can you edit the question to include more of your code? It isn't exactly clear what you're asking.
Comment: You could turn your sub into a function
Comment: I've always referred to Pearson's descriptions for arrays: http://www.cpearson.com/excel/passingandreturningarrays.htm
Answer: The preferred method is going to be turning your Sub into a Function:
Function useArray(ByRef varArr() As String) As string()

    varArr(2) = "changed it"
    useArray = varArr

End Function

Which you would call by:
Sub test()

    Dim a(2) As String

    a(0) = "a0"
    a(1) = "a1"
    a(2) = "a2"

    MsgBox useArray(a)(2)

End Sub

Comment: In Excel 2010 this won't compile.
Comment: @ArnovanBoven Strange that you're having issues... [I'm not](https://i.stack.imgur.com/jigax.gif) (No clue what the green screen is about in the last frame though - I think it's the color used to detect unchanged pixels to make the file smaller).
Comment: Says 'Can't assign to array' on `useArray = varArr(2)` in Excel 2010
Comment: That's because it's `useArray = varArr` @ArnovanBoven - `useArray` hasn't been dimensionalized until you assign the array to it
Comment: Hahaha oh my - I see it now. Thanks!! @ArnovanBoven
Answer: Sub Main()
    Call DoSomethingWithArray(PopulateArray)
End Sub

Function PopulateArray() As Variant
    PopulateArray = Array("foo", "bar") ' return some array
End Function

Sub DoSomethingWithArray(ByVal someArray As Variant) ' process array
    Dim i As Integer
    For i = LBound(someArray) To UBound(someArray)
        Debug.Print someArray(i)
    Next i
End Sub


MVC4 unobtrusive validation doesn't wait for remote validation to be completed

Question: My ASP.NET MVC4 application has a remote validation rule defined in model and implemented in a controller method. My form is dynamically added to the page. So, I used the following code to trigger the validation.
$(tabId).on("submit", formId, function (event) {
       event.preventDefault();

       var form = $(this);

       form.removeData("validator");
       $.validator.unobtrusive.parse(form);

       if (form.valid())
       {
           // form submission

           // THIS part executes even though the remote validation returns false
       }

       return false;
 });

It starts remote validation and doesn't wait for the completion and then submits the form. If any other field is non-valid (say, name is a required field), then it stops the submission. However, it doesn't wait for the remote validation.
I found some work around on SO such as link1 and link2. However, these work only if I have jQuery validation rules defined in my page. However, I'm using MVC4 model validation rules. Thus I am not interested to redefine the rules in my view page again.
Any idea to solve?
Comment: Have you tried calling `form.validate()` before `if (form.valid())`?
Comment: Yes, I tried `form.validate()`. It didn't work.
Comment: @NRocking Did you find any solution ? I am exactly looking for its solution.
Answer: You can use the pendingRequest variable on the validator to see if there are any still pending when the form tries to submit
$(tabId).on("submit", formId, function (event) {
       event.preventDefault();
       var form = $('#formid');
       form.removeData("validator");
       $.validator.unobtrusive.parse(form);

       if (form.valid() && form.data('validator').pendingRequest == 0)
       {
           // form submission
       }
       return false;
});

And if you want to show messages to the user while the field is validating, you can use the startrequest and stopRequest functions:
$(function(){
    var validator = $('#formid').data('validator');

    var oldStartRequest = validator.startRequest;
    validator.startRequest = function (element) {
        console.log(element.name + ' has begun validating')
        oldStartRequest.apply(this, arguments);
    };

    var oldStopRequest = validator.stopRequest;
    validator.stopRequest = function (element, valid) {
        console.log(element.name + ' has finished validating');
        console.log(element.name + ' is valid: ' + valid)
        oldStopRequest.apply(this, arguments);
    };
});

Answer: You should call the $.validator.unobtrusive.parse(form) as soon as the form gets added to the page.  Calling it in a submit event is not correct and is most likely your problem.  One of the things Validator and Unobtrusive do is capture those events for you, and due to the way Unobtrusive works, if you want to do specific things on successful submit, you have to sneakily attach yourself to the submitHandler like so:
$('#nameForm').data('validator').settings.submitHandler = function(form){
   alert('successful submit');

   //do AJAX submit here

   return false; //otherwise page will get reloaded
};

I've made a working example for you, but note that due to the way jsfiddle works, it's somewhat hard to do an AJAX call, so I had to add a hidden field called html which if you change the value of between true and false you can see the different behaviours.
http://jsfiddle.net/ryleyb/ZeZAu/1/
Comment: [Helpful discussion](http://stackoverflow.com/questions/4747017/how-to-add-a-submithandler-function-when-using-jquery-unobtrusive-validation) of how to deal with valid/invalid forms that doesn't break the way Validate/Unobtrusive works
Answer: You could attach to the global ajax events and make sure nothing is waiting for a reply when you submit the form. Untested e.g.
var isInAjaxCall = false;
var queuedFuncs = [];
$(function() {
    $(document).bind("ajaxStart", function () {
        isInAjaxCall = true;
     }).bind("ajaxStop", function () {
        isInAjaxCall = false;
        while(queuedFuncs.length > 0){
           queuedFuncs.shift();
        }
    });
});

function SubmitForm() {
    if (isInAjaxCall) {
        queuedFuncs.push('SubmitForm');
        return false;
    }

    var form = $('#form');
    form.removeData("validator");
    $.validator.unobtrusive.parse(form);

    if (form.valid()) {
        // form submission
    }
    return false;
}

Answer: My post here provides the solution, but there must be a better way:
ASP.NET-MVC jQuery unobtrusive remote validation returns false positives


pegar valor de autocomplete jquery para calculo em linha dinamica

Question: necessito pegar o valor retornado do autocomplete para efetuar uma soma em uma lista dinâmica de produtos, sendo que já faz o calculo de valor e quantidade e agora precisei inserir uma nova coluna "MEDIDA" sendo necessario tambem remover as letras e pegar somente a qtd da medida, segui o codigo:

autocomplete

// MEDIDA

var x_medida = [

   "1 UNIDADE",
    "PCT 10",
    "PCT 20",
    "PCT 30",
    "PCT 40",
    "PCT 50"

];

$( ".medida" ).autocomplete({ source: x_medida });

Tabela dinamica

contador++;

var newRow = $("
");
var cols = "";

cols += '' + contador + '	';
cols += '<input type="text" name="produto' + contador + '" class="produto" />	';
cols += '<input type="text" name="medida'  + contador + '" class="medida centro" />	';
cols += '<input type="text" name="qtd'     + contador + '" class="qtd centro" onkeyup="somenteNumeros(this);" />	';
cols += '<input type="text" name="preco'   + contador + '" class="preco centro"  align="center" />	';
cols += ' R$ 0.00 	';
cols += ' Excluir 	';

newRow.append(cols);

$("#products-table").append(newRow);

soma de valores da linha

// FUNCTION ( CALCULA TOTAL DA LINHA )

function calculateRow(row) {

    var preco    = +row.find('input[name^="preco"]').val();
    var qtd      = +row.find('input[name^="qtd"]').val();
    //var medida   = +row.find('input[name^="medida"]').val();

    //2 casas decimais
    var total = (preco * qtd).toFixed(2);

    //substitui ponto por virgula
    total = total.replace(".", ",");

    //a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
    row.find('.total').html("R$ " + (total).replace(/\B(?=(\d{3})+(?!\d))/g, "."));

}

Answer: Pode usar match com o regex abaixo para pegar apenas os números do valor:
var medida   = +row.find('input[name^="medida"]').val().match(/\d+/);

Caso o valor seja: "PCT 10", irá retornar "10". E você pode usar esse valor para incluir nos seus cálculos.
Comment: Perfeito amigo, tentei tanta coisa e foi mais simples que imaginava .... kkkkk obg ae !!!


O(nⁿ) complexity pseuodocode structure using loops or recursion

Question: O(n) time is simply one loop, O(n²) is a loop inside a loop where both loops run at kn times (k is an integer). The pattern continues. However, all finite integers k of O(nᵏ) can be constructed by hand that you can simply nest loops inside another, but what about O(nⁿ) where n is an arbitrary value that approaches infinity?
I was thinking a while loop would work here but how do we set up a break condition. Additionally, I believe O(nⁿ) complexity can be implemented using recursion but how would that look pseudocode-wise?
How do you construct a piece of algorithm that runs in O(nⁿ) using only loops or recursion?
Comment: "How do you construct a piece of algorithm that runs in O(nⁿ) using only loops or recursion?" - why?
Comment: Not necessarily a specific one but I am just curious how that would look like. A recursion tree could have that time complexity right? Run the recursive function for every element in the array for example? I could be wrong.
Answer: A very simple iterative solution would be to calculate nn and then count up to it:
total = 1
for i in range(n):
    total *= n

for i in range(total):
    # Do something that does O(1) work

This could also be written recursively:
def calc_nn(n, k):
    if k == 0:
        return 1
    return n * calc_nn(n, k - 1)

def count_to(k):
    if k != 0:
        count_to(k - 1)

def recursive_version(n):
    count_to(calc_nn(n, n))


Comparação mesmo periodo do mês passado SQL

Question: Preciso fazer uma query que traga a quantidade de ordens do mesmo período do mês anterior. Porém, a comparação é o seguinte: se hoje é dia 3 de abril, preciso trazer dia 1, 2 e 3 de março.
Se hoje é dia 10 de abril, preciso trazer o os primeiros 10 dias de março também e assim sucessivamente.
select count(distinct idt_ordens), dat_creation
from tabela
where dat_creation  >= date_trunc('day', current_date) - interval '1' month
group by dat_creation

Comment: Informe o SGBD (banco) pois a solução pode depender deste , em tese eu faria duas tabelas virtuais (até views) com "running totals" e depois comparando via lead / lag , usando analytic (window) functions . Mas publique a estrutura da tabelas e um exemplo de como precisa da saída , se possível um exemplo no sql fiddle.
Answer: Considerando a sintaxe de uso do interval e a função date_trunc, usadas na sql apresentada:
select count(distinct idt_ordens), dat_creation
from tabela
where dat_creation  >= date_trunc('day', current_date) - interval '1' month
group by dat_creation

Cabe uma resposta para usuários do PostgreSQL, que também atende ao autor da pergunta, mesmo não tendo sido informado o SBGD (sistema gerenciador de banco de dados).
O trecho date_trunc('day', current_date) - interval '1' month consegue definir adequadamente o equivalente ao mesmo dia no mês anterior, ao truncar tudo que vier depois do dia e subtrair um mês da data após truncar, não importando se o mês tem 28 ou 31 dias.
Fica faltando definir o primeiro dia do mês anterior, para validar o período que se deseja, usando (date_trunc('month', current_date) - interval '1' month), que trunca tudo que vier depois do mês e joga para o dia 1 e subtrai um mês após truncar.
Após definir as condições de selecionar as informações, só usar na consulta:
select count(distinct idt_ordens), dat_creation
from tabela
-- maior ou igual ao primeiro dia do mês anterior
where dat_creation >= (date_trunc('month', current_date) - interval '1' month)
    -- menor ou igual ao dia equivalente do mês anterior
    and dat_creation <= (date_trunc('day', current_date) - interval '1' month)
group by dat_creation

Particularmente prefiro a sintaxe utilizando between para intervalos.
select count(distinct idt_ordens), dat_creation
from tabela
where dat_creation between (date_trunc('month', current_date) - interval '1' month)
    and (date_trunc('day', current_date) - interval '1' month)
group by dat_creation

Veja a definição das datas funcionando: dbfiddle;
Comment: Funcionou!!! Muito obrigado!
Comment: Ainda bem que ajudou, qual o banco de dados que você está usando?
Comment: Banco de dados postgres amigo


Do melody notes over chords basically change the underlying harmony and the chord extension?

Question: Lets say you have a bunch of chords you play a melody over.
If the melody notes are a part of the underlying chord it sounds more consonant.
But if the melody notes over the chord, are not a part of the chord, they essentially change the harmony (add extensions).
Lets say we have a G minor chord, and the melody note A occurs, it basicly changes the chord to Gmadd9, even if it's for a brief second.
Is this a valid way of viewing things? Or am I over analysing?
Answer: They're often passing notes, and as such, don't really change the basic underlying harmony. If that was the case, a bar may contain not just a simple chord, but several chords with extensions, or even different chords. Yes, it could be portrayed that way, but what are the benefits? By just playing the extensions, those 'new chords' are being recognised, but are usually so ephemeral that it's not worth mentioning in the chord written in that bar. An Am9 chord still is basically an Am chord, but then is it Am add9 or Am7 with a 9th extension?
Look at 'Laura'. Most of the chords are just triads, but the tune is around the 9th of the chord a lot of the time. The chords don't reflect this.
An interesting idea, but unwieldy in operation. It's a valid way to look at things, but important academically rather than practically.
Comment: They are not *always* passing notes - a passing note needs to go somewhere. I've seen songs where a particular melody figure is repeated (without change) over a sequence of chords. On some chords the melody 'fits' and on others it doesn't - e.g. a repeated E melody over the sequence C, G/B, Am. It seems common in songs where the melody and chords are only loosely coupled.
Comment: @Ian Goldby - your example of the repeated E would be classified as a pedal point and therefore often classified as a non-chord tone in the underlying harmony (analysis).
Comment: The OP may be thinking in terms of homophonic harmony.  The exact replication of the rhythm often leads one to this conclusion, each note defines a new chord.  But this is false, or at lease unnecessary as you have pointed out.
Comment: @Dekkadeci My example was intentionally simplistic. Another example would be the three notes E, D, C repeated over each chord. I honestly don't know if this changes the analysis or if that is still classified as a pedal point. (Does a pedal point have to be a single pitch?)
Comment: @Dekkadeci - would a repeated note in the *melody*, on top, be classed as a pedal point?
Comment: @Tim - Yes, it would. I've seen that referred to as an inverted pedal point.


Calculating the flux of the curl

Question:
Consider the sphere with radius $\sqrt{2}$ and centre the origin.  Let $S'$ be the portion of the sphere that is above the curve $C$
(lies in the region $z \geq 1$) and has $C$ as a boundary. Evaluate the flux of $\nabla \times F$ through $S_0$. Specify which orientation you are using for $S'$.
$$F = (z-y,0,y)$$
(curve $x^2+y^2=1$ lying in the plane $z=1$).

So my thoughts are can we use the Divergence Theorem? If so when we use the $\text{curl} = \langle 1,1,1\rangle$?
Then when we apply the Divergence Theorem we can just say that the flux of this would be $0$? Or is this incorrect?
Comment: Please apply Stokes theorem
Comment: What is S0? You can use stoke's theorem. Or if you want to use divergence thorem then you meed another surface so that the whole surface is closed.
Comment: @Math Lover Stokes Theorem, as a piecewise was what I was thinking — one with the curve C and then the top of the surface - could you help parametrise the top surface
Comment: OK I am adding some details
Comment: @MathLover Thank you, much appreciated
Comment: Please do  not delete a question just after getting an answer.  This is disrespectful to the person who provided that answer, and disrespectful to future readers who might benefit from that answer.
Comment: @MathLover sorry about that - the response was appreciated sorry about the deletion of the question
Comment: ok @George, no problem
Answer: Method1:
Parametrize the surface as $(\sqrt2 \cos\theta \sin \phi, \sqrt2 \sin\theta \sin \phi,\sqrt2 \cos \phi)$
Outward unit normal vector $\hat{n} = (\cos\theta \sin \phi, \sin\theta \sin \phi,\cos \phi)$
At $z = 1, \phi = \frac{\pi}{4}$
So use $0 \leq \phi \leq \frac{\pi}{4}, 0 \leq \theta \leq 2\pi$ to set up your double integral.
$\displaystyle \iint_R (\nabla \times \vec{F}) \cdot \hat{n} \ (\sqrt2)^2 \ d\phi \ d\theta$
Or Method 2
Take boundary C which is a circle of radius $1$ and parametrize as $r(t) = (\cos t, \sin t, 1), 0 \leq t \leq 2\pi$.
$\displaystyle \int_C \vec{F} \cdot r'(t) \ dt$
Please make sure the orientation matches up for both integral.

Calculating the flux of the curl


CakePHP 3 belongsToMany Validation

Question: I am struggling with how to do validation with belongsToMany relationships.  Namely, the classic recipes/ingredients relationship.  I would like a recipe to always have an ingredient on create or edit.  What would my validation look like in my RecipesTable?  I have tried:
$validator->requirePresence('ingredients')->notEmpty('ingredients')

As well as
$validator->requirePresence('ingredients._ids')->notEmpty('ingredients._ids')

The second one works in that my form doesn't validate, but it does not add the error class to the input.  I am setting up the input with a field name of ingredients._ids.
I am also having trouble with creating the data to pass to $this->post in my tests in order to successfully add a record in my test.  My data in my test looks like:
$data = [
    'ingredients' => [
        '_ids' => [
             '2'
        ]
    ];

And of course I'm doing the post in my test with $this->post('/recipes/add', $data);
I'm not passing the required rules for ingredients in my test.
Comment: What exactly does "_I'm not passing the required rules ..._" mean? Are there any validation errors? If so, are they related to your former validation problem, or this a different problem?
Comment: I probably should have divided this up into two questions. Are you able to verify how the validation rules should be set up in the Table Object to require ingredients on create or update of a recipe record?  If I can solve that, my tests might naturally fall into place.
Comment: You've already found the answer, that is indeed how it had to be done. I wanted to wait with answer until I knew whether this would get merged: **https://github.com/cakephp/cakephp/pull/5947** It finally did, and when following the naming conventions (`ingredients._ids` for the fieldname, `ingredients` for the entity property name), your input field should now be able to pick up the error automatically.
Comment: Thank you for the reference to the pull request, I'm glad it got merged. Will this also take care of adding the error class to the element in addition to displaying the validation message?
Comment: Yes it does, it should work exactly as it does with all other fields, the wrapper gets the `error` class, and the message element is being appended in the wrapper.
Answer: I solved how to set up the validators.  In the recipe Table validator:
$validator->add('ingredients', 'custom', [
    'rule' => function($value, $context) {
        return (!empty($value['_ids']) && is_array($value['_ids']));
    },
    'message' => 'Please choose at least one ingredient'
]);

However, the validation message was not being displayed on the form, so I'm doing a isFieldError check:
        <?php if ($this->Form->isFieldError('ingredients')): ?>
            <?php echo $this->Form->error('ingredients'); ?>
        <?php endif; ?>

I'm using multiple checkboxes in my view file versus a multi-select.
And with that, I'm getting my validation message on the form.
As I thought, my tests fell into place once I figured out the validator.  What I show above is indeed correct for passing data in the test.
Comment: Using Cake3/4 afterMarshal event you can actually solve the form display error by using e.g. `if ($entity->getError('ingredients') && !$entity->getError('ingredients._ids')) {
            $entity->setError('ingredients._ids', $entity->getError('ingredients'));
        }`
Answer: I will have desired to add this answer as a comment of Kris answer but I do not have enough reputation.
Alternatively, to solve the issue with validation message not being displayed on the form, you can add these two line in your controller.
if(empty($this->request->data['ingredients']['_ids']))
    $yourentity->errors('ingredients', 'Please choose at least one ingredient');

CakePHP 3 belongsToMany Validation


Regression error term using Stata

Question: When using Stata for multiple regression, where do I find the error term?
For the regression equation:
y = constant + B1*X1 + B2*X2 + ... + Bk*Xk + E
Where is E in the output from Stata?
Answer: Unlike the coefficients and like the covariates, each observation has its own residual, so it would be hard for Stata to show you all of them in the output.
However, you can get Stata to predict them for you like this:
<code>. sysuse auto, clear
(1978 Automobile Data)

. reg price mpg weight i.foreign

      Source |       SS           df       MS      Number of obs   =        74
-------------+----------------------------------   F(3, 70)        =     23.29
       Model |   317252881         3   105750960   Prob > F        =    0.0000
    Residual |   317812515        70  4540178.78   R-squared       =    0.4996
-------------+----------------------------------   Adj R-squared   =    0.4781
       Total |   635065396        73  8699525.97   Root MSE        =    2130.8

------------------------------------------------------------------------------
       price |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         mpg |    21.8536   74.22114     0.29   0.769    -126.1758     169.883
      weight |   3.464706    .630749     5.49   0.000     2.206717    4.722695
             |
     foreign |
    Foreign  |    3673.06   683.9783     5.37   0.000     2308.909    5037.212
       _cons |  -5853.696   3376.987    -1.73   0.087    -12588.88    881.4934
------------------------------------------------------------------------------

. predict ehat, residuals

. predict yhat, xb

. list price mpg weight foreign yhat ehat in 1/5, clean noobs

    price   mpg   weight    foreign       yhat        ehat
    4,099    22    2,930   Domestic   4778.672   -679.6717
    4,749    17    3,350   Domestic    6124.58    -1375.58
    3,799    22    2,640   Domestic   3773.907    25.09298
    4,816    20    3,250   Domestic    5843.67    -1027.67
    7,827    15    4,080   Domestic   8610.108   -783.1082
</code>
Comment: In addition, the output does include some summary information on the residuals: The standard deviation of the residuals is displayed as `Root MSE` in the upper right hand block. (The mean is by construction 0, so there is no need to report that)

Regression error term using Stata


Get random friends from mysql

Question: There where 2 mysql tables users(id,name,city) and friend_list(id,userid,friend,status).
Now i need to get three random friends from the friend_list table and their name from users table.
Friend_list table
id |  userid  |friend |status
1  |    1     |   2   | friends
2  |    3     |   1   | friends
3  |    2     |   3   | friends

users table:
id  |  name
1   | xxx
2   | yyy
3   | zzz

I need query something like this.
SELECT f.*,u.name FROM friend_list f,users u WHERE (f.userid = 1 or f.friend = 1) AND f.status = 'friends' AND f.userid = u.id AND f.order by RAND() limit 3

but for eg: it should select 1 in userid column and also from friend column.
I m trying to achieve it without using JOIN's
Comment: Have you tried using rand() function and join ??
Comment: @rockieB :I used SELECT f.*,u.name FROM friend_list f,users u WHERE (f.userid = 1 or f.friend = 1) AND f.status = 'friends' AND f.userid  = u.id  AND f.order by RAND() limit 3 ` but the problem is that selecting the name from users table. How to match selected row to id column of users table(f.userid  = u.id) and (f.friend = u.id)?
Answer: You can use the oreder by rand() as in below  query.
select Friend_list.friend,users.name from Friend_list inner join users on Friend_list.userid=users.id order by rand();

Answer: To select 2 random entries try:
SELECT * FROM
(
 SELECT * from users join on Friend_list.userid = users.id where users.id = ?
) as sub_equity
ORDER BY RAND() LIMIT 2

I had a same task on a project :-)
Answer: SELECT Friend_list.*, users.name
FROM Friend_list INNER JOIN users ON Friend_list.userid = users.id
ORDER BY RAND()  // this will show random records

Answer: You can use ORDER BY RAND() LIMIT 3;
Answer: Try doing this:
SELECT u.name as person, u2.name as friend_with
FROM users u
INNER JOIN friends_list f ON u.id = f.userid
INNER JOIN users u2 ON u2.id = f.friend
WHERE f.userid = 1 or f.friend = 1
AND f.status = 'friends'
ORDER BY rand() LIMIT 3;

SQLFIDDLE DEMO
This will get you three random records with the name of the person and the name of his friend, being one of the userid 1
Comment: I need the result without using join's... See my edit(Added the query close to the result)...
Comment: You have implicit joins in your query. i just used them explicitly. I changed it to add the validation of the userid 1. see if it is what you want
Comment: Will it affect the query processing time if there where more records on table ie. more than 100k or 1000k records...
Comment: Random is not very quick, but it's probably best for you to test it against your data to see if you can use this or if you would have to do attempt a different approach.
Answer: Try this:
SELECT * FROM friend_list f
INNER JOIN users u ON u.id = f.userid
ORDER BY rand() LIMIT 1;

SQL FIDDLE: http://sqlfiddle.com/#!2/e483c/1/0
Answer: ORDER BY RAND() is quite slow if there are many rows.
If users.id is sequential and you have statistic on users.id (e.g. MAX(users.id), MIN(users.id)), generate three random number between min, max in client side.
And following query:
SELECT u.name as person, u2.name as friend_with
FROM users u
INNER JOIN friends_list f ON u.id = f.userid
WHERE users.id IN (random_number1, 2, 3);

this query can use INDEX, so it's faster than ORDER BY RAND()
ah.. users.id would not be continuous (e.g user deleted), so you need to generate enough random number.

Get random friends from mysql


Reinforcement Learning (self navigation) : Stopping back and forth oscillation

Question: I am using deep q learning (output layer activation function is tanh) for a reinforcement learning agent to navigate in a grid. What it learns is not to hit the walls and other obstacles. If it hits something it get -0.9 reward and 0 otherwise. After sometime the agent begins to go one or two steps forward and then backwards and again forward and so on.
To break out from this oscillation I can use exploration (10% or 1% or something). But if i do that it remedy the oscillation problem but it affect the actual functionality since now the agent will take a random action once every ten times and thus will hit something even though the system has learned not to.
Usually how do people address such an issue ? Thank you
Answer: In your question you explain the following rewards:

-0.9 for hitting a wall or obstacle
0 otherwise

Your agent's behaviour is:

to go one or two steps forward and then backwards and again forward and so on

With the information you have given, this appears to be successful. The agent has learned to optimally solve the problem you have set it, as defined by the rewards.
It is not completely clear what the rest of the environment is like, what the agent "observes", and what behaviour you would like to train the agent to achieve. However, you should start by looking at the reward structure. Reinforcement learning is all about the agent accumulating the highest total reward.
A couple of suggestions:

If you want the agent to navigate to a specific position quickly, then make the problem episodic - ending when it reaches the goal - and add a small negative reward for each step (maybe -0.1). Maybe time limit the episode and grant an end reward for how close the agent is to the goal.
If you want the agent to explore the space, the you need to have a reward signal for what counts as exploration. For example, grant +0.1 reward if the agent moves to a position it has not been in before. If this is not an episodic problem, maybe let the rewards from visited squares grow back up over time to some maximum.

Unrelated to reward, if you want to simulate a more complex motion, such as control in driving, you may need to switch away from a grid world where the agent has free choice of movement and absolute control, and use a simplified physics, giving the agent imperfect control over steering. This takes a lot more effort to set up the environment, but can result in more complex behaviours.
Comment: @EshanM.Herath: One thing I missed - you probably need to lose the $\text{tanh}$ activation function in the output layer. With some exceptions, when you are calculating Q (the action value) you need your estimator to be able to predict higher and lower returns, whilst $\text{tanh}$ is limited to $[-1,1]$
Comment: @EshanM.Herath: Yes linear activation function and MSE loss are good general choices, although you could also scale the maximum possible returns (*not* rewards) so everything fits into $[-1,1]$. You don't have to define floors/ceilings as far as I know, but NNs in RL can be unstable, so it might be something that will help.
Comment: Thank you. And does that mean I should use a linear activation function at the output layer. If so do i have to define a ceiling and a floor for the output values.


Botão só funcionar se passar o Id na URL no asp.net MVC

Question: Estou com um problema na minha aplicação gerenciador de Cursos em asp.net MVC.
O cenário é o seguinte: Tenho uma tela onde o "Aluno" faz sua inscrição em um curso. Ao clicar no botão "inscrição", ele é associado a um curso e quantidade de vagas deste curso será decrementada. O Razor da tela é mais ou menos assim:
@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.Nome_Curso)

            @Html.DisplayFor(modelItem => item.Sigla)

        ...

                        <input type="submit" value="Inscrição" name="inscricao" class="inscricao btn btn-success" data-toggle ="modal", data-target="#modalaviso" data-inscricaoid="@item.CursoId" />

}

Neste caso, só funciona se eu passar o Id como parâmetro na URL. Exemplo: minha URL de inscrição é Cursos/Inscricao só que assim o botão não faz nada. Agora se eu passar o parâmetro Id ele funciona, assim: Cursos/Inscricao/1.
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

}

Não quero ficar passando o Id na URL. Preciso que quando o "aluno" clicar no botão "inscrição" ele seja associado ao curso e as vagas decrementadas sem passar o Id na URL.
Comment: Relacionado: http://pt.stackoverflow.com/questions/67178/desabilitar-um-bot%C3%A3o-no-asp-net-mvc
Comment: Também relacionado: http://pt.stackoverflow.com/questions/67538/como-fazer-associa%C3%A7%C3%A3o-de-um-id-no-asp-net-mvc/67551#67551
Answer: Basicamente, você está usando uma requisição Ajax cujo método é POST, mas você não está passando dados por POST.
Altere para o seguinte:
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

}

Conforme o exemplo de Action que respondi aqui, serão necessárias algumas alterações:
[HttpPost]
public ActionResult Inscricao(int inscricaoId)
{
    using (var scope = new TransactionScope())
    {

        // Aqui pegaria o aluno logado.
        var aluno = db.Alunos.FirstOrDefault(/* Aqui vai uma condição */);
        if (aluno == null) return View("Inscricao", db.Cursos.ToList());

        var curso = db.Cursos.FirstOrDefault(c => c.Id == inscricaoId);
        if (curso == null) return View("Inscricao", db.Cursos.ToList());

        var alunoCurso = new AlunoCurso {
            Aluno = aluno,
            Curso = curso}
        };

        db.AlunoCursos.Add(alunoCurso);
        db.SaveChanges();

        curso.Qtd_Vagas--;
        db.Entry(curso).State = EntityState.Modified;
        db.SaveChanges();

        scope.Complete();
    }

    return View("Inscricao", db.Cursos.ToList());
}

Comment: Fiz as alterações e agora minha página de Inscrição não renderiza @Cigano!


Java units of measurement libraries other than JSR-275 and Units of Measure API

Question: Are there any Java libraries dealing with units of measurement except for JSR 275 (rejected and abandoned) and Units of Measure API (which doesn't seem to have any production-quality implementations)?
Comment: Did you ever find an answer? JScience seems full featured but with very little activity, seems like there would be a great need for this kind of library so it's surprising.
Comment: @RasmusStorjohann No, I haven't.
Answer: I have written a units library that does not use static typesetting (as in many practical applications I encountered this would have been more cumbersome that I would like such a library to be).
It is designed to handle string based units as well as sharper defined units.
Some of the supported features include:

conversions of values, e.g.:
Units.convert(3, "m", "mm");
Units.convert(3, SiBaseUnit.METER, "mm");

would both return 3000.

simplification of string based units, e.g.:
Units.simplify("kg^3 m^4 s^-6 A^-1");

would return "J^2 T".

finding the names of a unit in a specific context, e.g.:
Units.inContext("lx s", UnitContextMatch.COMPATIBLE, PhysicsContext.PHOTOMETRY)

would return a navigable set containing ("luminous exposure").

supports SI units, binary units, imperial units, US customary units, atomic units, planck units and many more. The user can also easily define own units.

fully supports arbitrary logarithmic units, e.g.
LevelUnit.BEL.inReferenceTo(1, Unit.of("mV")); // automatically determines ref type -> root power
LevelUnit.BEL.inReferenceTo(1, Unit.of("W"), LevelUnitReferenceType.POWER); // specify type explicitly
Unit.of("ln(re 1 nA)") == LevelUnit.NEPER.inReferenceTo(1, Unit.of("nA")); // true

supports SI prefixes, binary prefixes and allows the user to easily implement own prefixes

Can handle unknown units if not relevant, e.g.:
Units.convert(3, "m^2 this_is_not_a_unit", "mm^2 this_is_not_a_unit");

would return 3e6, as the unknown unit this_is_not_a_unit is the same on both sides of the conversion.

for performance critical parts of the code one can obtain the conversion factor (if the conversion is purely multiplicative), e.g.:
Units.factor("kg", "t");

will return 1e-3.

Allows to check for equivalence, e.g.
Units.equivalent(1, "s", "min");

will return false, as 1min is not the same as 1s. On the other hand, checking for convertibility
Units.convertible("s", "min");

will return true.

tightly integrated in the coordinates library (as of Java 16 this library still requires preview-features, but as of Java 17 it will production ready)

The constants are implemented via a Constant interface that supports e.g.:

definition of own constants, e.g.
// (3 ± 0.2) mole
Constant.of(3, 0.2, "mole");

chaining commands, e.g.
// constant with the distance travelled by light in vacuum in (2 ± 0) seconds as value
PhysicsConstant.SPEED_OF_LIGHT_IN_VACUUM.mul(2, 0, SiBaseUnit.SECOND);

// constant of the elementary charge per (electron) mass
PhysicsConstant.ELEMENTARY_CHARGE.div(PhysicsConstant.ELECTRON_MASS);

Constant c = Constant.of(3, 0.2, "mole");
PhysicsConstant.SHIELDING_DIFFERENCE_OF_T_AND_P_IN_HT.mul(c);

(simple) uncertainty propagation

the Constant interface provides default implementations for the Texable interface from the jatex module, such that a constant can easily return proper LaTeX code.

properly documented implementations for most of the physics constants as defined by NIST, as well as some mathematical constants.
Answer: I have created an opensource Unitility for working with physical quantities and units of measurements including easy conversion between them. Example of usage:
// Creating temperature instance of specified units
Temperature temperature = Temperature.ofCelsius(20.5);         // {20.50 °C}

// Getting converted value for calculations
double valueInCelsius = temperature.getInCelsius();            // 20.50 °C
double valueInFahrenheits = temperature.getInFahrenheits();    // 68.90 °F

// Checking property current unit, value, and value in base unit
TemperatureUnits unit = temperature.getUnit();                // CELSIUS
TemperatureUnits baseUnit = unit.getBaseUnit();               // KELVIN

// Changing property unit and converting back to base unit
Temperature tempInFahrenheits = temperature.toUnit(TemperatureUnits.FAHRENHEIT);
Temperature tempInKelvins = temperature.toBaseUnit();

Additionally, logical and basic math operations are supported within quantities of the same type:
// Logic operation example:
Temperature smallerTemp = Temperature.ofCelsius(-20.0);
Temperature greaterTemp = Temperature.ofCelsius(0.0);
smallerTemp.isLowerThan(greaterTemp);
greaterTemp.isGreaterThan(smallerTemp);

// Math operation example:
Temperature sourceTemperature = Temperature.ofCelsius(20);
Temperature temperatureToAdd = Temperature.ofKelvins(293.15);
Temperature actualTemperature = sourceTemperature.add(temperatureToAdd); // {40°C}

Maybe this will be helpful if you are looking for something simple. It supports a selection of most typical physical quantities and its units for SI and IMPERIAL units.
If you need any specific unit or quantity to be added - just let me know.
Edit: 2024.01.16

it now includes modules for Spring and Quarkus support to preconfigure object mappers for easier use in web applications
maven repository: https://mvnrepository.com/artifact/com.synerset/unitility-core
Comment: Nice library! This is much more elegant than JSR-363.
Answer: https://github.com/unitsofmeasurement/uom-se from JSR 363
https://mvnrepository.com/artifact/org.unitsofmeasurement/unit-api/0.6.2-RC1
Hopefully your problem got solved approx. 4 yrs ago!
Comment: Link-only answers are generally [frowned upon](http://meta.stackexchange.com/a/8259/204922) on Stack Overflow. In time it is possible for links to atrophy and become unavailable, meaning that your answer is useless to users in the future. It would be best if you could provide the general details of your answer in your actual post, citing your link as a reference.


What is the word for the panel on a piano that is in front of the keyboard?

Question: Not the part of the piano that typically has the brand name on it, but the piece of wood that is under the keyboard and is in full view of the pianist.
Answer: The keybed is the part of the piano under the keyboard that supports the keyboard and stops the downward movement of the keys.
The key slip is the panel of wood in front of the white keys and keybed.


Login by email instead of username

Question: I can't find if it is possible or not to change the log in system by using the couple (email, password) instead of (username, password).
I think people never remember their usernames when not available as they wanted and so had to add a number at the end of it ...
Answer: Both the Login Toboggan and Email Registration modules allow your users to use their email when logging in.
Comment: Mind you that LoginToboggan has a different (not to say *problematic*) approach of administrator approvals: https://www.drupal.org/node/1069414
Answer: The developer has moved a module that meets your need from the sandbox to the project page:
https://www.drupal.org/project/login_email
The module exists as 7.x-1.x-dev  It works as is...looks like a bit of assistance can turn this into an official release.
Answer: In order to allow both username and email:
first add validator
function YOURMODULE_form_user_login_alter(&$form, &$form_state, $form_id) {
    $form['#validate'][1] = 'YOURMODULE_form_user_login_replace_email_validate';
    $form['#validate'][2] = 'user_login_authenticate_validate';
    $form['#validate'][3] = 'user_login_final_validate';
}

then check if looks like email address (contains @, letters before and after @ and at least 1 '.' after @).
If it is, than replace email by username:
function YOURMODULE_form_user_login_replace_email_validate(&$form, &$form_state) {

    $name = $form_state['values']['name'];
    if (strpos($name, '@')) {
        $mailParts = explode('@', $name);
        if ((int)count($mailParts) === 2) {
            $extParts = explode('.', $mailParts[1]);
            if (count($extParts) > 1) {
                $query = db_select('users', 'u');
                $query->distinct();
                $query->fields('u', ['uid']);
                $query->fields('u', ['name']);
                $query->fields('u', ['mail']);
                $query->condition('u.mail', $name, '=');
                $result = $query->execute()->fetchAllAssoc('name');

                if (!empty($result)) {
                    $name = array_keys($result)[0];
                    $form_state['values']['name'] = $name;
                }
            }
        }
    }
}

I had a specific situation when I had to add email-based authentification to working site with a lot of users leaving the "old" authentification working, and I did it in such a way.
Answer: Here's how to let a user login with their email address in Drupal 7:
/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, $form_state, $form_id) {

  // On the user login form...
  if ($form_id == 'user_login') {

    // OPTIONAL: Change the title on the user name input.
    $form['name']['#title'] = t('E-mail address');

    // OPTIONAL: Clear the descriptions on the user name and pass inputs.
    $form['name']['#description'] = '';
    $form['pass']['#description'] = '';

    // Prepend a custom validation handler.
    array_unshift($form['#validate'], 'MY_MODULE_user_login_form_validate');

  }

}

/**
 * A custom validation handler for the user login form.
 */
function MY_MODULE_user_login_form_validate(&$form, &$form_state) {

  // If they provided a valid email address for the user name...
  $name = $form_state['values']['name'];
  if (valid_email_address($name)) {

    // If an account exists for the email address...
    $account = user_load_by_mail($name);
    if ($account) {

      // Set the account's user name onto the form state.
      form_set_value($form['name'], $account->name, $form_state);

    }

  }

}

Login by email instead of username


What result is $\left | \bigcup_{i \in I}A_i \right | =\sum_{i \in I} |A_i|$?

Question: I'm reading a text that uses the following equality for disjoint sets $(A_i)_{i \in I}$:
$$\left | \bigcup_{i \in I}A_i \right |=\sum_{i \in I} |A_i|$$
This has to do with disjoint unions, but I'd like to understand, how does the equivalence hold?
Comment: I suspect you want absolute value bars (for "cardinality of") around the union on the left.
Comment: Do you mean $$ \left|\bigcup_{i \in I}A_i\right|=\sum_{i \in I} |A_i|?$$
Comment: To prove this, you will need a definition for $\sum_{i \in I} |A_i|$.  So start with writing that down.  Or looking it up.
Comment: Please name the text.
Comment: @RobArthan University lecture notes, non-public. And these don't have definitions for this.
Answer: This is a generalization of the usual rule that $|A|+|B|=|A\cup B|$, granted that $A\cap B=\varnothing$. Of course the additivity would be false if $A\cap B\neq\varnothing$. If $A=B=\{0\}$, then $|A|+|B|=2$ but $|A\cup B|=|A|=1$.
So in general, if you want to guarantee that a union's cardinality is the sum of cardinals, you would like that union to be a disjoint union.
Now, since it is generally the definition of the generalized cardinal summation, I can't quite give you an answer explaining why this is "true" without being circular (it's true because this is how we define it). But we can prove why this definition works in general.
In order to prove that, we need to show that it does not depend on the choice of each $A_i$. Namely, if $\{B_i\mid i\in I\}$ is a family of pairwise disjoint sets such that $|A_i|=|B_i|$, then $\bigcup A_i$ and $\bigcup B_i$ have the same cardinality.
So for each $i\in I$ there is a bijection between $A_i$ and $B_i$, say $f_i\colon A_i\to B_i$. We define a function $f$ whose domain is $\bigcup A_i$ by defining: $$f(a)=f_i(a)\iff a\in A_i$$
We need to show that $f$ is well-defined, and that it is a bijection. I will leave it to you to verify these details, but essentially the key point is that the $A_i$'s are disjoint (for it to be well-defined) and the $B_i$'s are disjoint (for it to remain injective) and surjectivity comes from the assumption that each $f_i$ is surjective.
Let me finish with a note that we had to use the axiom of choice to choose each $f_i$. Without the axiom of choice it is possible for $I=\Bbb N$, and for each $i$, $|A_i|=|B_i|=2$, but $\bigcup A_i$ is countable whereas $\bigcup B_i$ is not countable.


Vuetify autocomplete - Clear auto complete cache-items list / suggestions

Question: How do I clear the cache item list for auto complete ? I am using the cache-items flag. Once The user has the results for the current query and want to try a new list, I need the current items to be cleared.
I have "cache-items" on so the user can see all his selections before submitting.
<v-autocomplete v-if="showautocomplete" v-model="autocomplete_model"
 :items="items" :loading="isLoading" autofocus
:search-input.sync="autocomplete_search" chips clearable hide-selected cache-items>

Answer: I don't know if you still need this but I think I've found an answer here: https://github.com/vuetifyjs/vuetify/issues/11365 from bka9.
You can add a ref on your v-autocomplete and change the cachedItems through the $refs. I'm not sure when you would have to trigger the method but that's all that's missing.
<template>
  <v-autocomplete ref="autocomplete" cache-items ... />
</template>

Comment: Not ideal, but this worked for me. Vuetify's "autocomplete" sure works a lot differently than many other autocompletes I have used over the years. Thank you for sharing this answer!


Jboss EAP 6.2 AvailableCount in connection pool decresing

Question: 1.We have a J2EE application using Servlets & JSPs running on Jboss EAP-6.2, and using SQL server database.
2.Everything was fine on UAT system where users count was 20 but when we moved the same application to production system where users count is more than 80 , we are facing issue in Jboss regarding connection pool count. This count keeps on decreasing and after 8-10 hours, users are not able to login in the system so we need to Flush the connection pool manually by clicking the Flush button available in Datasource section in Profile tab.
3.We have checked there are no connection leakage, as we have closed all the database connection in the Finally{ } section.
4.We have also increased the max-min pool size in STANDALONE.XML file and added some validation tags recommended by RedHat site.Please see attached file.
Question- Is there any way by which we can automate the Flush button functionality available on Jboss Adminstrator console so that idle connections will get destroyed automatically.
Attached - Jboss console view of connection pool.
enter image description here
enter image description here
Comment: If you measure you InUse counter (which means connections which were requested to the pool but still not returned, normally because the transaction is still in place) and it is always increasing its value it can be a symptom that at any place the connection is not released back to the pool.
Comment: [Here](https://access.redhat.com/solutions/309913) you have a note by RedHat to check for connection leakage, perhaps can help you.
Comment: Hi @alphamikevictor, we have done similar setting like in the link you shared but still nothing is getting printed in Server logs regarding connection leakage. Thanks for you comments and can we make flush button to get clicked automatically without doing manually.
Answer: Ok, if you just want to regularly flush your pool, first create a file (for example commands.cli) with this content:
<code>/subsystem=datasources/data-source=ibpmprod/:flush-idle-connection-in-pool()
/subsystem=datasources/data-source=ibpmprod/:flush-all-connection-in-pool()
</code>
Then everytime you want to perform the flush use the cli:
<code>${JBOSS_INSTALLATION_DIR}/bin/jboss-cli.sh -c --file=commands.cli
</code>
You should check if flush-idle or flush-all fits better in your needs, and of course you can cronify it so it will run at the frequency/times you need.


Modificar variável ao clicar javascript e PHP

Question:

<?php
    for ($i=0;$i<10; $i++){
?>
button onclick='clica()' id='clica' value='<?php echo $i;?>'><?php echo $i;?></button>
<?php
 }
?>

Tenho este código e gostaria que a cada vez que clicar em um botão, exiba o valor numérico dele. Porém só é exibido o primeiro valor, e se eu coloco a função dentro do for, exibe apenas o último. Como devo fazer para conseguir exibir o valor certo?
Comment: você está utilizando o mesmo id para todos os botões, por isso não está funcionando. Se você modificar para `onclick="clica"` sem os parênteses poderá utilizar `var x = this.value;` dentro da função
Answer: Tens de colocar um ID específico para cada button. Então no evento onclick passe this como parâmetro.
Depois na função javascript é só pegar o número pelo valor do elemento.
Exemplo:

function clica(elemento) {
  var x = elemento.value;
  alert(x);
}
<button onclick='clica(this)' id='clica1' value='1'>Botao 1</button>
<button onclick='clica(this)' id='clica2' value='2'>Botao 2</button>
<button onclick='clica(this)' id='clica3' value='3'>Botao 3</button>

O for dos botões pode ser corrigido colocando os IDs com o número:
<?php for ($i=0; $i < 10; $i++){ ?>
  <button onclick='clica(this)' id='clica<?php echo $i;?>' value='<?php echo $i;?>'><?php echo $i;?></button>
<?php } ?>

Answer: Caso não queria colocar um id para cada button, recomendo usar jquery, assim iria facilitar um pouco para pegar o valor de cada botão
<?php for ($i = 0; $i < 10; $i++): ?>
    <button class="botoes" value="<?= $i ?>"><?= $i ?></button>
<?php endfor ?>