Infinite regression and the limits of the density of rational numbers vs irrational numbers.

Question: If we have a space $(0,1)$ we can find two irrational numbers $i_1$ and $j_1$ so that $0 < i_1 < j_1 < 1$.
Then we can find two rational numbers $a_1$ and $b_1$ so that $i_1 < a_1 < b_1 < j_1$.
Then we can find two irrational numbers $i_2$ and $j_2$ so that $a_1 < i_2< j_2 < b_2$.
Then we can find two rational numbers $a_2$ and $b_2$ so that $i_2 < a_2 < b_2 < j_2$.
$\dots$
Then we can find two irrational numbers $i_n$ and $j_n$ so that $a_n < i_n < j_n < b_n$.
As $n \to \infty $ what becomes of the segments $(i_n,j_n)$ and $(a_n ,b_n)$ and the density of rational numbers vs irrational numbers?
Will the vales of $i_n,a_n,b_n,j_n$ approach $i_n = a_n = b_n = j_n = 0.5$
 or do we have to say $i_n \to a_n \to b_n \to j_n \to 0.5$

I will try to flesh out the question with some actual numbers.
Let $i_1 = \frac{1}{10^{1!}} + \frac{1}{10^{2!}} + \frac{1}{10^{3!}} + \dots$
Let $j_1 = 1 - \frac{1}{10^{1!}} + \frac{1}{10^{2!}} +
 \frac{1}{10^{3!}} + \dots$
Let $a_n = \frac{2^n-1}{{2^{n+1}}}$
Let $b_n = \frac{2^n+1}{{2^{n+1}}}$
If $n > 1$ then let $i_n = \frac{2^n-1}{{2^{n+1}}} +
 \frac{1}{10^{(n+1)!}} + \frac{1}{10^{(n+2)!}} + \frac{1}{10^{(n+3)!}}
 + \frac{1}{10^{(n+4)!}} \dots$
If $n > 1$ then let $j_n = \frac{2^n+1}{{2^{n+1}}} -
 \frac{1}{10^{(n+1)!}} + \frac{1}{10^{(n+2)!}} + \frac{1}{10^{(n+3)!}}
 + \frac{1}{10^{(n+4)!}} \dots$
Comment: So your claim is that $\frac12=\frac13=\frac1\pi$? I don't understand how from "$n\to\infty$ you deduce $a_n=b_n$ for some $n$.
Comment: Or in other words, $\frac1n\to 0$ as $n\to\infty$. Could you point out the natural number for which $\frac1n=0$?
Comment: So approaches and equals are not the same. If you answer this question I will give you top answer. https://math.stackexchange.com/questions/2955013/when-can-we-say-that-something-is-equal-to-rather-than-something-approaches-a-l
Comment: @IvanHieno You have to be careful: "the sequence $(x_i)_{i\in\mathbb{N}}$ approaches $x$" **is the same as** "the limit of the sequence $(x_i)_{i\in\mathbb{N}}$ is exactly equal to $x$." The crucial point here is avoiding conflating a *sequence* and a *number*, and it accounts for the confusion going on.
Comment: Incidentally, this title is highly misleading: there's nothing here about Cantor, you're just asking a question about sequences. Even if this is *part of* an attempt to come to grips with Cantor's results, if that's not directly germane to the question it shouldn't be in the title.
Comment: However, since you have mentioned it, I've said a bit about it in my answer.
Answer: Not necessarily. You can pick initial $0 < c < d< 1$, and then choose your $a_n, i_n, j_n, b_n$ so that
$$
a_n < i_n < c < d < j_n < b_n
$$
for all $n$.
Answer: As in your other question, the issue here is a conflation of sequences and objects.
The situation you have here is:

Each sequence approaches ${1\over 2}$: $$\lim_{n\rightarrow\infty}a_n=\lim_{n\rightarrow\infty}b_n=\lim_{n\rightarrow\infty}i_n=\lim_{n\rightarrow\infty}j_n.$$
However, no individual term is exactly ${1\over 2}$.

Incidentally, a closely-related conflation is often the key mistake made in "refutations" of Cantor's diagonal argument: the argument in question claims that the "antidiagonal real" $D$ appears in in the sequence, since arbitrarily good approximations to $D$ appear in the sequence. Here the conflation is between "a number appearing in a given sequence" and "a sequence of approximations to a number being a subsequence of a given sequence."
A lot of the confusion around arguments about infinity comes from "discontinuous behavior at infinity": behavior happens at infinite stages which doesn't occur at any finite stage. Distinguishing carefully between sequences and individual numbers is an important step towards resolving this, since once we fully realize the distinction we can recognize that there's no reason a priori to expect "finitary facts" to yield directly-analogous "infinitary facts."
Comment: Noah said "no individual term is exactly ${1\over 2}$".  That is true, but what is the density of the rationals vs the irrationals when our segments approaches an infinitesimal length? If there exists more irrationals than rationals, then they must exist someplace else.
Comment: @IvanHieno "what is the density of the rationals vs the irrationals when our segments approaches an infinitesimal length? If there exists more irrationals than rationals, then they must exist someplace else." I'm not sure what that means but I think you're trying to claim that at some point we need to get an interval where there are some irrationals with no rationals between them? If so, **that's false**. The basic intuitions one has about how *cardinality* interacts with *geometry* are generally false so even after phrasing your claim precisely you need to prove it - even if it seems obvious.
Comment: Would you be able to explain what you mean when you say "The basic intuitions one has about how cardinality interacts with geometry are generally false". How does it differ, given that Cantor theorized about points in lines, planes and solids etc.
Comment: @IvanHieno Cantor theorized by **actually proving things**; he didn't let his sense of what's "obvious" get in the way (e.g. he was surprised by the fact that $\mathbb{R}^2$ and $\mathbb{R}$ have the same cardinality). Statements like "there can't be more irrationals than rationals, since the rationals "separate out" the irrationals" are perfectly obvious at first glance, but when you sit down to try to prove them rigorously you quickly find that you can't actually seem to build the bijection you want without waving hands and saying things like "clearly" and "obviously."
Comment: @IvanHieno Regardless, the point is: **the onus is on *you* to state precisely and prove your claims**, not on us to decipher and disprove them. This is especially true when pushing back against an established theorem; there's nothing wrong with doing that, indeed it's a good thing to do to understand the results, but you need to be careful to back up your assertions and recognize the burden of proof. (After all, *we have already* rigorously proved Cantor's theorem!)
Comment: I want you to know that I really do value any time that you and others give me. The problem is that I just can't "see" Cantor's conclusion, like I can "see" other ideas like Euclid's Proof of the Infinitude of Primes.
Comment: @IvanHieno That's very fair, and common. I think there are two things to do. First, try to phrase your counterarguments precisely (e.g. what exactly does " If there exists more irrationals than rationals, then they must exist someplace else" mean?). Even before trying to prove them, this is useful: e.g. for me, something that often happens is that I'll run into a kind of "slipperiness" right off the bat, where I suddenly realize I don't know exactly what I want to say. That doesn't mean I'm *wrong*, of course, and sometimes I can fix it after all, but it certainly indicates something worrying.
Comment: The second is to separately look step-by-step at Cantor's argument and convince yourself that each basic step works. This can often be tricky for longer proofs, but here it's not bad since there's only three steps: (1) given a map $f:\mathbb{N}\rightarrow\mathbb{R}$, we define the "antidiagonal" real $D_f$. (2) We show that $D_f$ isn't in the range of $f$. (3) We conclude that no $f:\mathbb{N}\rightarrow\mathbb{R}$ is surjective, and this is exactly what we wanted. Now, **this sort of step-by-step analysis may not be enough on its own** to get an intuitive understanding.
Comment: The other piece of it is to look at different ways to phrase the proof. For example, one important shift is from *contradiction* to *direct proof*, which I've done above: rather than start by assuming that $f$ was surjective and then getting a contradiction, I've started with $f$ arbitrary and (constructively!) produced a real not in its range. The proof by contradiction is fine, but *eliminating* the contradiction generally makes it easier to understand (and I would argue reveals the actual content and is a Good Thing). Another useful tweak is to change the codomain: (cont'd)
Comment: instead of showing that $\mathbb{R}$ is uncountable, show that $\mathcal{P}(\mathbb{N})$ (the set of sets of natural numbers) is uncountable. The reason this is an improvement is because it's easier to define the "antidiagonal set:" given $f:\mathbb{N}\rightarrow\mathcal{P}(\mathbb{N})$, we just let $S_f=\{n: n\not\in f(n)\}$. (Note that this more generally shows that no map from a set to its powerset is ever surjective; see e.g. [here](https://math.stackexchange.com/a/2957155/28111)). Once "$\mathcal{P}(\mathbb{N})$ is uncountable" becomes intuitively clear, (cont'd)
Comment: and *then* focus on understanding that $\mathcal{P}(\mathbb{N})$ and $\mathbb{R}$ have the same cardinality (and hence $\mathbb{R}$ is uncountable). This latter is quite simple, so we've isolated the hard work on understanding the following three steps: (1) Given a function $f:\mathbb{N}\rightarrow\mathcal{P}(\mathbb{N})$, let $S_f=\{n: n\not\in f(n)\}$. (2) We know $S_f$ can't be in the range of $f$: for every $n$, either $n\not\in f(n)$ in which case $n$ is an element of $S_f$ but not $f(n)$, or $n\in f(n)$ in which case $n$ is an element of $f(n)$ but not $S_f$. Either way, $S_f\not=f(n)$.
Comment: Finally, (3) notice that what we've proved is "Any function from $\mathbb{N}$ to $\mathcal{P}(\mathbb{N})$ is non-surjective," and we can rephrase that as "There is no surjection from $\mathbb{N}$ to $\mathcal{P}(\mathbb{N})$" - that is, **$\mathcal{P}(\mathbb{N})$ is uncountable.**


Create contextually filtered view of shared fields across multiple content types

Question: I have a content type "Construction Job" with the title field renamed "Job #". When we create a new job, we assign it a unique job number in the title field.
I have two additional content types, "Update team 1" and "Update team 2". These content types have different fields because the work being done is different, but they share a field called "pictures". Each content type also has an entity reference field to the "Construction Job" content type so we can tie them together.
I'm trying to create a dashboard type display with various different views so management can review jobs with all of the information in one location. I'd like to create a slideshow off all of the pictures uploaded from either of the two update content types, and contextually filter that slideshow so that only the images from the updates for that particular "Construction Job" are shown.
I can create a separate slideshow view for the pictures from each respective Update type, but then I'm left with two separate slideshows on the same page. I'm trying to combine this into one slideshow as we're looking at adding a third different Update content type.
I've tried adding a contextual filter for each entity reference field from the two independent content type, but that doesn't work. That is I can create a contextual filter for the entity reference field for the first content type, but the view then eliminates all images from the second update content type. When I add the second contextual filter, the view returns no results when I enter a value in the filter preview.
Answer: I haven't tried anything exactly like this buts it sounds like it is very possible if you mess with your AND, OR settings. Since they share the same field and that is what you are filtering on there should be no issue with that being your contextual filter.
Look at your regular filters under 'Filter Criteria'. Filter on the content type in an OR group using 'And/Or, Rearrange' (the arrow next to 'Add'). And it should work.
Comment: Both of the content types have unique entity reference fields back to the "construction job". If I try to share this field between the two of them, I get an error when I try to save a new node for "update team 1" or "update team 2". So I created unique entity reference fields for each content type. Even though they are referencing the same entity type, I can't seem to share that between the content types.

If I have 2 groups of filter criteria, separated with and OR, can I apply different contextual filters to those individual groups? I don't see where I can add an OR contextual filter.
Comment: Is there is conditional filter?
Comment: I know there is a way to do that. I imagine you have messed with the contextual filters quite a bit. Maybe try to mess with the relationships. I will take a look at this when I get off work and see if I can't remember how to get this done.
Answer:
That error shouldn't be there so fixing that would be an option.
A likely Solution: Install https://www.drupal.org/project/views_argument_substitutions Add a "Global: Null" contextual filter and Provide default > Content ID. Then add regular OR filters using the replacement * * * ! 1 * * * (no spaces) for the entity reference fields.

Advice: Skip the multiple content types and use the conditional fields module to display different fields depending on a taxonomy field. So a taxonomy vocabulary with the terms Update Team 1, Update Team 2 etc.
If you don't want people to be able to choose, you can have an entity reference to a taxonomy and prepopulate and hide it with the url.
In views then, you filter by that term instead of by content type.
I trimmed like 10 content types down to one doing this. Much much easier to manage.
Comment: I've been considering using the conditional fields and consolidating them into one master "update" type. I already have a taxonomy field to designate which team the authenticated user is reporting on.

I've used the conditional field module in other projects. My concern is that each of these updates has at least 15 fields and are both growing. I'm either going to have to manage two content types, or a bunch of conditional entries for each field I add to the mast type. There is talk of adding a 3rd update type for another team.
Comment: Hmm yea fair enough.. I had a lot of overlap and it was a one off thing so it made sense. Another interesting option could be conditional fields and field collections. You can still manage each Update set of fields separately but with a possibly nice benefit if there were multiple teams per update type.. Each team or person would have their own node which they add to and can take care off while the main views can show the collections as if they were nodes.

Though your solution at the minute could be exactly what you need.
Comment: drupal.org/project/field_group would be good as well if you trust people to choose their Update tab.. Have all of the fields in one content type but group them per Update. Have common fields outside of the field groups and the others inside their tabs.
Answer: Thanks for the help.
I found this module, https://www.drupal.org/project/views_contextual_filters_or which worked perfectly.
I added two relationships, one for each entity reference in the respective Update types. I added two contextual filters filtering on the Content NID -> Provided in URL, each using one of the relationships I created.
With the module installed and activated, there is a check box under Advanced -> Query Settings. This checkbox modifies the query so all conditional filters are OR instead of AND.


Qmail / Zend Mail - RFC 5322 compliant

Question: My company is getting spammed by itself, or rather by it's Qmail, we've got a few automated processes sending out e-mails with Qmail and Zend Mail.
I'm not a expert in either of these, (I know literally nothing about them), and the 'spam e-mails' are Qmail telling us that a series of e-mails being sent isn't RFC 5322 compliant.
Is there a way for me to locate what is generating these error e-mails? Or a place where I can find out what e-mails it's trying to deliver but can't.
This is the mail we recieve
From: email@example.com
[mailto:email@example.com]
Sent: 10. september 2013 15:10
To: email@example.com
Subject: failure notice

Hi. This is the qmail-send program at www.company.com.
I'm afraid I wasn't able to deliver your message to the following addresses.
This is a permanent error; I've given up. Sorry it didn't work out.

<email@example.com>:
188.8.131.52 failed after I sent the message.
Remote host said: 550 5.7.0 (BAY0-MC3-F46) Message could not be delivered.
Please ensure the message is RFC 5322 compliant.

--- Below this line is a copy of the message.

Return-Path: <firstname.lastname@example.com>
Received: (qmail 25746 invoked by uid 0); 10 Sep 2013 15:10:02 +0200
Message-ID: <firstname.lastname@example.com>
To: user <firstname.lastname@example.com>
Subject:
From:
Date: Tue, 10 Sep 2013 15:10:02 +0200
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Comment: It might be helpful to capture one of the messages that get rejected *including all headers* and add it to your question.  Sanitising personal email addresses would be a good idea but even those could be hiding the reason for the rejection so if you can reproduce the rejection with an email address you don't have to sanitise, all the better.
Comment: You shoujld be able to find the answer by looking at the qmail logs.
Comment: There isn't any (as far as I've been cable of finding.) I don't think that it's been enabled in the config file.
Comment: If there are no qmail logs at all, you do indeed have a serious problem, with more than these emails. Apart from that, I second @Ladadadada's request for more information.
Comment: I have updated my question to include the entire e-mail we get back though I have omitted the recievers e-mail, I'm rather clumsy asking these kind of questions.
Answer: Your From: header has no value. This is a pretty blatant violation of RFC 5322. Fix your application so that it provides a valid value for the From: header.
Comment: The issue is, that I don't know WHERE this is being caused, the site is old and quiet frankly impossible to get around in. Is there a way qmailer / Zend place where I can find out what's going on? i.e if I figure out how to turn on Error logging?
Comment: There may or may not be clues in the system logs, depending on how your applications are deployed. You'll just have to go look.

Qmail / Zend Mail - RFC 5322 compliant


Fazer busca em um site

Question: Boa tarde.. Preciso fazer um projeto em java no netbeans que o programa vá no site e busque o que foi digitado no campo de texto do programa. O meu tema é receitas e o site é o cybercook, digitando bolo na tela de busca do meu programa e clicando em buscar, devera abrir uma nova tela do meu programa com uma lista dos bolos que aparecem no site. Ao clicar em um dos bolos, terá que abrir uma nova tela com algumas informações do bolo. Não sei se ficou claro o que preciso fazer, ouvi falar da biblioteca jsoup pra buscar as coisas dentro do site, mas eu nao consegui usa-la para o que eu preciso, e ainda to com problemas nos eventos dos botões e da caixa de texto. se alguem puder me ajudar obrigado.

Pelo que entendi dos comentarios tenho que fazer algo assim... Estou com duvida de como faço para o texto que for digitado no campo de texto ser salvo em alguma variavel algo do tipo, para que eu posso então, coloca-lo na parte do codigo onde esta escrito bolo.
Comment: Bem vindo ao StackOverflow amigo, isto é um pedido de software e não um problema real, portanto se caracteriza como off-topic, pois não é um problema que possa ser reproduzido ao meu ver. O que você já tentou?
Comment: Ola Gabriel, bem vindo ao [pt.so]. A comunidade é voltada a perguntas objetivas sobre programação e a sua está muito ampla. Podemos te ajudar em problemas específicos, mas não podemos fazer tudo por você. Traga suas dúvidas específicas junto com os detalhes do esforço que você já fez para resolvê-las e a comunidade irá te apoiar. Além disso recomendo uma visita a [help] e [ask], e também q faça o [tour]
Comment: Imagens não ajudam em muito Gabriel, tem que postar um exemplo que possa ser reproduzido. LEIA: http://pt.stackoverflow.com/help/mcve e depois edite a sua questão. :) boa sorte
Comment: Eu editei o port para tentar traduzir uma das minhas duvidas
Answer: Da forma que está fazendo você está pegando todos os links (da página toda). Se seu objetivo é obter somente o link das receitas, você precisa inspecionar o código HTML para verificar onde são carregadas essas informações.
No site em questão, as receitas são carregadas em um div com id resultado-busca. Dentro dele, cada receita é inserida dentro de um div com classe bloco-receita.
Ainda assim, há muitos links, então é preciso ser mais restrito.
Pois bem, dentro de cada div com classe bloco-receita, há uma div com nome foto-item e é dentro desse div que está o link que aponta para a página da receita.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class BuscaReceitas {
    public static void main(String[] args) {
        Document pagina;
        try {
            pagina = Jsoup.connect("http://cybercook.com.br/resultado.php?ctr_busca=rapida&tp_busca_a=0&plv=bolo").get();

            Elements links = pagina.getElementById("resultado-busca")
                                   .getElementsByClass("bloco-receita");

            for(Element link : links.select(".foto-item > a")){
                System.out.println("Texto: " + link.attr("title"));
                System.out.println("Link: " + link.attr("href"));
            }
        } catch(Exception e){}
    }
}

Obtive os seguintes resultados nos testes:

... a lista é extensa. :P

Fazer busca em um site


How do I stop a module from installing optional configuration, or make sure it's installed by the time I want to remove it myself?

Question: I don't want the "Frontpage" view to be installed along with my installation profile.
I tried adding a hook_install to a module which does this:
\Drupal::entityTypeManager()->getStorage('view')
  ->load('frontpage')
  ->setStatus(FALSE)
  ->save();

But during installation that tells me that the frontpage view doesn't exist when my module is being installed. Fair enough, so I added the module that owns the frontpage view config (core node) to my dependencies:
dependencies:
  ...
  - drupal:node

Still didn't work. Then I realised it's optional config; maybe the module responsible for processing that config (core views) also needs to be a dependency. It would make sense, so my dependencies became:
dependencies:
  ...
  - drupal:node
  - drupal:views

Still didn't work, same problem - the View simply doesn't exist yet, so it can't be deleted.
So two halves of the same question:

How do I stop this config from ever having been installed in the first place (or installed but initially disabled)?
If that's not possible, what dependencies do I need to provide to ensure that the View in question is installed by the time my own hook_install is executed, so I can remove/disable it myself?
Comment: `But during installation that tells me that the frontpage view doesn't exist` did you try installing your module in a fresh/vanilla Drupal install? I only ask since [your answer worked for Darol](https://drupal.stackexchange.com/questions/187473/how-to-disable-front-page-view-programmatically). So either something changed since '16 or something is going on with your Drupal.
Comment: @NoSssweat I did - the content View isn't optional conf, I wonder if that's the difference
Answer: Hmm, have you tried in the .profile file an hook_install_tasks?
Or maybe with the hook_install_tasks_alter.
/**
 * Implements hook_install_tasks_alter().
 */
function MODULE_install_tasks_alter(array &$tasks, array $install_state) {
  $tasks['install_finished']['function'] = 'CALLBACK_post_install';
}

And deactivate the view in the callback.
Comment: Turns out `hook_install` is the best place to do this, but moving it to the install profile was definitely the way to go. Thanks


How to Select Fields When Refreshing Model in Laravel

Question: As you probably know, we can use refresh method on a model instance in order to refresh it from the database.
Refresh completely reloads all columns from database. refresh method does not seem to take any input, so I was wondering if there is a way to refresh some fields from the database.
To demonstrate, let's have a pseudo-model as below:
Foo
---
bar: char
baz: char

And I have a single instance of Foo called $foo. $foo->refresh() fetches both $foo->bar and $foo->baz. How do I only fetch/refresh bar field?
Thanks in advance.

Environment

PHP 7.4.5
Laravel 7.x
Comment: For which case you need to `refresh()`?
Comment: @MrEduar For [this case](https://github.com/laravel/framework/issues/32939). More specifically, Laravel does not seem to load `storedAs` columns because they are generated in database after they are inserted. Refreshing after MariaDB generates stored column does not kill for a couple of hundred insertions but what if there is more? It would double the queries which would slow down the performance twice as much. Selecting only one column for refreshing/freshing would be more performant.
Answer: I think there's no way to do such. The best option you have is to get the PK of your $foo object and query for the fields you want:
$id = $foo->id;
$refreshed = Foo::select('bar')->where('id', '=', $id)->first();
$foo->bar = $refreshed->bar;

However, this will unsync your model with the database. Another option is to create a custom method in your model that does it in a more abstract way and retrieves the new unsynced object:
// In your model:
public function refreshField(string $field)
{
    $this->$field = (new static())
        ->select($field)
        ->where($this->key(), '=', $this->{$this->key()})
        ->first()->$field;

    return $this;
}

// Then outside:
$foo = Foo::first();
// perform actions. . .
$foo->refreshField('bar');

Again, keep in mind that this will keep your model unsynced with the database. Also, this is a POC, I didn't test it, but the general idea should work. If you create a parent model and extend all your other models from this (which extends from Eloquent), this should work with any of your models.
For a more complete version, you can pass an array instead of a string and retrieve all the fields that you want to refresh, then assign them in a loop:
public function refresFields(string ...$fields)
{
    $fields = $this->$field = (new static())
        ->select($fields)
        ->where($this->key(), '=', $this->{$this->key()})
        ->first();

    foreach ($fields as $field) {
        $this->$field = $field;
    }

    return $this;
}

I wouldn't recommend this, but if you really need it, give it a try. Good luck


Roland Juno ds sound quality for recording

Question: I would like to ask what is the sample rate and bit resolution sound quality supported by the Roland Juno Ds61 keyboard?
Also I would like to know, what would be the difference if I use the midi cable to record audio directly or to record through an audio interface connected to the Juno Ds61?
The user "Your Uncle Bob" said once: "The Roland Juno-DS can send audio to your DAW over USB; this will give you better audio quality than connecting the Juno's audio outputs to an audio interface, because the audio isn't converted to analog and back to digital." Could anybody confirm this information, please?
Finally the only information I found on Roland Corporation Website is this: "The functionality and operation of the Juno-DS61/88 and your computer-based application(s) will be the same no matter which type of connection you are using - the only difference is how the MIDI and Audio signals are routed"
Thanks for the help
Answer: For the bit/sample rate, I am sure this kind of information can be found in the user manual, or maybe by asking Roland directly.
Uncle Bob is totally right saying that, if you can record using the USB of the Juno, meaning that it will, kind of, act as a sound card (it will seen as a sound card by the computer, but is not actually a sound card as no sound is actually produced and converted to digital) and send the digital audio directly to your computer, whereas, with a sound card plugged in the analog outputs, the synth is first converting digital to analog, and the sound card analog to digital again (if you could improve quality doing so, people would know it ;)).
Just one thing:

if I use the midi cable to record audio directly

MIDI cannot carry audio signals. It can carry NoteOn/Off Messages, Control Change messages and a lot more but not audio. It is likely (but I did not check in the manual) that the Juno will be seen by the computer as an audio interface and a MIDI interface.
Comment: Thanks Tom. I understand that MIDI cannot carry audio signals. I was reffering to connecting the JUNO DS to the computer via USB cable (I can record audio and midi data by this way). The bit  rate info it is not in the manual but hopefully Roland send me the information
Comment: @SergioSlzr Point taken, that was a nitpick anyway ;). Did you solve your problem in the end?


R - For loop with dplyr for subsetting data across multiple data frames

Question: I have 50 data frames with temperature and humidity data and I want to create a new data frame, which includes a specific row from each data frame. Firstly I've created a list (onomata_list) in which I imported all 50 data frames, secondly I've created a dummy data frame (All_stations_30_6_17) to "send" the rows from each data frame and finally I wrote the following for loop in order to achieve the abovementioned:
 for(i in 1:length(onomata_list)){
  new_df <- onomata_list[[i]] %>% filter(date == "2017-06-30" & time == "17:00")
  All_Stations_30_6_17 <- rbind(All_stations_30_6_17,new_df)
}

Unfortunately it doesn't work, and I receive the following message:
Error in rbind(All_stations_30_6_17, new_df) :
object 'All_stations_30_6_17' not found
It tried to solve it for the last couple of hours, but I had no luck. Any suggestion ?
Comment: In the code you have posted, you have not created the variable `All_stations_30_6_17` before you use it. It would be helpful if you could post a small reproducible example.
Answer: This should work if you have a list of dataframes:
library(purrr)
library(dplyr)

All_Stations_30_6_17 <- map_dfr(onomata_list, ~ filter(.x, date == "2017-06-30" & time == "17:00"))

Map functions generally iterate through list elements. Here map_drc will map the purrr-style function (denoted with the ~) over the list elements of onomata_list and then row bind (hence the _dfr) into a dataframe output.
Comment: @H.Johnson The [tidyverse](https://www.tidyverse.org/) is a collection of several very useful packages for data manipulation. `purrr` and `dplyr` are two of those packages, but I think you would find it helpful to learn these packages.
Comment: It works perfectly. Thank you very much not only for the solution, but for introducing me this new function!!
Comment: I will definitely do so LMc! Thanks again!!
Comment: hi again! I would like a little clarification regarding your code. It works perfectly if I want to create 1 dataframe from the contents of a list, but If I want to convert each list's element into a new dataframe, but keeping the filter for each and every new dataframe,  can I do it with an alteration of the abovementioned script ? I've been trying it for about 2 hours but I haven't manage to achieve it..
Comment: @H.Johnson then I would just use `map` instead of `map_dfr`, which is what converts the list into a single, stacked dataframe.


TSQL - Insert rows based off range of integers

Question: I am creating a SPROC that will take a number as a parameter. I need to take this number and get 2 numbers before it and 2 numbers after it and then insert those into a temp table. For example - The int is 355. I need to write an insert statemenet that inserts 353, 354, 355, 356 and 357. (-2 & +2). I am not entirely sure how to do this. I was thinking maybe a cursor? In C# I would do a for loop but I am not sure the right way to approach in a set language. Thanks!
Here is what I have so far:
CREATE PROCEDURE [dbo].[GetLanePrediction]
    @startzip int
AS
BEGIN
    --SET NOCOUNT ON;
    DECLARE @posnegval int = 2
    DECLARE @TempZips TABLE (ID INT IDENTITY(1,1), Zip INT)

    --INSERT INTO @TempZips (Zip)
    --Some kind of for loop or cursor here?

END

The output would create a temp table (@TempZips) with 5 rows. Like so:
ID     Zip
1      353
2      354
3      355
4      356
5      357

Comment: Your stored procedure takes two numbers as a parameter which pretty much invalidates your explanation.
Comment: @GordonLinoff whatever the solution is, I will repeat it for both start and end.
Answer: Here is one simple method based on the question:
CREATE PROCEDURE [dbo].[GetLanePrediction] (
    @onenumber int
) AS
BEGIN
    DECLARE @TempZips TABLE (ID INT IDENTITY(1,1), Zip INT)

    INSERT INTO @TempZips (Zip)
        SELECT one_number + v.n
        FROM (VALUES (-2), (-1), (0), (1), (2)) v(n);

END;

EDIT:
You can also use a recursive CTE:
;WITH n as (
      SELECT -@posnegval as n
      UNION ALL
      SELECT n + 1
      FROM n
      WHERE n < @posnegval
     )
INSERT INTO @TempZips (Zip)
    SELECT @onenumber + n.n
    FROM n
    -- WITH OPTION (maxrecursion 0);  -- only needed if you'll ever have more than 100 numbers

Comment: Hm, that could work. But I'd like the variable "@posnegval" to indicate how many integers get added. (To be more dynamic). If it's not possible, I will stick with strictly 2 and just make it work but if not that's still doable.
Answer: Just another option using an ad-hoc tally table
Declare @I int =355
Declare @R int =2

Select ID = N
      ,Zip= -1+@I-@R+N
 From ( Select Top ((@R*2)+1) N=Row_Number() Over (Order By (Select NULL)) From master..spt_values n1 ) A

Returns
ID  Zip
1   353
2   354
3   355
4   356
5   357


Solving a Diffrential Equation by Taking Derivative

Question: Taking a derivative of a differential equation and solving it is one approach to solving a differential equation. However, for some reason I can't get this method to work in cases where there is an interaction term.
Let's consider the differential equation:
$$y'+yx=0$$
Derived with respect to x we have:
$$y''+y'x+x'y = 0$$
$$\rightarrow y'' +y'x+y=0$$
If the differential equation is solved the answer is different for the equations above. Is there something that I am missing when taking the derivative of the equation?
Comment: Both equations have the solution $y=Ae^{-x^2/2}$. The second equation has another linearly independent solution, $y = Be^{-x^2/2}erf(x/\sqrt{2})$ that was introduced in the differentiation.
Comment: Hey. Let me check, if I understand your question correctly. You have the equations $y'+yx = 0$ and $y'' + y'x + y = 0$, and you expect them to have the same solution, because one equation is just the derivative of the other. Is this correct? Can you include in your post what different solutions you get for the two equations and how?
Comment: @HowDoIMath Yes, you have it right. It is possible that the approach is erroneous, but it seemed to work at least for equations with no interaction term. I will post the solutions.
Answer: if the D.E is $y'+xy=0$, the solution is
$$y=c_1e^{\frac{-x^2}{2}}$$
if the D.E is $y''+xy'+y=0$, the solution is
$$y=c_1e^{\frac{-x^2}{2}}+\sqrt{\frac{\pi}{2}}c_2e^{\frac{-x^2}{2}}erfi(\frac{x}{\sqrt{2}})$$
so that $erfi(x)$=imaginary error function
to find the $c_2$
$$y'=-c_1xe^{\frac{-x^2}{2}}-x\sqrt{\frac{\pi}{2}}c_2e^{\frac{-x^2}{2}}erfi(\frac{x}{\sqrt{2}})+\sqrt{\frac{\pi}{2}}c_2e^{\frac{-x^2}{2}}\sqrt{\frac{2}{\pi}}e^{\frac{x^2}{2}}$$
$$y'=-c_1xe^{\frac{-x^2}{2}}-x\sqrt{\frac{\pi}{2}}c_2e^{\frac{-x^2}{2}}erfi(\frac{x}{\sqrt{2}})+c_2$$
substitute it in $y'+xy=0$, to get
$$c_2=0$$
so the solution will stay without any change
Comment: I just want to sum up the answer quickly. The approach taking derivative of differential equation works, but the differentiated equation introduces new terms to the solution (because of losing the constant presumably). The terms can be solved for using the original differential equation, and solving for them gives the same answer as solving the original equation.
Comment: @Dole, yes, exactly as you said


PHP functions return type

Question: I am aware that some built-in php functions have mixed return type, such as strpos().
Is there some sort of a 'Best Practice' on returning values from a custom php function?
Take a look at this
function getSupportedCurrencies() {
    // code here
}

The getSupportedCurrencies() expects an array of currencies to be returned.
But if there is no supported currencies, we can easily return false or null.
But semantically, we should return an empty array().
I understand that PHP variables are loosely typed allowing the program to be flexible.
But what benefits does a loosely typed function provide? Does it just only give
programmers an opportunity to write bad code? Please give an example wherein it is
needed to have mixed return type. Thanks.
Comment: Lovely example of where [return type hinting](https://wiki.php.net/rfc/returntypehint2) would be useful as well
Comment: People can write bad code, strong or loose typing. Make your methods understandable and if you're providing an API, document their usage properly for other developers. It's a matter of opinion though as to good examples of when you need a mixed return type.
Comment: Thanks for the response. I am just worried on having too many return types for a single function. Should it be a concern?
Answer: There is no really way to be typesafe in PHP as you mean, no really security that returned value is of wrong type. You may want to look at some extra tool like HipHop compiler (or to some other language).
Answer: Personally, when working with functions which accept arrays. I'd prefer something like:
function GetCur ($Argument = array()){
        $Errors = 0;
    if (!is_array($Argument)){
        // If is not an array then increment the errors
        $Errors++;
    }
    if (empty($Argument)){
        // If passed array is empty then increment
        $Errors++;
    }
    if ($Errors >0){
        // If errors are higher than 0, then return false
        return false;
    }
    // Do other validations that you need your function to do

}

Then validate as so:
if (GetCur($Array) !== false){
    // function has not returned false, so correct information has been passed
}else{
    // Function has returned false, so incorrect information has been passed. So log/show a error
}

a simple comparison would be to look at the workings for Strpos which specifies:

Warning This function may return Boolean FALSE, but may also return a
  non-Boolean value which evaluates to FALSE. Please read the section on
  Booleans for more information. Use the === operator for testing the
  return value of this function.

Please note, this is an example. There are more efficient ways to handle countless if statements within a function, which would also provide better readability if you are creating an API

PHP functions return type


How to unit test new object creation in interface default method?

Question: There is a default method in the interface that creates new object and uses its functions. So I need to mock it. But I can't figure it out without making another default method which returns new instance. I used to make factories so far that handles object creation and than mock the factory method. But can't do it in interfaces since interfaces can't have instance variables which is factories in this scenario. Any other ideas? I want to be consistent in the project but now I have 2 different approach to avoid object creations in methods. Here is an example:
public interface ISomeInterface
{
    default Integer callMe( )
    {
        Object someObject = new Object( ); // need to mock this
        Integer result = someObject.finish();
        result = result + 1;

        return result;
    }
}

I used to refactor the code with factories when I don't use interface like this;
default Integer callMeNotInterfaceClass( )
{
    Object someObject = new Object( );
    Integer result = instanceFactory.create().finish(); // I can mock create() method
    result = result + 1;

    return result;
}

Only solution I implemented so for wrapper method:
public Integer callMe( )
{
    Object someObject = new Object( );
    Integer result = wrapperMethodCall.finish(); // only solution so far. But now I have 2 different approaches in the project to avoid object creation.
    result = result + 1;

    return result;
}

default Object wrapperMethodCall() {
    return new SomeObject().someMethodsToBeMocked();
}

Comment: 2 approaches might be warranted still. If you don't like having two, pick one.
Comment: If the type of `someObject` has been tested, I don't see why testing would be needed here, as you'd be testing an assignment & addition, which have already been thoroughly tested. Assuming your real case is more complex, you'd typically want to separate how the data is obtained (instantiation) from how the data is used (calls) - not only would you be able to test the logic by injecting a mock, but you'd also gain flexibility of being able to swap implementations in production code (assuming the type isn't final, allowing for future implementations).
Comment: @VinceEmigh my mistake while creating sample example. wrapperMethodCall instantiates new SomeObject(). Yes as I said in the question, that is how I used to, instantation is done by factories and code can be tested easily. But in the interfaces, I can't do that since I can't hold a SomeFactory instance in the interface, I need to create new SomeFactory() in the method again
Comment: @cmlonder You don't need a factory, you need to allow clients to specify where the data is coming from. Even with a factory, you'd still be mixing how the data is obtained (factory) with how the data is used, thus you'd still have to allow the client to specify the factory used. You should separate it by allowing the client to specify which object to use. You could then expose a method which instantiates a default implementation, passing it into the method with all the logic.
Comment: @VinceEmigh I got it. You mean I need one more method in the interface like getObject():IForcedObjectIntefrace, so client implements IForcedObjectIntefrace and provides it to me in the implementation of ISomeInterface:getObject method. And I can use getObject().finish() method. Right?
Comment: You'd have `callMe(Object)`, which you'd test by passing in a mock. Beyond testing, this gives clients flexibility in what implementation will be used. You could then have a `callMe()` which instantiates the default implementation and passes it to `callMe(Object)`, so clients aren't forced to supply their own implementation if they don't have one/want to.
Answer: As usual, unit tests force you to think of the design of your classes.
First, you should notice that you have two main different type of objects.
Some objects are values: they are immutable, can exist in multiple copies, are comparable (and have a hashCode too). This is the kind of objects that are easy to store in a database. If you know a bit of Kotlin, you've heard of the data classes: that's it.
Some other objects that have the semantic of an entity: they are mutable, it doesn't make sense to compare them and often you have only one copy of them. They are the objects that do something.
The objects that have the semantic of an entity are the ones you need to mock in unit tests, whereas you don't need to mock the values. To pass the mocks, these objects have to be injected in the classes, as parameters of the constructor.
In your snippet, you created in a function an object that seems to have the semantic of an entity (a value doesn't finish anything) and that's why you have a problem: you can't unit test because you can't mock this entity.
The solution is simple: either you inject the object in the method:
public interface ISomeInterface
{
    default Integer callMe(Object someObject)
    {
        Integer result = someObject.finish();
        result = result + 1;

        return result;
    }

    ...
}

Or you inject the object in the class:
public interface ISomeInterface
{
    default Integer callMe()
    {
        Integer result = finishObject();
        result = result + 1;

        return result;
    }

    // classes will need an instance of the object to implement this
    Integer finishObject();

    ...
}

In both cases, classes that implements your interface have either the responsibility to provide the object itself when they call the method or to return value of the finish method.
But remember: if you create the object in a method of those classes, unit testing them will become difficult too. Use the factory pattern to create entity objects in a static method and pass thoses object to the constructor.
Unit testing of classes and methods will become easier if you follow this rule of thumbs: when the object has a semantic value, and create it at the higher level (main if possible) and pass it as a parameter of your constructors or methods.


Span of two vectors in $\mathbb{R}^2$

Question: The span of two vectors in $\mathbb{R}^2$ neither of which is zero vector, and which are not parallel, is-

a point.
line in $\mathbb{R}^2$ not running through origin.
line in $\mathbb{R}^2$ running through origin.
all of $\mathbb{R}^2$.

Thanks for helping.
Comment: What do you think and why?
Comment: As they are independent , they can span R2
Comment: Is it 4 ? as they are independent
Comment: 4 what ?  Span means all linear combinations of the vectors
Comment: https://www.math.wisc.edu/~chandara/subspacesofR2.pdf
Answer: The answer is $4)$. To this end, it amounts to showing the following:
the system of equations: $x(a,b)+y(c,d) = (m,n)$ has a solution for any $m,n$. This means:
$ax+cy = m, bx+dy = n$ has at least one solution,and using Cramer's rule, this occurs when $ad - bc \neq 0$ which means the vectors $(a,b), (c,d)$ are non-parallel. Thus we're done.
Answer: Let say the your vectors are- $\begin{bmatrix}\alpha_1 \\ \alpha_2\end{bmatrix} \ \& \ \begin{bmatrix}\beta_1 \\ \beta_2 \end{bmatrix}$.
So,
$$x_1\begin{bmatrix}\alpha_1 \\ \alpha_2\end{bmatrix} \ + x_2\ \begin{bmatrix}\beta_1 \\ \beta_2 \end{bmatrix} = \begin{bmatrix}\gamma_1 \\ \gamma_2\end{bmatrix}, \text{ where } \gamma_1, \ \gamma_2 \in \mathbb{R}.$$
$$\implies \begin{bmatrix}\alpha_1 && \beta_1\\ \alpha_2 && \beta_2\end{bmatrix}   \begin{bmatrix}x_1 \\ x_2 \end{bmatrix} = \begin{bmatrix}\gamma_1 \\ \gamma_2\end{bmatrix}.$$
Say,
$$A=\begin{bmatrix}\alpha_1 && \beta_1\\ \alpha_2 && \beta_2\end{bmatrix}.$$
From the given information in the question, we can say that $A$ is a full rank matrix, so it is invertible.
$$\begin{bmatrix}x_1 \\ x_2 \end{bmatrix} = A^{-1}\begin{bmatrix}\gamma_1 \\ \gamma_2\end{bmatrix}.$$
For any $\gamma_1,\gamma_2$, we can get a unique solution for $x_1,x_2$. So, the vectors span the whole $\mathbb{R}^2$.

Span of two vectors in $\mathbb{R}^2$


Cyclical/Recursive React PropTypes

Question: Not to be confused with a similar question asking how to define PropTypes recursively, I'm looking for a way to pass in an argument that itself is recursive without:

wasting cycles checking stuff that has already been checked and
throwing "Warning: Failed prop type: Maximum call stack size exceeded" messages due to the checker recurring until it dies.

Here's a simplistic example of how this might be used.
const fields = [{
        accessor: 'firstName',
        type: 'text',
        required: true,
        label: 'First Name',
        placeholder: 'Enter your first name'
}];

fields.push({
    accessor: 'children',
    type: 'dynamicList',
    label: 'Children',
    fields: fields
});

return (
    <Form
        fields={fields}
        onSave={data => console.log(data)} />
);

One hacky workaround I can think of immediately is to instead pass some sort of identifier instead that the component uses to look up some referenced prop. Is there another way, without changing React's typechecker to prevent cycles?
Note: For those interested, doing something like above works fine as far as I can tell, save for the log warnings and potentially some slight performance impact.
Answer: One way I came up with to handle prop cycles on recursive PropTypes is an adjustment to the lazy evaluation method, like so:
function lazyFunction(f, _lazyCheckerHasSeen) {
    return function() {
        if (_lazyCheckerHasSeen.indexOf(arguments[0]) != -1) {
            return true;
        }

        _lazyCheckerHasSeen.push(arguments[0]);
        return f().apply(this, arguments);
    }
}

Used like so, for the aforementioned example:
const lazyFieldType = lazyFunction(function () {
    return fieldType;
}, []);

const fieldType = PropTypes.shape({
    accessor: PropTypes.string.isRequired,
    type: PropTypes.oneOf(['text', 'multitext', 'checkbox', 'select', 'multiselect', 'section', 'dynamicList']).isRequired,
    required: PropTypes.boolean,
    label: PropTypes.string,
    placeholder: PropTypes.string,
    fields: PropTypes.arrayOf(lazyFieldType),
});

Form.propTypes = {
    fields: PropTypes.arrayOf(fieldType),
    onSave: PropTypes.func.isRequired
};

Cyclical/Recursive React PropTypes


Prove that $\frac{x^2}{x^2 + y^2}$ is irreducible in $\Bbb{Q}[x,y,\frac{1}{x^2+y^2}]_0$

Question: I was doing Vakil's FOAG, in exercise 5.4 N needs to investigate an important example that $\Bbb{Q}[x,y,\frac{1}{x^2+y^2}]_0$ is not UFD (where we take localization of $\Bbb{Q}[x,y]$ at $x^2+y^2$ and take the degree zero part of it).
Ravi gives an example :
$$(\frac{x^2}{x^2+y^2})(\frac{y^2}{x^2+y^2}) = (\frac{xy}{x^2+y^2})^2$$
However I have some difficulty in showing $\frac{x^2}{x^2+y^2}$ is irreducible, notice that is not irreducible in $\Bbb{Q}[x,y,\frac{1}{x^2+y^2}]$ but the example indicate that it is irreducible in the degree zero part of $\Bbb{Q}[x,y,\frac{1}{x^2+y^2}]$. in this case we may have to prove it by definition?
Comment: $\Bbb{Q}[x,y,\frac1{x^2+y^2}]$ is a UFD, $\frac{x^2}{x^2+y^2}$ doesn't have many factorizations in it, doesn't leave many choices for the possible factorizations in $\Bbb{Q}[x,y,\frac1{x^2+y^2}]_0$
Comment: Ah got it , thank you @reuns , I forget to use UFDness of  $\Bbb{Q}[x,y,\frac1{x^2+y^2}]
$
Answer: We have $p / (x^2 + y^2)^m * q / (x^2 + y^2)^n = x^2 / (x^2 + y^2)$. Rearranging, we get $pq = x^2 (x^2 + y^2)^{m+n-1}$. Assume that neither $p$ nor $q$ are divisible by $x^2+y^2$. Note that as $p / (x^2 + y^2)^m $ has degree 0 and $deg(p) \geq 0$, $m$ cannot be negative, and similarly for $n$.
Now, $\mathbb{Q}[x,y]$ is a UFD and $x^2 + y^2$ is irreducible in it. Since $x^2 + y^2$ does not divide $pq$, it cannot divide the right side either, so $m+n-1 = 0$. WLOG let $m = 1, n = 0$, so $p$ has degree 2 and $q$ has degree 0.
This implies $q$ is invertible.
Comment: perfect solution thank you David Lui


Determining limit of a recursively defined sequence

Question: Reading my calculus notes I found the following exercise:
Let $\displaystyle a_1=\alpha$ and $a_{n+1}=\frac{a_n+ \beta/a_n}{2}$ for $n\geq1$, where $\alpha>0$ is arbitrary and $\beta$ is a positive fixed number. Show that $(a_n)\to\sqrt{\beta}$ when $n\to\infty$
I've been stuck for a while trying to solve this problem. I don't really know how to approach it. I tried using induction since the sequence is defined recursively but I didn't get the desired result. Any help is appreciated.
Comment: Not exactly the same but very similar usecase, look at https://math.stackexchange.com/q/3538354/399263
Comment: When you are trying to find the limit of a sequence, try setting $a_{n+1}=a_n$ and solve for $a_n$. If the limit exists and the sequence is monotonic, $a_{n+1}=a_n$ should occur when $n\to\infty$
Answer: Finding the possible limit is relatively straightforward:  $l=\dfrac{l+\beta/l}2\implies 2l^2=l^2+\beta\implies l=\sqrt\beta$.
To show this is indeed the limit, try showing you have a bounded monotone sequence.


Responsive Mobile Menu - Jquery Toggle

Question: I have created a responsive jquery mobile menu. The problem that I am having is the jquery coding by default hides the menu and only when the image is clicked the navigation expands. This functionality is fine except when being viewed on a desktop. Because it is set up by default to not appear it is not shown.
I was hoping someone could help me to show the navigation on the desktop version and when a width threshold is crossed by default the navigation doesn't appear until it is clicked. This is so when someone visits the website on a mobile device the screen isn't covered with the menu. I was also having problems retracting the menu when the image is pressed again.
I have have uploaded my projected onto jsfiddle. link http://jsfiddle.net/bLbdavqu/
Thanks
Answer: This can be achieved reasonable quickly and easily using Bootstrap.
Example
http://getbootstrap.com/examples/navbar-fixed-top/
Documentation
http://getbootstrap.com/components/#navbar
Code Example (from above link)

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      Brand

Link

Link

          Dropdown

Action

Another action

Something else here

Separated link

One more separated link

      <form class="navbar-form navbar-left" role="search">

          <input type="text" class="form-control" placeholder="Search">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>

Link

          Dropdown

Action

Another action

Something else here

Separated link

JSFiddle (above example)
http://jsfiddle.net/rlgod/7d1szLkh/

Responsive Mobile Menu - Jquery Toggle


Proof of continuity of norm in function space

Question: How would you go about proving that the norm induced by the scalar product
$$ \int_a^b f\cdot g \mathop{dx}$$
in the space $\mathcal{C}([a,b])$ is continuous?
Trying to calculate
$$ \left|\int_a^b |f|^2 \mathop{dx} - \int_a^b |g|^2 \mathop{dx} \right|$$
it is clear that I can find an upper bound for this quantity provided that $f$ and $g$ are "close enough", but what notion of proximity should I use?
The same norm? Wouldn't the reasoning be circular?
Answer: The norm which induces the topology is always continuous (for the usual topology on $\mathbb{R}$) since you can write that
$$x=x-y+y\text{ so }||x||\leq ||x-y||+||y||\text{ and then }||x||-||y||\leq ||x-y||,$$
and also
$$||y||-||x||\leq ||x-y||,$$
which leads to
$$\big|||x||-||y||\big|\leq||x-y||,$$
so the norm is $1$-lipschitz and so continuous.
Comment: @Karl ??? No, the inequality $|f(x)-f(y)|\le f(x-y)$ is not the definition of continuity.  But here that's the same as $|f(x)-f(y)|\le d(x,y)$, which obviously implies $f$ is continuous (let $\delta=\epsilon$).
Comment: If you call the norm $f$ just for fun, what I read here is $|f(x)-f(y)|\lt f(x-y) $ which doesn't feel like the definition of continuity
Comment: Ok. On the first line did you mean for the usual topology on $\mathcal{C}([a,b])$?
Comment: Yes: the norm here is both the function and the way to compute distances in your vector space.
Comment: No, here in this general example I deal with a normed space $(E,||\cdot||)$ and with $(\mathbb{R},|\cdot|)$ (that is, the topology induced by the absolute value - this is what I wanted to precise).


How many squares with vertices on $x^2y^2 =1$ are possible?

Question: We can form a square with vertices on the curve $x^2 y^2 = 1$ and which does not intersect this curve.

Can we get any other square with vertices on $x^2 y^2 = 1$ and which does not intersect this curve? Can anyone please tell me elaborately?
Comment: If the vertices are on the curve, then the square does intersect the curve.
Answer: Yes. Rotating and scaling so as to keep the vertices on the curve, we get a square with vertices at $\pm(a,1/a)$ and $\pm(-1/a,a)$ with $a>0$. We can rotate clockwise until there is an intersection when the slope of the side from $(a,1/a)$ to $(-1/a,a)$ is less than the slope at $(a,1/a)$. This condition on $a$ may be expressed as
$$\frac{1/a-a}{a+1/a}\geq -\frac{1}{a^2},$$
or equivalently,
$$a^4 -2a^2-1\leq 0.$$
There is a similar condition for counterclockwise rotation, but rather than repeat the calculation, we can note that counterclockwise is the same as clockwise rotation followed by exchanging $x$ and $y$ coordinates (in this case $a\mapsto 1/a$). Hence, we also have the condition
$$a^{-4} -2a^{-2}-1\leq 0,$$
or equivalently,
$$a^{4} +2a^{2}-1\geq 0.$$
Solving for these two equations, we get $\sqrt{\sqrt{2}-1}\leq a\leq \sqrt{1+\sqrt{2}}$.
EDIT: We can show that these are the only such squares. Firstly suppose a square could be inscribed in the first quadrant. Let $(x_i,y_i)$ be the coordinates of the vertices with their $x$ coordinate in increasing order. Then the chords from $(x_1,y_1)$ to $(x_2,y_2)$ and from $(x_3,y_3)$ to $(x_4,y_4)$ have the same slope. By the intermediate value theorem, there are two points $c_1,c_2$ with $0<x_1<c_1<x_2<x_3<c_2<x_4$ so that the slope of the curve at those points are the same. Hence,
$$-\frac{1}{c_1^2}=-\frac{1}{c_2^2}$$
or $c_1=c_2$, which is a contradiction. Thus, at least one vertex must lie in another quadrant. The curve in the first quadrant is convex, so if at least two vertices lie in the first quadrant, then all of the vertices must lie in the convex hull of the curve in the first quadrant, as otherwise there would be an intersection with the curve. As such, at most one vertex can lie in the first quadrant, and by symmetry with the other quadrants, we conclude that each vertex must lie in a different quadrant. Now suppose we have a vertex $(a,a^{-1})$ in quadrant I, and a vertex $(b,-b^{-1})$ in quadrant II. Then there is a vertex $(b+a^{-1}+b^{-1},b-b^{-1}-a)$ in quadrant III. Since it lies on the curve in quadrant III, we have
$$(b+a^{-1}+b^{-1})(b-b^{-1}-a)=1$$
However,
$$(b+a^{-1}+b^{-1})(b-b^{-1}-a)=b^2-b^{-2}-ab+a^{-1}b-a^{-1}b^{-1}-ab^{-1}-1$$
Hence,
$$b^2-b^{-2}-ab+a^{-1}b-a^{-1}b^{-1}-ab^{-1}-2=0$$
Multiplying by $-ab^3$, we get
$$-ab^5+ab+a^2b^4-b^4+b^2+a^2b^2+2ab^3=(ab+1)(ab^3+ab-b^4+b^2)=0$$
Letting $c=ab$, we get
$$(c+1)(c(b^2+1)-b^4+b^2)=0$$
Then, either
$$c=-1\quad\text{or}\quad c=\frac{b^4-b^2}{b^2+1}$$
Now, suppose $c$ is the latter. Then if $b\leq-1$, $$a=\frac{b^3-b}{b^2+1}\leq 0,$$ which is a contradiction since $a>0$. However, if $b>-1$, then $$b+a^{-1}+b^{-1}=\frac{b^4+b^2}{b^3-b}> 0$$
which is a contradiction since $b+a^{-1}+b^{-1}<0$. Thus, we conclude that $$c=ab=-1$$
which characterizes squares with a center that coincides with the origin.
Comment: @anonymous No. I edited my post to prove this fact.
Answer: You can get squares with vertices on either branch by joining the points $(a,1/a)$, $(1/a,-a)$, $(-a,-1/a)$ and $(-1/a,a)$ for $a\in(0,1)$ (any other way is related to this via a rigid motion). We require the slope of the line joining $(a,1/a)$ and $(1/a,-a)$ to be less than the slope of the tangent at $(a,1/a)$. You can easily check that the condition is equivalent to
$$
a^4+2a^2-1\ge 0
$$
which is true for $a\in[\sqrt{\sqrt{2}-1},1]=[0.643594...,1]$.
You need the condition on the slopes because otherwise, by convexity of the branch in the first quadrant, the side of the square intersects the branch again.
Comment: Take $a=0.99$. Draw it. What do you see?
Comment: I had make a mistake in the algebra. Actually, there is a range of values of $a$ that produces "good" squares. I edited my answer.
Comment: @Blue No, it is not. If the slope of the side is less negative than the slope of the tangent, the side intersects the first branch twice. Actually, it is clear that if $a$ is very small, it does not work.
Comment: @Arthur The mentioned computation implies that it would actually meet the curve (unless it is wrong for some reason)
Comment: @GReyes: It's okay for the slope of the connecting line to exceed the tangent slope, provided the connecting line crosses the curve "outside" the square. (Indeed, in the trivial case shown in the problem, one connecting line's slope is *infinite*, which certainly exceeds the slopes of the tangents at the vertices.)
Comment: @sani Not connected to your original square, but to one of the squares of the family that I am considering.
Comment: @Arthur you are right about $a=0.99$. I edited my answer (detected a mistake in the algebra)
Comment: @GReyes: I didn't claim that *any* $a$ would work. There's certainly a threshold (which you seem to have found) between values that work and those that don't. That's exactly the threshold between connecting lines crossing the curve "outside" the square vs on its boundary (that is, when the vertices of the square are exactly the respective points of tangency). Cheers!


Sub relatório não aparece quando executa de dentro do sistema

Question: Já pesquise em vários lugares, sites e afins e não acho uma forma do sub relatório aparecer quando se executa o programa. Seguem os códigos, se precisarem de algo mais me avisem.
Principal
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report2" language="groovy" columnCount="2" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="401" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="04e67a5f-9121-468f-a228-62c2dcf438c2">
    <property name="ireport.zoom" value="1.6105100000000014"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="144"/>
    <parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["/"]]></defaultValueExpression>
    </parameter>
    <queryString>
        <![CDATA[select clientes.cli_nome,
    clientes.cli_endereco ||', ' ||clientes.cli_bairro || '. ' || clientes.cli_cidade || '-' || clientes.cli_estado as endereco,
    clientes.cli_cep,
    clientes.cli_telefone,
    clientes.cli_cnpj_cpf,
    clientes.cli_inscricao_est,
    pedidos.ped_id,
    pedidos.ped_pagamento,
    pedidos.ped_pedido,
    to_char(pedidos.ped_vencimento,'dd/mm/yyyy') as vencimento,
    to_char(pedidos.ped_data,'dd/mm/yyyy') as data,
    produtos.pro_nome || ' - ' || to_char(produtos.pro_peso,'09D90') || ' Kg' as produto,
    itens.item_quantidade,
    itens.item_valor,
    to_char(produtos.pro_peso*item_quantidade,'09D90') || 'Kg' as peso_total,
    to_char((itens.item_valor * itens.item_quantidade) ,'R$999G990D99') as total_parcial
    from clientes inner join pedidos on clientes.cli_id = pedidos.fk_cliente
        inner join itens on pedidos.ped_id = itens.fk_pedido
        inner join produtos on itens.fk_produto = produtos.pro_id
        inner join fornecedores on produtos.fk_fornecedor = fornecedores.for_id
    group by clientes.cli_nome,
        clientes.cli_endereco,
        clientes.cli_bairro,
        clientes.cli_cidade,
        clientes.cli_estado,
        clientes.cli_cep,
        clientes.cli_telefone,
        clientes.cli_cnpj_cpf,
        clientes.cli_inscricao_est,
        pedidos.ped_id,
        pedidos.ped_pagamento,
        pedidos.ped_vencimento,
        pedidos.ped_data,
        pedidos.ped_pedido,
        produtos.pro_nome,
        produtos.pro_peso,
        itens.item_quantidade,
        itens.item_valor,
        fornecedores.for_frete
    order by pedidos.ped_id;]]>
    </queryString>
    <field name="cli_nome" class="java.lang.String"/>
    <field name="endereco" class="java.lang.String"/>
    <field name="cli_cep" class="java.lang.String"/>
    <field name="cli_telefone" class="java.lang.String"/>
    <field name="cli_cnpj_cpf" class="java.lang.String"/>
    <field name="cli_inscricao_est" class="java.lang.String"/>
    <field name="ped_id" class="java.lang.Long"/>
    <field name="ped_pagamento" class="java.lang.String"/>
    <field name="ped_pedido" class="java.lang.String"/>
    <field name="vencimento" class="java.lang.String"/>
    <field name="data" class="java.lang.String"/>
    <field name="produto" class="java.lang.String"/>
    <field name="item_quantidade" class="java.lang.Integer"/>
    <field name="item_valor" class="java.lang.String"/>
    <field name="total_parcial" class="java.lang.String"/>
    <group name="pedidos" isStartNewColumn="true" minHeightToStartNewPage="1">
        <groupExpression><![CDATA[$F{ped_id}]]></groupExpression>
        <groupHeader>
            <band height="202">
                <staticText>
                    <reportElement uuid="090b1b2e-691b-4087-814f-a9719710ddf6" x="0" y="0" width="39" height="20"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[Cliente:]]></text>
                </staticText>
                <textField isBlankWhenNull="true">
                    <reportElement uuid="4f1e744d-c261-440b-a1b0-8dcca9f708c2" x="50" y="0" width="319" height="20"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[$F{cli_nome}]]></textFieldExpression>
                </textField>
                <staticText>
                    <reportElement uuid="f67f5f22-57b5-4414-b3e2-d167574933b6" x="0" y="20" width="50" height="20"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[Endereço:]]></text>
                </staticText>
                <textField isBlankWhenNull="true">
                    <reportElement uuid="6b8ec808-2aed-460a-bbce-8a99c5984e51" x="50" y="20" width="319" height="20"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[$F{endereco}]]></textFieldExpression>
                </textField>
                <staticText>
                    <reportElement uuid="9a871df8-d0cb-445b-9d7f-b0da28f87b9c" x="0" y="47" width="28" height="20"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[CEP:]]></text>
                </staticText>
                <textField isBlankWhenNull="true">
                    <reportElement uuid="dd23b706-61da-48b1-a8bd-6ff0ac90522b" x="28" y="47" width="69" height="20"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[$F{cli_cep}]]></textFieldExpression>
                </textField>
                <staticText>
                    <reportElement uuid="706adb91-b10c-4365-86f0-2af1ff661f8b" x="108" y="47" width="50" height="20"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[Telefone:]]></text>
                </staticText>
                <textField isBlankWhenNull="true">
                    <reportElement uuid="6e2d7f15-3dd6-48c1-9b73-2fbff7cea64a" x="158" y="47" width="91" height="20"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[$F{cli_telefone}]]></textFieldExpression>
                </textField>
                <staticText>
                    <reportElement uuid="863febee-4933-403f-9779-15927ff266b5" x="252" y="47" width="83" height="20"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[Tipo de Pedido:]]></text>
                </staticText>
                <textField isBlankWhenNull="true">
                    <reportElement uuid="d0c6c2e4-1680-42f0-9f3f-7e4a7bc5661d" x="335" y="47" width="32" height="20"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[$F{ped_pedido}]]></textFieldExpression>
                </textField>
                <staticText>
                    <reportElement uuid="10582492-b12c-496c-a83f-dafed4726ee9" x="0" y="73" width="60" height="20"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[CPF/CNPJ:]]></text>
                </staticText>
                <textField isBlankWhenNull="true">
                    <reportElement uuid="0341bc77-16fc-41b8-b430-fde280cd8571" x="60" y="73" width="100" height="20"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[$F{cli_cnpj_cpf}]]></textFieldExpression>
                </textField>
                <staticText>
                    <reportElement uuid="51693097-ef8d-458d-bde8-571a0348b64c" x="189" y="73" width="91" height="20"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[Inscrição estadual:]]></text>
                </staticText>
                <textField isBlankWhenNull="true">
                    <reportElement uuid="cc27ca8e-1442-46b4-8c63-79866062da2b" x="280" y="73" width="100" height="20"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[$F{cli_inscricao_est}]]></textFieldExpression>
                </textField>
                <staticText>
                    <reportElement uuid="201d920b-2479-4f30-a232-aa6eb6468bb2" x="0" y="102" width="108" height="20"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[Forma de pagamento:]]></text>
                </staticText>
                <staticText>
                    <reportElement uuid="29e76845-f4f9-4569-976d-021766025320" x="208" y="102" width="72" height="20"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[Vencimento:]]></text>
                </staticText>
                <textField isBlankWhenNull="true">
                    <reportElement uuid="505c3d68-9cf5-4856-851d-a3c0771ea1e4" x="108" y="102" width="100" height="20"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[$F{ped_pagamento}]]></textFieldExpression>
                </textField>
                <staticText>
                    <reportElement uuid="d140d2d6-3990-4b5b-9a69-2972fcdb6451" x="0" y="129" width="28" height="20"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[Data:]]></text>
                </staticText>
                <textField isBlankWhenNull="true">
                    <reportElement uuid="115f95b2-cce5-4bfa-bad9-ebf60dad2b02" x="28" y="129" width="100" height="20"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[$F{data}]]></textFieldExpression>
                </textField>
                <staticText>
                    <reportElement uuid="6b7193d1-55b6-4b48-8104-a0622653a30b" x="167" y="149" width="82" height="20"/>
                    <textElement textAlignment="Center">

                    </textElement>
                    <text><![CDATA[Itens do Pedido]]></text>
                </staticText>
                <staticText>
                    <reportElement uuid="65939aa9-ff63-45d7-a1c9-fe7491e3ee17" x="8" y="175" width="100" height="20"/>
                    <textElement textAlignment="Center" verticalAlignment="Middle">

                    </textElement>
                    <text><![CDATA[Produto]]></text>
                </staticText>
                <staticText>
                    <reportElement uuid="0153d5c1-8a60-444d-91bf-7751190f036d" x="175" y="175" width="55" height="20"/>
                    <textElement textAlignment="Center" verticalAlignment="Middle">

                    </textElement>
                    <text><![CDATA[Qnt]]></text>
                </staticText>
                <staticText>
                    <reportElement uuid="5af9e9c9-815c-43eb-b301-426134a85abc" x="230" y="175" width="73" height="20"/>
                    <textElement textAlignment="Center" verticalAlignment="Middle">

                    </textElement>
                    <text><![CDATA[Valor]]></text>
                </staticText>
                <staticText>
                    <reportElement uuid="69ca5e4e-d2dd-4b09-af34-2a04ae716e16" x="302" y="175" width="78" height="20"/>
                    <textElement textAlignment="Center" verticalAlignment="Middle">

                    </textElement>
                    <text><![CDATA[SubTotal]]></text>
                </staticText>
                <line>
                    <reportElement uuid="dc76c2bd-2f86-4323-91f4-e4eb055d8040" x="6" y="194" width="374" height="1"/>
                </line>
                <textField isBlankWhenNull="true">
                    <reportElement uuid="03fec0f2-b9e6-4b00-bf2b-5afa2ce4478a" x="280" y="102" width="100" height="20"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[$F{vencimento}]]></textFieldExpression>
                </textField>
                <textField>
                    <reportElement uuid="3e73ddee-56e2-4d8d-99d5-0114b198a29d" mode="Opaque" x="369" y="0" width="31" height="20" forecolor="#FFFFFF"/>
                    <textElement/>
                    <textFieldExpression><![CDATA[]]></textFieldExpression>
                </textField>
            </band>
        </groupHeader>
        <groupFooter>
            <band height="43">
                <line>
                    <reportElement uuid="82ff77bf-be41-484a-bbd5-9a16f0ef37ae" x="6" y="0" width="374" height="1"/>
                </line>
                <subreport isUsingCache="true">
                    <reportElement uuid="1d0fa4e3-b6f9-4a00-800c-1d22cad54f4f" x="8" y="0" width="369" height="22"/>
                    <subreportParameter name="idPedido">
                        <subreportParameterExpression><![CDATA[$F{ped_id}]]></subreportParameterExpression>
                    </subreportParameter>
                    <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                    <subreportExpression><![CDATA[getClass().getResource($P{SUBREPORT_DIR} + "pedidoMeiaPagina_TotalPesoValor.jasper")]]></subreportExpression>
                </subreport>
            </band>
        </groupFooter>
    </group>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="30" splitType="Stretch"/>
    </title>
    <pageHeader>
        <band splitType="Stretch"/>
    </pageHeader>
    <columnHeader>
        <band splitType="Stretch"/>
    </columnHeader>
    <detail>
        <band height="20" splitType="Stretch">
            <textField isBlankWhenNull="true">
                <reportElement uuid="3d686442-9407-42dd-82fb-7fb16ebaa426" x="229" y="0" width="73" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{item_valor}]]></textFieldExpression>
            </textField>
            <textField isBlankWhenNull="true">
                <reportElement uuid="87661932-aba9-4646-8c93-b05e20de638a" x="175" y="0" width="54" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{item_quantidade}]]></textFieldExpression>
            </textField>
            <textField isBlankWhenNull="true">
                <reportElement uuid="7b58e5fe-fc77-44b3-b828-95c0f7db8694" x="302" y="0" width="78" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{total_parcial}]]></textFieldExpression>
            </textField>
            <textField isBlankWhenNull="true">
                <reportElement uuid="19c6795a-459a-4893-9e06-618a8a02f708" x="6" y="0" width="161" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{produto}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <columnFooter>
        <band splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="55" splitType="Stretch">
            <staticText>
                <reportElement uuid="967d506c-c05c-4853-9ca4-91933bffcee7" x="208" y="20" width="383" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[ Interessado em nosso serviço? Ligue: (12) 982054378 ou (12) 981669841]]></text>
            </staticText>
            <staticText>
                <reportElement uuid="4c690251-8cbd-4faa-908d-049b069a184f" x="208" y="0" width="383" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Gerado por: Cella - Sistema de Pedidos e Romaneios.]]></text>
            </staticText>
        </band>
    </pageFooter>

        <band height="44" splitType="Stretch"/>

</jasperReport>

Sub relatório

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="pedidoMeiaPagina_TotalPesoValor" language="groovy" pageWidth="360" pageHeight="802" whenNoDataType="NoDataSection" columnWidth="360" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="f86bfb87-c71b-4a9b-8b41-ac35f3a4f0ee">
    <property name="ireport.zoom" value="1.4641000000000006"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <parameter name="idPedido" class="java.lang.Long"/>
    <queryString>
        <![CDATA[select sum(itens.item_quantidade*pro_peso) as peso_total,
    to_char(sum(itens.item_valor * itens.item_quantidade),'R$999G990D99') as valor_total,
    to_char((sum(itens.item_valor * itens.item_quantidade)*fornecedores.for_frete)/100,'R$999G990D99') as frete
    from pedidos inner join itens on itens.fk_pedido = pedidos.ped_id
        inner join produtos on itens.fk_produto = produtos.pro_id
        inner join fornecedores on produtos.fk_fornecedor = fornecedores.for_id
        where pedidos.ped_id = $P{idPedido}
    group by fornecedores.for_frete;]]>
    </queryString>
    <field name="peso_total" class="java.lang.Double"/>
    <field name="valor_total" class="java.lang.String"/>
    <field name="frete" class="java.lang.String"/>
    <detail>
        <band height="45" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="-1" width="63" height="22" uuid="6f37a33a-c214-40c6-9c22-e20a7bdf8655"/>
                <textElement verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Peso Total:]]></text>
            </staticText>
            <textField>
                <reportElement x="63" y="-1" width="129" height="22" uuid="411627a7-389a-41ab-80d3-2bcda481d700"/>
                <textElement verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{peso_total}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="192" y="0" width="57" height="21" uuid="679d42ae-f743-4e55-83c3-02d3037b2d83"/>
                <textElement verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Valor Total:]]></text>
            </staticText>
            <textField>
                <reportElement x="249" y="-1" width="111" height="22" uuid="1b888508-032f-416e-b0a8-cb146b32d98e"/>
                <textElement textAlignment="Right" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{valor_total}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="213" y="25" width="36" height="20" uuid="d1df3978-ef47-4c77-ba0f-558a5e92cdfe"/>
                <textElement verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Frete:]]></text>
            </staticText>
            <textField>
                <reportElement x="249" y="25" width="111" height="20" uuid="22ab8b1f-ada2-426c-bcad-15d0ce86e4c2"/>
                <textElement textAlignment="Right" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{frete}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

Java
public void gerarPedido(String query, int tipo, String nome) throws JRException, SQLException, IOException {

    xml += "\\pedidoMeiaPagina.jrxml";
    JasperDesign desenho = JRXmlLoader.load(xml);
    JasperReport relatorio = JasperCompileManager.compileReport(desenho);

    PreparedStatement pstmt = this.conexao.prepareStatement(query);
    ResultSet rs = pstmt.executeQuery();

    JRResultSetDataSource jrRS = new JRResultSetDataSource(rs);

    Map parametros = new HashMap();

    JasperPrint impressao = JasperFillManager.fillReport(relatorio,parametros, jrRS);

    if (tipo == 1) {
        JasperPrintManager.printPage(impressao, 0, true);
    } else if (tipo == 0) {
        caminho += nome;
        JasperExportManager.exportReportToPdfFile(impressao, caminho);

    } else if (tipo == 2) {
        JasperViewer.viewReport(impressao, false);
    }
}

Comment: informe como estão os arquivos. Se os relatórios estão dentro do jar ou se estão fora porém no mesmo diretório...
e se puder explicar porque está sempre compilando o jrxml em vez de utilizar o relatório já compilado...
Comment: Os arquivos jasper estão em Meus Documentos numa pasta de arquivos do sistema, como por exemplo os próprios jasper em uma pasta modelo e suas saídas em pdfs. Sobre estar sempre usando o jrxml não saberei lhe dizer, eu peguei este código pronto de um amigo meu e estava encarregado apenas de fazer o relatório e o subrelatório. Abraços
Answer: tente trocar:
getClass().getResource($P{SUBREPORT_DIR} + "pedidoMeiaPagina_TotalPesoValor.jasper")

por apenas:
"pedidoMeiaPagina_TotalPesoValor.jasper"

e certifique-se que o sub relatório já esteja compilado, e que está dentro do jar ou no mesmo diretório

Ou então troque para:
$P{SUBREPORT_DIR} + "pedidoMeiaPagina_TotalPesoValor.jasper"

e no gerarPedido adicione: (troque "C:\DiretorioDoSubrelatorio\" pelo diretorio aonde está o jasper do sub relatorio
...
Map parametros = new HashMap();
parametros.put("SUBREPORT_DIR","C:\DiretorioDoSubrelatorio\");
JasperPrint impressao = JasperFillManager.fillReport(relatorio,parametros, jrRS);
...

Answer: resolvi meu problema, fiz as seguinte alterações:
Principal, em defaultValueExpression eu coloquei o real caminho do sub relatório e alterei a linguagem para Java. Para um caminho mais dinâmico pode ser usado o segundo método que o Rodrigo de Bona citou.
No sub relatório eu apenas alterei a linguagem para java. Ainda sim dava um erro de conexão null.
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report2" language="java" columnCount="2" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="401" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="04e67a5f-9121-468f-a228-62c2dcf438c2"><property name="ireport.zoom" value="1.6105100000000014"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="144"/>
<parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
<defaultValueExpression><![CDATA["/"]]></defaultValueExpression>
</parameter>

Solução do erro de conexão, como na minha classe do Jasper já possuia uma conexão, enviei ela mesmo para que faça a consulta.

   public void gerarPedido(String query, int tipo, String nome) throws JRException, SQLException, IOException {
xml += "\\pedidoMeiaPagina.jrxml";
JasperDesign desenho = JRXmlLoader.load(xml);
JasperReport relatorio = JasperCompileManager.compileReport(desenho);

PreparedStatement pstmt = this.conexao.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();

JRResultSetDataSource jrRS = new JRResultSetDataSource(rs);

Map parametros = new HashMap();
parametros.put("REPORT_CONNECTION",conexao);
JasperPrint impressao = JasperFillManager.fillReport(relatorio,parametros, jrRS);

if (tipo == 1) {
    JasperPrintManager.printPage(impressao, 0, true);
} else if (tipo == 0) {
    caminho += nome;
    JasperExportManager.exportReportToPdfFile(impressao, caminho);

} else if (tipo == 2) {
    JasperViewer.viewReport(impressao, false);
}

}

Espero que ajude, abraços!


Retornar mensagens através de exceções

Question: Olá, me gerou uma dúvida com relação a forma mais "elegante" para o meu método exibir uma mensagem para o usuário.
Estou utilizando o seguinte blade com objetivo de retornar as mensagens, porém ele não retorna Exceptions, na verdade os exceptions travam minha aplicação sempre que são disparados.
Observem que no meu método verificarUpdate existem alguns cenários que talvez fossem interessante mostrar como feedback ao usuário.
Existe alguma forma de em alguns casos essas execeções serem covertidos para mensagem de erro? O laravel traz alguma facilidate para isso?
feedback.blade.php
    @if ($errors->any())

                @foreach ($errors->all() as $error)
                    {{ $error }}

                @endforeach

    @endif

    @if (isset($mensagem))

        {{ $mensagem }}

    @endif

Classe RegistradorDeEncarregado
namespace App\Services;

use App\Encarregado;
use Illuminate\Support\Facades\DB;
use Exception;

class RegistradorDeEncarregado
{

    public function desabilitarEncarregado(int $id): Encarregado
    {
        DB::beginTransaction();
        $result = Encarregado::where('id', $id)
        ->update([
            'ativo' => 0]);
        DB::commit();

        return $this->verificarUpdate($result, $id);
    }

    private function verificarUpdate(bool $result, $id){
        $encarregado = Encarregado::find($id);

        // Cenário perfeito
        if($result && isset($encarregado)){
            return $encarregado;

        // Quando o id que vai sofrer a alteração já possui
        // o mesmo valor do parâmetro
        }else if(!$result && isset($encarregado)){
            throw new Exception('Registro já se encontra com o(s) parâmetro(s) de alteração.');

        // Id não existente
        }else{
            throw new Exception('Não foi possível alterar o registro do encarregado.');
        }
    }
}

Classe EncarregadoController
    public function disability(
            Request $request,
            RegistradorDeEncarregado $registradorDeEncarregado)
    {
        $encarregado = $registradorDeEncarregado->desabilitarEncarregado($request->id);
        $request->session()
            ->flash(
                'mensagem',
                "Encarregado {$encarregado->nome} salvo com sucesso."
            );

        return redirect()->route('encarregado_listar_ativos');
    }

Comment: não consegui entender o exibir de forma mais elegante. Você está dizendo mensagens normais de seu sistema a partir de um array['success','danger','info','warning'] OU erros da aplicação, fatalError, etc? Edite sua pergunta para ficar mais claro e assim conseguirmos te ajudar melhor. Abraço
Comment: Pergunta editada. De forma geral, estou tentando trazer os exeptions citados no meu método para a tela do sistema.
Answer: Exception não deveria ser mostrada, eles pode até conter dados sigilosos que não deveriam ser lidos por usuários comuns. Mas caso queira fazer eles aparecerem na aplicação é fazer:
try {
    ..codigo
} catch (Exception $e) {
    echo 'Exceção capturada: ',  $e->getMessage();
}

Como você está usando blade, então no catch tem que retornar a view como a variavel da mensagem do exception.
Tipo:
try {
    ..codigo
} catch (Exception $e) {
    $mensagemErro = $e->getMessage();
    return view('paginaView', ['erro' => $mensagemErro]);
}

Comment: De certa forma, então, uma estratégia interessante seria retornar um mensagem genérica ao usuário e atravéz de algum tipo de log registrar a exceção gerada para posteriormente ser tratada.

Retornar mensagens através de exceções


make all gives linker command fail error in caffe installation

Question: After following all the steps in caffe installation, I find this error:
clang: warning: argument unused during compilation: '-pthread'
Undefined symbols for architecture x86_64:
  "cv::imread(std::string const&, int)", referenced from:
      caffe::WindowDataLayer<float>::InternalThreadEntry() in window_data_layer.o
      caffe::WindowDataLayer<double>::InternalThreadEntry() in window_data_layer.o
      caffe::ReadImageToDatum(std::string const&, int, int, int, bool, caffe::Datum*) in io.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [.build_release/lib/libcaffe.so] Error 1

What can be done. I tried all possible cases, reinstalling and finding in githun issues.
Thanx in advance.
Comment: Same problem here :(
Comment: Please answer this if you get any solutions. I will edit the question if I get any solutions. Thanx
Answer: Seems like you have not installed OpenCV in your system.
If you are using the Homebrew package manager, try executing the following commands
brew tap homebrew/science
brew install homebrew/science/opencv

If the above two line of commands do perform without any error, try building Caffe again.


Basic understanding of compact sets in regards to covers

Question: So before my book even goes into the theorem that says "A set $E \subset R $ is compact iff E is closed and bounded", they go into examples of an open set, but I'm having trouble understanding their thought process.
Let $E=(0,1]$ and for each positive integer n, let $G_n=(\frac{1}{n},2)$. If $0 <x\le 1$ there is a positive integer $n$ such that $\frac{1}{n}<x$, hence $x \in G_n$ and thus $E \subset \cup_{n=1}^{\infty}G_n$.
Ok, I get that part, basically since $\frac{1}{n}$ goes to $0$ as $n \to \infty$, but never equals $0$, E is contained in the union of $G_n$. However, the next part I don't understand...
"Choose a finite set $n_1,n_2,...,n_r$ of positive integers, then
$\cup_{i=1}^{\infty}G_{n_i}=G_{n_0}$ where $n_0=$max{$n_1,...n_r$}." I don't understand how $G_{n_1}+G_{n_2}+...+G_{n_r}=G_{n_0}$. The largest subcover?
And finally why is $E  $ not a subset of $G_{n_0}$
Comment: Check for typos in your third-to-last and second-to-last paragraph. Is the union finite or infinite?
Comment: $A \cup B \neq A + B$. Also this question has nothing to do with compactness, so you should edit the title.
Comment: @SilviaGhinassi it shows why open sets can't be compact
Comment: $E$ is not closed, but it's also not open. Please consider rephrasing your first sentence to clarify.
Comment: @SilviaGhinassi but isn't the compliment of a closed set, an open set?
Comment: No, it's not a compl**e**ment of a closed set!
Answer: The equality $G_{n_1} \cup G_{n_2} \cup \ldots \cup G_{n_r} = G_{n_0}$ (use union, not addition, these are quite different!) holds because the $G_i$ are increasing: if $i < j$ then ${1 \over j} < {1 \over i}$ so that $G_i = (\frac{1}{i},2) \subset (\frac{1}{j},2) = G_j$.
This means that if we look at any finite set of indices, there is a maximal one among them, and because the larger the index, the larger the set (as we saw), this means that the union of the corresponding $G_i$ is just the one with the largest index, and this is what your text essentially says.
Now, if $G_{n_0}$ is any fixed member of your open cover, then find $x$ with $0 < x < \frac{1}{n_0}$. Then this $x$ is in $(0,1]$ but not in $G_{n_0}$. So one member cannot cover $(0,1]$. So, using what we have seen in the previous paragraph, no finite set of members can cover $(0,1]$, because a finite subset has as its union the one with the largest index, which cannot cover by itself.
This implies that $(0,1]$ is not compact. Compactness of $E$ means every open cover of $E$ has a finite subcover. But here we have some cover, that does not have a finite subcover. And this is exactly what is needed to refute compactness.
Note that by the closed and bounded theorem, which holds in the reals in the usual metric, $[0,1]$ is compact. So just removing a single point (making it non-closed) makes $E$ non-compact, which is the point of the example.


Turn dict with duplicate keys into list containing these keys

Question: I receive a response I have no control over from an API. Using requests response.json() will filter out duplicate keys. So I would need to turn this response into a list where each key is an element in that list: What I get now:
{
  "user": {
    //...
  },
  "user": {
    //...
  },
  //...
}

What I need:
{
  "users": [
   {
    "user": {
      //...
   }
   },
   {
    "user": {
      //...
    }
    },
    //...
  ]
}

This way JSON won't filter out any of the results, and I can loop through users.
Comment: Does this answer your question? [Python json parser allow duplicate keys](https://stackoverflow.com/questions/29321677/python-json-parser-allow-duplicate-keys)
Comment: Your expected json structure is invalid
Comment: I see I missed 2 curly brackets, should be valid now. @LiuXiMin no I've checked all there thread and maybe I'm just not experienced enough but that has not helped me answer my question. Not sure why I get downvotes and vote for duplicate when its not a duplicate. The answer in that Q is not the answer to this question. Maybe some of you can use it to figure out the answer to this Q but I cant.
Comment: @Majs I posted an answer, which should work
Answer: Okay, let me have a try by method used in Python json parser allow duplicate keys
All we should do is handle the pairs_list by ourself.

from json import JSONDecoder

def parse_object_pairs(pairs):
    return pairs

data = """
{"foo": {"key": 2, "key": 3}, "foo": 4, "foo": 23}
"""

decoder = JSONDecoder(object_pairs_hook=parse_object_pairs)
pairs_list = decoder.decode(data)

# the pairs_list is the real thing which we can use

aggre_key = 's'

def recusive_handle(pairs_list):
    dct = {}
    for k, v in pairs_list:
        if v and isinstance(v, list) and isinstance(v[0], tuple):
            v = recusive_handle(v)
        if k + aggre_key in dct:
            dct[k + aggre_key].append({k: v})
        elif k in dct:
            first_dict = {k: dct.pop(k)}
            dct[k + aggre_key] = [first_dict, {k: v}]
        else:
            dct[k] = v
    return dct

print(recusive_handle(pairs_list))

output:
{'foos': [{'foo': {'keys': [{'key': 2}, {'key': 3}]}}, {'foo': {'bar': 4}}, {'foo': 23}]}


Como verificar se um tipo é numérico em C++?

Question: Vamos supor que eu tenho uma função:
template<class T>
T soma(const T& x, const T& y) {
    static_assert(/*O tipo é for numérico?*/, "Tipo de argumento inválido, O argumento precisa ser numérico");
    return x + y;
}

Dá pra saber se o tipo T é numérico?
Comment: acho que aqui tem tudo https://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Answer: Se está usando uma versão mais antiga do C+= tem que recorrer a alguns truques para obter o resultado esperado. No SO tem uma resposta com um deles. Tem outras fontes que indicam truques. Ou pode fazer assim:
static_assert(is_arithmetic_v<T>::value, "Must be arithmetic");

Se já estiver usando C++ 17 e precisar fazer mais que um assert. tem algo na linguagem que ajuda muito que é o if constrexpr. Exemplo:
template<class T> struct dependent_false : std::false_type {};
template<class T>
T soma(const T& x, const T& y) {
    if constexpr (std::is_arithmetic_v<T>)
        return x + y;
    else
        // faz alguma coisa aqui
        static_assert(dependent_false<T>::value, "Must be arithmetic");
}

Coloquei no GitHub para referência futura.

Legal para saber mais
Paper de como chegou aí
Exemplos com comparação para o C++ 14
Mais exemplos

E finalmente se puder esperar pelo C++ 20 poderá fazer uso de Concepts que é a solução definitiva. As opções acima são paliativos porque a linguagem não pode expressar em código restrições no uso da variável gabaritada de forma direta.
Comment: estou usando c++ 17
Answer: A partir do C++11 você pode usar a função std::is_arithmetic da biblioteca padrão type_traits para verificar se um tipo arbitrário se trata de um número inteiro ou real (ponto flutuante), veja só:
#include <iostream>
#include <type_traits>

class A {};

int main()
{
    std::cout << std::boolalpha;
    std::cout << "A:           " <<  std::is_arithmetic::value << '\n';
    std::cout << "bool:        " <<  std::is_arithmetic<bool>::value << '\n';
    std::cout << "int:         " <<  std::is_arithmetic<int>::value << '\n';
    std::cout << "int const:   " <<  std::is_arithmetic<int const>::value << '\n';
    std::cout << "int &:       " <<  std::is_arithmetic<int&>::value << '\n';
    std::cout << "int *:       " <<  std::is_arithmetic<int*>::value << '\n';
    std::cout << "float:       " <<  std::is_arithmetic<float>::value << '\n';
    std::cout << "float const: " <<  std::is_arithmetic<float const>::value << '\n';
    std::cout << "float &:     " <<  std::is_arithmetic<float&>::value << '\n';
    std::cout << "float *:     " <<  std::is_arithmetic<float*>::value << '\n';
    std::cout << "char:        " <<  std::is_arithmetic<char>::value << '\n';
    std::cout << "char const:  " <<  std::is_arithmetic<char const>::value << '\n';
    std::cout << "char &:      " <<  std::is_arithmetic<char&>::value << '\n';
    std::cout << "char *:      " <<  std::is_arithmetic<char*>::value << '\n';
}

Saída:
A:           false
bool:        true
int:         true
int const:   true
int &:       false
int *:       false
float:       true
float const: true
float &:     false
float *:     false
char:        true
char const:  true
char &:      false
char *:      false

No seu caso:
#include <type_traits>

template<class T>
T soma(const T& x, const T& y) {
    static_assert( std::is_arithmetic<T>::value, "Tipo de argumento inválido, O argumento precisa ser numérico");
    return x + y;
}

Comment: Obrigado por me ensinar sobre o std::boolalpha