Como alterar o valor de um input por uma factory?

Question: Eu tenho um <input type=file> e quero adicionar o path da imagem a este input para enviar o formulario para meu webservice. Eu consigo pegar o caminho da imagem através de uma factory e não consigo alterar o valor desse input adicionando o path.
Como eu faço para mudar o valor desse input pela factory ?
input
<input type="file" ng-model='User.imageFile' id='imageFile'/>

factory
var app = angular.module('starter');

app.factory('CameraFactory', ['$q', function($q) {

    var options = {
        quality: 50,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: 0,      // 0:Photo Library, 1=Camera, 2=Saved Photo Album
    }

    var onSuccess = function(imageData) {
        window.resolveLocalFileSystemURI(imageData, function(fileEntry) {
            //console.log(fileEntry.nativeURL);
            var imageFile = document.getElementById('imageFile');
            imageFile.value = fileEntry.nativeURL;
        });

        var image = document.getElementById('smallimage');
        image.src = imageData;

    };

    var onFail = function(e) {
        console.log("onFail! " + e);
    };

    return {
        getPicture: function() {
            return navigator.camera.getPicture(onSuccess,onFail,options);
    }
  }
}]);

Answer: Colega, você está abordando o problema sem levar em conta a filosofia do angularjs que é alterar o DOM somente através de diretivas.
Uma factory não deveria alterar o DOM.
Um controller não deveria alterar o DOM.
Você diz que quer "adicionar o path da imagem a este input para enviar o formulario para meu webservice"
Então, você está utilizando o input para salvar temporariamente o valor do caminho da imagem e conseguir recuperá-lo de outro ponto em seu código. Você não precisa fazer isso.
Você pode salvar a string do caminho da imagem em uma variável na factory (lastImagePath, por exemplo), ou enviá-la de um callback ou promise após o plugin recuperar a imagem.
Exemplo (não testado!) da opção de callback:
app.factory('CameraFactory', function($q) {

    var options = {
        quality: 50,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: 0,  // 0:Photo Library, 1=Camera, 2=Saved Photo Album
    }

    return {
        getPicture: function(cback) {
            var onSuccess = function(imageData) {
                window.resolveLocalFileSystemURI(imageData, function(fileEntry) {
                    if (cback) cback(
                            { success:true,
                              path: fileEntry.nativeURL,
                              imageData: imageData
                            }
                    );
                });

            };

            var onFail = function(e) {
                console.log("onFail! " + e);
                if (cback) cback( {success:false} );
            };

            navigator.camera.getPicture(onSuccess, onFail, options);
    }
  }
});

Então, no seu controller:
CameraFactory.getPicture( function(result) {
     if (result.success) {
           // faça algo com result.path e result.imageData
     } else {
           console.log('falhou...');
     }
);

Comment: perfeito, funcionou exatamente como eu queria. muito obrigado.
Answer: A modificação que você está fazendo, está fora do escopo do angular, ela é feita diretamente no elemento html. Atualmente, o angular não consegue reconhecer este tipo de alteração e por tanto é necessário solicitar a ele que atualize seu escopo. Para isso você precisará injetar nesta factory o $rootScope e executar o seguinte código após alterar o elemento de imagem:
var onSuccess = function(imageData) {
    window.resolveLocalFileSystemURI(imageData, function(fileEntry) {
        //console.log(fileEntry.nativeURL);
        var imageFile = document.getElementById('imageFile');
        imageFile.value = fileEntry.nativeURL;
        $rootScope.$apply()
    });

    var image = document.getElementById('smallimage');
    image.src = imageData;
    $rootScope.$apply()
};


Can't find application class in @INC when starting Mojolicious-generated app

Question: I generated a mojolicious app with the command mojo generate app first-app. It generated the app structure that should allow a running example when running the dev server with morbo ./script/first-app.
The file structure looks like this:
mojo app structure
My error when running morbo ./script/first-app in the root of the project directory is this error:
Can't load application from file "/home/djnorrisdev/Documents/mojo-practice/first-app/script/first-app":
    Can't find application class "first-app" in @INC. (
    /home/djnorrisdev/Documents/mojo-practice/first-app/lib
    /home/djnorrisdev/perl5/perlbrew/perls/perl-5.30.0/lib/site_perl/5.30.0/x86_64-linux
    /home/djnorrisdev/perl5/perlbrew/perls/perl-5.30.0/lib/site_perl/5.30.0
    /home/djnorrisdev/perl5/perlbrew/perls/perl-5.30.0/lib/5.30.0/x86_64-linux
    /home/djnorrisdev/perl5/perlbrew/perls/perl-5.30.0/lib/5.30.0)
Compilation failed in require at (eval 72) line 1

(Line breaks added for readability. An indented line is a continuation of the previous line.)
I tried using the full path for morbo (as mentioned in a 6 year old SO post), but that gives the same error as above. That command was this: /home/djnorrisdev/perl5/perlbrew/pls/perl-5.30.0/bin/morbo ./script/first-app
I'm guessing anyone familiar with a full mojolicious app would be familiar with the script file, but here's the contents of script/first-app :
#!/usr/bin/env perl

use strict;
use warnings;

use Mojo::File 'curfile';
use lib curfile->dirname->sibling('lib')->to_string;
use Mojolicious::Commands;

# Start command line interface for application
Mojolicious::Commands->start_app('first-app');

Considering this is a mojolicious-generated app, I would assume it should not get an @INC error and run with morbo without issue. Does anyone have insight into this?
Comment: I tried this:: `mojo generate app first-app` and got error `Your application name has to be a well formed (CamelCase) Perl module name like "MyApp"`. So I tried again with `mojo generate app TestApp` and that worked. I then did `cd  test_app` and ran `morbo script/test_app` and it worked (I got the welcome page at http://127.0.0.1:3000/ ) I am using `perl` version 5.28.1, Ubuntu 19.04, Mojolicious version 8.14
Answer: For your setup to work, first-app.pm would have to contain package first-app;, but that's not legal code because of the dash. Håkon Hægland suggests that mojo generate app first-app should not have worked (presumably to avoid this very problem), so it's unclear how you came to have the setup you describe.
To fix the problem, you could rerun mojo generate app with a more suitable name (such as FirstApp) and start over.
Alternatively, you should theoretically be able to fix the problem with as little as three changes:

Rename lib/first-app.pm to a more conventional name such as lib/FirstApp.pm.
Change the argument passed to ->start_app to 'FirstApp'.
Change the package directive in now-named lib/FirstApp.pm to package FirstApp;.

A module's path, a module's package directive, and the use statement used to load the module —the value passed to ->start_app in this case— must all match. The three changes ensures this for the module in question.
[Note: I have no experience with Mojo.]
Comment: Thank you, naming it with PascalCase worked. I previously tried #1-3 before I posted the original post, but I was still not using best naming practices that time either. As to why it didn't error out during the generate app command, I have no clue.


Why does a goodness of fit test use the chi square distribution rather than the hypothesised distribution?

Question: This is a homework(-like) question. I know the answer but don't understand it.

If we were to answer the question "Are 5 different groups of mammals equally common?", what test would you perform?

The answer is: goodness-of-fit test to a Chi-squared distribution.
Why?
Why a Chi-square distribution? I would rather chose a null hypothesis to be that all group are equally common, therefore the abundance would be uniformally distributed. I would calculate a chi-squared value using $\frac{N}{5}$ as expected values (for the 5 expected values), where $N$ is the total number of observed individuals. Wouldn't it be right? Therefore, I would do a g-o-f test to a uniform distribution, isn't it?
Comment: You're right about the null hypothesis--but exactly how would you go about testing it?
Comment: @whuber I would calculate a chi-squared value using $\frac{N}{5}$ as expected values (for the 5 expected values), where $N$ is the total number of observed individuals. Wouldn't it be right? Therefore, I would do a g-o-f test to a uniform distribution, isn't it? Thanks!
Comment: What's your question, then?  With the edit it asks why a $\chi^2$ GOF test should be used and then explains why a $\chi^2$ GOF test should be used. There seems to be nothing left to say.
Comment: oh sorry if it was unclear. The question is why a goodness-of-fit test **to a chi-squared distribution**? Maybe the question [here](http://stats.stackexchange.com/questions/125313/are-there-as-many-males-than-females-in-the-population) makes more sense because the distribution is not chi-squared but binomial. Let me know if my question makes sense. I may just missunderstand the way the answer key is formulated!
Comment: A related question with more focus on why chi-squared goodness of fit test can be used to test if data come from the binomial distribution: http://stats.stackexchange.com/questions/104468/understanding-the-chi-squared-test-and-the-chi-squared-distribution
Answer: There are two different distributions in play - the distribution of your data (or strictly speaking, the hypothesised distribution of the population they are drawn from), and the distribution of your test statistic under the assumption that the null hypothesis is correct. This is a little subtlety that I find can catch people out when they are new to the concept, but in fact it is usually the case that the null distribution of your test statistic is quite different to the (hypothesised or actual) distribution of your data.*
Using a chi squared goodness of fit test means that if your null hypothesis is true, then your test statistic, $\chi^2 = \sum_{i=1}^n {\frac{(O_i - E_i)}{E_i}^2}$, would follow a chi square distribution (at least, approximately - you may hear it called "asymptotic", i.e. for large samples it should be close enough to chi square for practical purposes). This is why you use the chi square distribution tables. Remember that $\chi^2$ is larger if your data is a bad fit to the hypothesised distribution, since in this case the square of the difference between expected and observed frequencies, the $(O_i - E_i)^2$ in the numerators, is large. So if $\chi^2$ is larger than the critical value in the tables, you have significant evidence against the null hypothesis, in the sense that a $\chi^2$ value that large, and hence a fit that poor, would be unlikely if the hypothesised model were true.
None of this means that your data is chi squared distributed, or that you expect it to be so. The expected frequencies $E_i$ used in the $\chi^2$ calculation are premised on the population having whatever distribution is specified according to $H_0$.
We can look at this in more detail. Supposing that $H_0$ is true so the expected frequencies are "correct" (they may not match the observed frequencies precisely, but if we were to take hundreds of samples and tabulate each one, then in each category the average of our observed frequencies should be very close to the expected one), then the quantity $\frac{O_i - E_i}{\sqrt{E_i}}$ will behave approximately like a z-score for that cell. The sum over all the cells of $\sum_{i=1}^n {\frac{(O_i - E_i)}{E_i}^2}$ is then, roughly, the sum of squared z-scores. Perhaps you already know that the random chi-squared variable with $\nu$ degrees of freedom, $\chi^2_\nu$, is the sum of the squares of $\nu$ independent standard normal variables. You may now be able to see that, so long as your data were drawn from a population whose distribution matched your null model, your test statistic will approximately follow a chi-squared distribution.
Things are actually slightly more complicated - since the total of the expected frequencies equals the total of the observed frequencies, the total of $O_i - E_i$ must be zero. Hence the value of $O_i - E_i$ in the last cell is completely determined by what happened in the previous cells, so our "z-scores" weren't quite independent. Fortunately we can compensate for this by subtracting one from the degrees of freedom, which explains why in your case, with 5 cells in your table and hence 5 values of $\frac{(O_i - E_i)^2}{E_i}$ in your sum, you'd compare your test statistic to the critical value listed in the tables for $\chi^2_4$. If your test statistic is above the critical value, this tells you the sum of squared z-scores would be unlikely to be so high. Were your null hypothesis true, then your test statistic should behave like the sum of squared z-scores, so the fact it came out so high constitutes evidence against the null hypothesis - i.e. it suggests your population did not follow the hypothesised distribution.
$*$ The very first hypothesis test that many people learn is the Z test for the mean, where the data are sampled from a normal distribution of known variance $\sigma^2$ and the null hypothesis is $H_0: \mu = \mu_0$ . In this case, all three of the population distribution, the sample mean and the z-score (the test statistic for this test) are normally distributed. But this is rarely true for hypothesis tests in general. Moreover, for the Z test, assuming the null hypothesis is true, their distributions are $X \sim \mathcal{N}(\mu_0, \sigma^2)$, $\bar{X} \sim \mathcal{N}(\mu_0, \frac{\sigma^2}{n})$ and $Z \sim \mathcal{N}(0, 1)$. So on closer inspection we see that, even here, the distributions of the data and the test statistic are quite different after all.
Comment: +1 It might help your readers' understanding a little to point out that the test statistic only *approximately* has a $\chi^2$ distribution. Indeed, the test statistic can be seen as a way of combining five $Z$ statistics of the form $(O_i-E_i)/\sqrt{E_i}$, one for each group, into a single overall statistic reflecting all five $Z$'s at once. Thus a glimmer of the connection to the Normal theory in your last paragraph may show through the otherwise mysterious formula.
Comment: @whuber I was tempted to do so, I might expound on it yet, but hopefully your comment provides some insight at least. I regularly teach this topic to high school students and I find the biggest thing that throws them is that there are two completely different distributions in play, each serving a completely different purpose. If I've managed to communicate clearly why the two are distinct, I've achieved the main aim!
Comment: @whuber Right, I added a bit. A bit of hand-waving about degrees of freedom but I think at the introductory level this is probably the best approach! For the benefit of future readers, do we already have some good Q&As on the degrees of freedom adjustment that could be linked in the answer?
Comment: Check out http://stats.stackexchange.com/questions/16921/how-to-understand-degrees-of-freedom.
Comment: @whuber That is one of my all-time favourite threads on CV. Maybe a little daunting for a beginner, but very valuable! As a more specific supplement, do we have a thread that addresses the issue of df for a chi square goodness of fit test? Preferably in the basic case like this one, though the meatier problem where some parameters of the fitted model were estimated from the data would do. I'm thinking along the lines of "a next step for the curious".
Comment: http://stats.stackexchange.com/questions/104468/understanding-the-chi-squared-test-and-the-chi-squared-distribution This thread on "Understanding the Chi-squared test and the Chi-squared distribution" explains in a little more detail the "z score" nature of the distribution, in the case where the original distribution is chi-squared.


Find areas in matrix c++

Question: I need to find how many areas and with how many elements are there in a matrix. The matrix is filled with 0 and 1. We have an area if there are adjacent 1 (diagonal, vertical or horizontal).
<code>int count_regions( int *arr, int rows, int cols ) {
    int region_count = 0;

    for ( int first_index = 0; first_index != rows * cols; ++ first_index ) {
        if ( arr[ first_index ] == 0 ) continue;

        ++ region_count;

        int first_row = first_index / cols, first_col = first_index % cols;
        int last_col;
        for ( last_col = first_col;
              last_col != cols && arr[ first_row * cols + last_col ] != 0;
              ++ last_col ) ;

        for ( int last_row = first_row;
              last_row != rows && arr[ last_row * cols + first_col ] != 0;
              ++ last_row ) {
            for ( int col = first_col; col != last_col; ++ col ) {
                arr[ last_row * cols + col ] = 0;
            }
        }
    }
    return region_count;
}
</code>
Comment: What is your question?
Answer: Try having a look at connected components labelling algorithms.

Find areas in matrix c++


What does it mean to play in an 'arpeggiated' style on the guitar?

Question: I sometimes hear a guitar player described as having an 'arpeggiated' style, such as Peter Buck of R.E.M.
I know that an arpeggio is the 1st, 3rd, 5th and 8th of a scale, but exactly what does it mean to play this style on the guitar?
Comment: Note, that an arpeggio is not always the 1st, 3rd and 5th; it's a decomposition of the chord, so e.g. for a Dsus4, it's the 1st, 4th and 5th.
Answer: An arpeggio is simply a chord played one note at a time.  So if you're playing in an arpeggiated style, then instead of strumming the chords, you'll play each note of the chord one at a time.  You mention Peter Buck, whose playing on "Everybody Hurts" is a perfect example of arpeggiated playing.
Strumming a D-chord:
<code>$D.0.$G.2.$B.3.$e.2 $D.0.$G.2.$B.3.$e.2 $D.0.$G.2.$B.3.$e.2 | $D.0.$G.2.$B.3.$e.2 $D.0.$G.2.$B.3.$e.2 $D.0.$G.2.$B.3.$e.2 | $D.0.$G.2.$B.3.$e.2 $D.0.$G.2.$B.3.$e.2 $D.0.$G.2.$B.3.$e.2 | $D.0.$G.2.$B.3.$e.2 $D.0.$G.2.$B.3.$e.2 $D.0.$G.2.$B.3.$e.2 ||
</code>
Arpeggiating a D-chord:
<code>$D 0 $G 2 $B 3 | $e 2 $B 3 $G 2 | $D 0 $G 2 $B 3 | $e 2 $B 3 $G 2 ||
</code>


Feedly API & JSON

Question: I'm trying to access the Feedly API to collect and share articles automatically to a Facebook group. So far, I haven't even able to figure out how to use the Feedly API wrapper located here: https://github.com/zgw21cn/FeedlyClient
from feedlyclient import FeedlyClient

# Feedly

feedaccess = "removed"
myfeedId = "removed"

con = FeedlyClient()
con.get_feed_content(feedaccess,myfeedId,False,10000)
parsed = json.loads(con)
print json.dumps(parsed)

Terminal
PS D:\Python Projects\Python 2\fbauto> & python "d:/Python Projects/Python 2/fbauto/feedlytest.py"
Traceback (most recent call last):
  File "d:/Python Projects/Python 2/fbauto/feedlytest.py", line 8, in <module>
    con = FeedlyClient.get_feed_content(feedaccess,myfeedId,False,10000)
TypeError: unbound method get_feed_content() must be called with FeedlyClient instance as first argument (got str instance instead)
PS D:\Python Projects\Python 2\fbauto> & python "d:/Python Projects/Python 2/fbauto/feedlytest.py"
Traceback (most recent call last):
  File "d:/Python Projects/Python 2/fbauto/feedlytest.py", line 9, in <module>
    con.get_feed_content(feedaccess,myfeedId,False,10000)
  File "d:\Python Projects\Python 2\fbauto\feedlyclient.py", line 75, in get_feed_content
    return res.json()
  File "C:\Python27\lib\site-packages\requests\models.py", line 892, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Python27\lib\json\__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Please help.
SECOND ATTEMPT
import json
import requests

# Feedly

feedaccess = "REMOVED"
myfeedid = "user/REMOVED/category/tutorial"

def get_feed_content(unreadOnly=None, newerThan=None, count="10",
                         continuation=None,
                         ranked=None):
        """
        return contents of a feed
        :param access_token:
        :param streamId:
        :param unreadOnly:
        :param newerThan:
        :param count:
        :param continuation:
        :param ranked:
        :return:
        """

        headers = {'Authorization': 'OAuth ' + feedaccess}
        quest_url = ('http://cloud.feedly.com/v3/streams/contents')
        params = dict(streamId=myfeedid)
        # Optional parameters
        if unreadOnly is not None:
            params['unreadOnly'] = unreadOnly
        if newerThan is not None:
            params['newerThan'] = newerThan
        if count is not None:
            params['count'] = count
        if continuation is not None:
            params['continuation'] = continuation
        if ranked is not None:
            params['ranked'] = ranked
        res = requests.get(url=quest_url, params=params, headers=headers)
        return res.json()

con = get_feed_content()
print json.dumps(con , indent=4)

TERMINAL
{
    "items": [],
    "id": "user/REMOVED/category/tutorial"
}

Just returns my user credentials. Feedly documentation says I can use category as stream ID. https://developer.feedly.com/v3/streams/
THIRD ATTEMPT
import json
import requests
from client import FeedlyClient

# Feedly

feedaccess = "REMOVED"
myfeedid = "user/REMOVED/category/tutorial"
feedcount = "20"
myurl = "http://cloud.feedly.com/v3/streams/contents?streamId=" + myfeedid + "&count=" + feedcount

headers = {'Authorization': 'OAuth ' + feedaccess}
res = requests.get(url=myurl, headers=headers)
con = res.json()
print json.dumps(con , indent=4)

SAME TERMINAL RESPONSE
Comment: You don't seem to have followed any of the instructions in that library's readme to get a valid client object.
Comment: I read a comment on their developer forum that the process for getting an access token is by applying for a code as stated in the ReadMe. I didn't understand the ReadMe itself. The link provided doesn't lead to anywhere that has so-called ID & key. There's client id & secret in the forum that gets posted/updated every month. Feedly does generate an access token for developers and I figured this might be good enough since those comments are from years ago.

A clearer step by step by step instruction would be appreciated. Let's say I get the keys. Then what? Where do I plug them?
Answer: The third attempt worked. There was a capitalization in my category name. It should be Tutorial not tutorial. Please see original post for code.

Feedly API & JSON


Question regarding cardinality and pigeonhole principle

Question: Suppose $A$ and $B$ are finite sets and $f:A\rightarrow B$. Prove that if $|A|>|B|$, then $f$ is not one-to-one.
Scratch work:
Since the goal is in negation, I try to prove it by contradiction and assume that $f$ is one-to-one. Since $A$ has more elements than $B$, it can't be the case that $f$ is one-to-one because some $a\in A$ has to share images with other. But other than the false assumption $f$ is one-to-one, I have no other clue to proceed with the question. What technique should I apply? Please give hints and guidance. Thanks in advance.
Comment: Another interesting (and useful) exercise in this vein is that if $|A| = |B| = n \in \mathbb{N}$ then $f: A \to B$ is injective iff it is surjective iff it is bijective.
Answer: Let $f(A)$ be the set of images. Then $f(A)\subseteq B$ so $|f(A)|\le |B|$.
If $f$ is one-to-one then $|f(A)|=|A|$.
Answer: Select a subset $A' \subset A$ such that $|A'| = |B|$. Let $A' = \{a_1, a_2, \dots, a_n\}$ and $B = \{b_1, b_2, \dots, b_n\}$. There is a trivial bijection (one-to-one and onto) $f:A' \to B$.
Now assume $g$ is a one-to-one mapping $A \to B$ which when restricted to $A'$ is $f$.
There exists $a_{n+1} \in (A - A')$ which is mapped to some element $b_i \in B$. However, for every element $b_i \in B$, there already exists $a_i \in A'$ such that $f(a_i) = b_i$. Hence $g(a_{n+1}) = g(a_i) = f(a_i) = b_i$ and $g$ is not one-to-one.
Comment: Sorry because I didn't state the question clearly. The question itself asks to prove the pigeonhole principle, so the pigeonhole principle can't be used in the proof.
Comment: @Dave I see. But you can basically use the same kind of reasoning. I changed a bit, does that help?
Answer: We write $A\preceq B$ if there exists an injection $A\to B$.
Theorem: Let $A, B$ be finite sets. Then, $A \preceq B, \iff \#A \le \#B$.
Proof: ($\Rightarrow$)
Let $\varphi(n)$ be the statement "B is a set of size $\,n\,$ and $A \preceq B \rightarrow \#A \le n$."
$$S = \left\{\,n\in \omega:\varphi(n)\, \right\}.$$
For $n = 0\,$, B is the empty set, and the only injection is to itself. So, clearly $0 \in S.$ Assume $n \in S $ we need to show that $n^{+} \in S$.
Suppose  $ \#B =n^{+}$ and $\,f: A \rightarrow B\,$ is an injective map. We choose an element $b\in B$. If $\,b \in f[A] $ then $ f(a) = b\,$ for a unique $a\in A$. Let $A^{*} = A-\left\{a \right\}$ and $\,B^{*} = B -\left\{b \right\}$. We define the function $g: A^{*} \rightarrow B^{*}$ to be the restriction of $f$ in $A^{*}$, i.e., $\,g = f\restriction_{A^{*}}$. Then, $g\,$ is a one-to-one function and by our inductive hypothesis $\#A^{*} \le \#B^{*}.$ But since $\#A^{*} = \#A-1\,$ and $\#B^{*} = n$. Then, $\#A-1 \le \ n \rightarrow \#A \le n^{+} .$
If $b \notin f[A]$. Let $B^{*} = B-\left\{b \right\}$. Where $f: A \rightarrow B^{*}$ is a one-to-one function, and by inductive hypothesis $\#A \le \#B^{*}.$ But since $\#B^{*} = \#B-1 = n$. Then, $\#A \le n^{+} $.
Hence $n^{+} \in S$ which close the induction.
($\Leftarrow$) We need to show that $\#A \le \#B$ implies the existence of an injective map $f: A\rightarrow B$.
For $\#B = 0\,$, that means $\#A = 0$. And clearly $f: \emptyset \rightarrow \emptyset $ is an injection. Suppose our claims holds for n, we need to show that also holds for $n^{+}$.  For $\# B = n^{+}$, as $n^{+} \not = 0\,$ the set is nonempty, so  there exist an element $b \in B$. Let $B^{*} = B -\left\{b \right\}$, then we have that $\#B^{*} = n$.
If $\#A \le \#B^{*}$ by our inductive hypothesis, there exist a injective map $g : A \rightarrow B^{*}$. Let $i_{ B^{*} \rightarrow B}$ be the inclusion map, i.e., $i_{ B^{*} \rightarrow B}: B^{*} \rightarrow B : j \mapsto j\,$, which is an injection. Therefore, the composition $\, i_{ B^{*} \rightarrow B} \circ g: A \rightarrow B\,$, is an injection as desired.
If $\, \#A \not\le \#B^{*}$ but $ \#A \le \#B $, i.e., $ \#A = n^{+}$. We set $A^{*} = A-\left\{a \right\}$. Then $\#A^{*}\le \#B^{*}$ and by the inductive hypothesis there exist an injective map $h': A^{*} \rightarrow B^{*}$. We can define the function $h: A \rightarrow B$, by adding the ordered pair $ \langle a, b \rangle $ to the function $h'$. That is, $h: = h' \cup \left\{\,  \langle a, b \rangle  \, \right\}$ (as $ \langle a, b \rangle $ is a genuine extra element, the map $h$ is one-to-one).  $\;\;\ \Box$
Since $\#A> \# B$ then by the above theorem cannot exists an injective map $A$ to $B$.


Apache rewrite rule causes "too many redirects" for JS and CSS files

Question: I'm working on a project with a custom CMS (which is written by someone else). There's an existing .htaccess file with some conditions and rewrite rules, one of which directs requests to the index.php file. This file loads the CMS object, and calls a method to check if the URL leads to an existing CMS page. If it doesn't, the user is redirected to a 404 page.
The CMS also allows you to build custom modules on top of the base CMS functionality. Usually this is used for user management and stuff like that, but for this project the client wants to be able to build a knowledge base with hundreds of knowledge base items, which in the CMS would become a giant mess. I've now built a custom module for these items, and they also store a slug. I want the URLs to be /knowledgebase/items/item-slug, but with the existing configuration this would lead to a redirect to the 404 page because, as far as the CMS is aware, the item-slug doesn't lead to an existing CMS page. This is the current rewrite section in the .htaccess file.
# Enable the rewrite engine
RewriteEngine On
RewriteBase /domain.tld

# SSL Redirect 301 transfer the current request.
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# never rewrite for existing files, and links
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
#RewriteCond %{REQUEST_FILENAME} !-d

# For Friendly URLs
RewriteRule ^knowledgebase/items/(.*)$ index.php?knowledge_item_slug=$1 # my own RewriteRule
RewriteRule ^(.*)$ index.php [L]

In index.php I've added the following lines to check if a custom knowledgebase item needs to be shown
if (isset($_GET['knowledge_item_slug']) && $_GET['knowledge_item_slug'] !== '') {
    include_once(__DIR__ . '/components/knowledgebase_item.php');
    exit(0);
}

This works fine, going to knowledgebase/items/test loads the test item as it should. With this rule added however, CSS and JS files can no longer be found after a hard reload (clearing the cache) and cause net::ERR_TOO_MANY_REDIRECTS errors in the console.
I've modified the rule to RewriteRule ^kennisbank/items/(.*)$ index.php?knowledge_item_slug=$1 [C] (basically just added the [C] flag) and now the item detail page works, but any other page causes the error The requested URL /domain.tld/page was not found on this server.
I've also tried placing RewriteRule ^(.*)$ index.php above my own RewriteRule (without the [L] flag, obviously), but then my own one doesn't work at all.
I'm not too familiar with Apache rewrites, any idea what's causing this issue?
Answer: Problem is that you have 2 RewriteRule rules after checking for non-file and non-directory in RewriteCond. Only immediate next RewriteRule is affected by one or more RewriteCond hence last rule executes without any conditions that routes every request including css/js/images to index.php.
You can have your .htaccess as this:
# Enable the rewrite engine
RewriteEngine On
RewriteBase /domain.tld

# SSL Redirect 301 transfer the current request.
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

# never rewrite for existing files, and links
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

# For Friendly URLs
RewriteRule ^knowledgebase/items/(.*)$ index.php?knowledge_item_slug=$1 [L,NC,QSA]

RewriteRule ^ index.php [L]

Do-nothing rule RewriteRule ^ - [L] will skip any rules below that line for the conditions above i.e. non-file and non-directory.


Particle Filter: Confidence Intervals

Question: Context
This is a basic question about confidence intervals. So the standard way to estimate a confidence interval.Assuming we have a set of $N$ random variables $\{X^i\}$ such that all of them are i.i.d. We know that the mean of is converges to the central limit of a $N(\mu,\frac{\sigma^2}{N})$, where $\mu$ is the true mean of $X^i$ and $\sigma^2$ is the true variance of $X^i$. Note: we are not assuming $X^i$ are normally distributed.
 The confidence interval can be estimated
$$ CI_{upper}=\bar{x}+1.96\frac{s}{\sqrt{N}}$$
where $s$ is the square root of the sample variance. The idea to me here is quite simple. Assuming $N$ is large enough, we carry out an experiment ONCE, compute $\bar{x}=\frac{1}{N}\sum x^i$, which is an unbiased estimate of $\mu$ and compute $s=\frac{1}{N-1} \sum (x^i-\bar{x})^2 $ which is an unbiased estimate of $\sigma^2$. So our confidence interval gives as the uncertainty of repeating the experiment $M$ times, i.e. if we repeated $M$ times we will expect $\mu$ to be inside the confidence interval 95% of the time. In code this can be written as,(this can also be seen as estimating only mean and variance of a single random variable)
<code>x<-rnorm(100)
mean(x)
var(x)
mean(x)+1.96*var(x)/sqrt(N)
</code>
Note: I am assuming i.i.d and I will come to a situation where I am uncertain whether i.i.d applies and if it doesn't how do we compute non-i.i.d confidence intervals.
Particle Filter
I am constructing a particle filter estimating , $p(x_t|y_{1:t})$. I want to estimate confidence intervals for the mean estimates of my particles at time $t$. I hypothesize that my mean estimates are the best estimate of the state,although this is not entirely true. In effect I have an approximation of , $p(x_t|y_{1:t})$  by a set of weighted samples $\{x^i_t, w^i_t\}$.
Therefore, I compute the weighted  mean
$$\bar{x}_t=\frac{1}{N}\sum w^i_tx^i_t$$
I intend to compute two quantities the variance of $\bar{x}_t$ and the confidence intervals around $\bar{x}_t$.The purpose of this is really to see how frequent resampling occurs effects variance, therefore, keep in mind that I may have resampled my particles $\{x^i_t, w^i_t\}$ from the previous time step and the index $i$ is not representative of the particle at time $t-1$.
Some theoretical consequences
There exists central limit theorems that state that my weighted approximation, $E(\hat{p}(x_{t}|y_{1:t}))$ converges in distribution to a normal distribution with mean $E(p(x_{t}|y_{1:t})$ and some unknown variance $\sigma_{pf}^2$, where $\hat{p}(x_{t}|y_{1:t})=\frac{1}{N}\sum w^i_t\delta(x_t-x^i_t)$. I am unaware of any independence and identically distributed assumptions. Although I read somewhere that $\{x^i_t,w^i_t\}$ are independent but not identically distributed.
How do I calculate the variance?
I tried to calculated the variance using simulation of the the data $\{y_t\}$(I can generate $y_t$ because I know $x_t$) to compute $\bar{x}_t$.These are the steps I took 1) Generate $\{y_t\}$ 2) Run the filter 3)Obtain $\bar{x}_t$
4) Repeat  1)-3) $M$ times  5)With my collection of $M$ pieces of  $\bar{x}_t$, we will denote by $\{\bar{x}_t\}$ I compute the  $mean(\{\bar{x}_t\})$ to get an estimate of $E(p(x_{t}|y_{1:t})$ and  $var(\{\bar{x}_t\})$ to get an estimate $var(p(x_{t}|y_{1:t})$. My confidence interval is therefore,
$$CI_{upper}=mean(\{\bar{x}_t\})+1.96var(\{\bar{x}_t\})$$
Notice I do not divide by $\sqrt{M}$.
QUESTION

Have I computed the variance and confidence intervals correctly?I am really treating $\bar{x_t}$ as a random variable and getting monte carlo estimates from it.Also when I compute the confidence interval, I did not use the number of simulations. Also in consideration of the fact that $\{x^i_t\}$ might not be identically distributed am I estimating the $var(\{ \bar{x}_t\})$ correctly?
Is there a way I can compute confidence interval of $\bar{x}_t$ without needing to simulate?
Was it correct that I obtained instances of $\bar{x}_t$ by generating a new  $\{y_t\}$ at each simulation. Does this not change the distribution I am estimating in the first place, $p(x_t|y_{1:t})$?

EDIT: in response to @Taylors comments

As you can see that my constructed confidence intrevals which are shown by the two red lines are too narrow. My true states which are shown by black dots are outside of the interval too frequently. I am using a simple random walk with fixed process variance of 1 and measurement variance of 3. The narrow interval was when I divide by $\sqrt{N}$ and the wide interval is when I don't divid by $\sqrt{N}$
Answer: You might want to check your formulas for the sample means and sample standard deviations once you start talking about particle filters. Also, the particles are not independent if you are resampling. But they are identical. I think you have that backwards.
Otherwise, if you weren't resampling, you would just be using the Law of Large Numbers, more basic Central Limit Theorems, and Slutsky's theorem to guarantee that sample means and standard deviations are the way to go. You've been asking a lot of questions about the Doucet/Johansen tutorial lately, and that tutorial mentions a few sources on the theorems you're asking about. Specifically they say:

SMC methods involve systems of particles which interact (via the
  resampling mechanism) and, consequently, obtaining convergence results
  is a much more difficult task than it is for SIS where standard
  results (iid asymptotics) apply. However, there are numerous sharp
  convergence results available for SMC; see [10] for an introduction to
  the subject and the monograph of Del Moral [11] for a complete
  treatment of the subject. An explicit treatment of the case in which
  resampling is performed adaptively is provided by [12].

To answer (1), you can drop the $1/N$ because your normalized weights sum to $1$ already:
$$
\bar{X}_t = \sum_i W_t^iX^i_t = \sum_i \frac{w_t^i}{\sum_jw_t^j} X^i_t
$$
$$
S^2_t = \sum_i W_t^i (X^i_t - \bar{X}_t)^2.
$$
Regarding (2) and (3), you probably never want to simulate your observed data.
Comment: @tintinthong yeah but it's a fancy central limit theorem. Also I think you mean $CI_{upper}=\bar{X}_t+1.96\frac{\sqrt{S^2_t}}{\sqrt{N}}$
Comment: @TaylorAhhhh. That makes so much more sense to think of it that way. Therefore, $x^i_t$ in a sense come from the same proposal distribution and when if $w^i_t$ is equal(in resampling) then $x^i_t$ are distributed according to posterior, $p(x_t|y_{1:t})$? So if I want to obtain my confidence intervals it would be $CI_{upper}=\bar{X}_t+1.96\frac{S^2_t}{\sqrt{N}}$, where $N$ is the number of particles and I do not need to run any simulations but I only need to rely on the central limit theorem.
Comment: Yes, indeed thanks for the correction. Taylor if you look in the confidence intervals plot I included, I found that when I divide by $\sqrt{N}$ it becomes too narrow. This is when I resample 50% of the time and with 500 particles for 100 time steps. Does this seem right?
Comment: Note this is a particle filter, not a joint smooth
Comment: @tintinthong you've gotta divide by $\sqrt{N}$. Maybe you have a bug somewhere else. It might be that you're using variance instead of standard deviation in the numerator. You've made this mistake a few times in your post. Also, variance is sometimes smaller than standard deviation, which might be what's going on. Lengthy comment discussions are ill-advised on this site, so if you have more questions, you should make another thread.

Particle Filter: Confidence Intervals


How to calculate price value and tax value in query

Question: i try to filter product price when customer insert minimun value and maximum value.
product.php
public function getProducts($data = array()) {
....

if (!empty($data['min'])) {
    $sql .= " AND p.price BETWEEN '" .$data['min']. "' AND 9999 ";
}

with this code, category page will list out all products from price x until 9999.
The problem is some product has tax and the value is store in another table(oc_tax_rate). So how to get final price of product in query ? (p.price + tax) , something like this :
if (!empty($data['min'])) {
    $sql .= " AND final_price BETWEEN '" .$data['min']. "' AND 9999 ";
}

as i check page controller/category.php
$this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax'))

above code will return final price.
OC : v1.5.6
Answer: First of all, when You use a min and max filter values, Your query should not be choosing between min and 9999 and between 0 and max but You should do this:
if (!empty($data['min'])) {
    $sql .= " AND p.price >= " . (int)$data['min'];
//                               ^^^^^ - against SQL injection!!!
}

and
if (!empty($data['max'])) {
    $sql .= " AND p.price <= " . (int)$data['max'];
//                               ^^^^^ - against SQL injection!!!
}

Also, as mentioned in the comment, do not forget to cure Your code against SQL injection!
Now, to Your real question: It is not possible to get the taxes and calculate taxed price along with products getting in one query. But You could do this in Your model - find this part of code
foreach ($query->rows as $result) {
    $product_data[$result['product_id']] = $this->getProduct($result['product_id']);
}

and we will modify it this way:
foreach ($query->rows as $result) {
    if (!empty($data['min'])
            && $this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')) >= $data['min']) {
        $product_data[$result['product_id']] = $this->getProduct($result['product_id']);
    } else if (!empty($data['max'])
            && $this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')) <= $data['max']) {
        $product_data[$result['product_id']] = $this->getProduct($result['product_id']);
    } else {
        $product_data[$result['product_id']] = $this->getProduct($result['product_id']);
    }
}

Comment: that awesome, thanks :D, i hope i will release free extension for opencart after fix this issue.


Do I *have to* flatten all hierarchical component declarations in React.JS?

Question: I'm wondering what the canonical method is for creating a dynamic select component in React. Do I have to create a separate component that returns options as per the code below in order to be able to customize the value through props for each entry, and then include these into a separate select component?
class ListEntry extends React.Component {
  render = () => {
    return(
      <option value={this.props.ovalue}>{this.props.ovalue}</option>
    )
  }
}

class SomeList extends React.Component {
  genstuff = (n) => {
    var theEntries = [];
    for(var i = 0; i < n; i++) {
      theEntries.push(<ListEntry ovalue={Math.random().toString()} />)
    };
    return(theEntries)
  }

  render = () => {
    var entries = this.genstuff(10);
    return(
      <select>
        {entries}
        <ListEntry ovalue="a basic entry"/>
        <ListEntry ovalue="another"/>
      </select>
    )
  }
}

Is there another "accepted" way to do this within the SomeList component itself? If so, what are the advantages, disadvantages?
I have also used this technique (successfully) for svg elements so the above question applies too:
class SmallCircle extends React.Component {
  render = () => {
    return(
      <circle cx={this.props.scx} cy={this.props.scy} r="5"
        stroke="blue" fill="dodgerblue" strokeWidth="2"/>)
  }
}

class SomeSvg extends React.Component {

  randomCoords = (n, domain) => {
    let xs = [...Array(n).keys()].map(i=> {
      return {
        "i": i,
        "x": Math.floor(Math.random() * domain + 1).toString(),
        "y": Math.floor(Math.random() * domain + 1).toString()
      }
    })
    return(xs)
  }

  render = () => {
    var svgcoords = this.randomCoords(5000, 700);
    var thecircles = svgcoords.map(xy => <SmallCircle key={xy.i.toString() + xy.x.toString() + xy.y.toString()}
        scx={xy.x} scy={xy.y} />);
    return(
      <svg width="700" height="700">
        {thecircles}
        <circle cx="1" cy="1" r="100" stroke="orange" strokeWidth="7" fill="grey" />
        <circle cx="700" cy="700" r="100" stroke="green" strokeWidth="7" fill="grey" />
        <circle cx="1" cy="700" r="100" stroke="red" strokeWidth="7" fill="grey" />
        <circle cx="700" cy="1" r="100" stroke="blue" strokeWidth="7" fill="grey" />
        <SmallCircle scx="200" scy="200" />
      </svg>
    )
  }
}

So basically my question is, does React require you to "unwrap" (ie flatten) hierarchical component structures into multiple granular top-level components all the time?
Here is the output, btw:

EDIT: I do realise I haven't included a "key" for each select entry and it's complaining in the console, but the question isn't affected by this.
Comment: If you wish to flatten, you can assign an additional prop called "parentID" to your list entry that helps in easily referencing it. If you wish not to flatten it, then you might want to a prop to your list entry with "children".

If you think I'm somewhere close to what you wish to achivie then I could probably help with an answer. I propose something along these lines. For *Flattened:* options ``  for *Heirarchial*: ` return } />`
Comment: Can you try to reformulate your question please? I'm not sure what you're asking?
Comment: No I think it's perfectly clear. "Flattening" a hierachical data structure, in computer science, means parsing it down into a vector (ie an array). That's what I'm asking about react. I have hierarchical display elements, but I'm having to declare them in a flattened form. I'm asking if this is the canonical way of doing things, as in, do I have to declare internal elements externally to the component, in a serial form, as opposed to creating sub-components within the components themselves. see: https://softwareengineering.stackexchange.com/questions/70743/what-does-flatten-mean
Comment: Seem you need [stateless](https://facebook.github.io/react/docs/components-and-props.html#functional-and-class-components)
Comment: Do you mean that all your circles are supposed to be organized hierarchically ? Maybe you can show in your question what kind of hierarchy they should have.
Comment: I have given two examples. The first is circles in an SVG, and the second is options in a select. In both cases, I must create a sub-component OUTSIDE the svg component, or OUTSIDE the select statement. This seems to be the only way to create sub-components in REACT. So basically the "natural" html hierarchical paradigm is transformed into a flattened serial paradigm. I don't know why this is so difficult to understand. Please only attempt to answer if you have a formal background in computer science, and experience of data structures across different programming languages.
Answer: No, React does not require you to do that.
If you wanted to, you could put all your React code in 1 giant component.
So, why not do that? There's many reasons actually: readability, reusability, testability, maintainability, etc.
Meaning: you create seperate components when you need certain logic to stand on its own. In your question, you have ListEntry as a seperate component. Why? If you dont use that component anywhere else in your code, you can just put that logic inside SomeList if you wanted to.
I think the key to your question is this: you dont need to inherit from React.Component if you dont use any of its logic. Basic 'stateless components' can be written as a function:
function MyComponent(props) {
    (...some logic...)
    return <option>{ props.value }</option>;
}

Or, ES6 equivalent:
const MyComponent = props => {
    (...some logic...)
    return <option>{ props.value }</option>;
}

or, if you dont need any logic in the rendering at all:
const MyComponent = props => <option>{ props.value }</option>;

So, you could just define this function in your components render (or in the function body for stateless components), like so:
class SomeList extends Component {
    render() {
        const ListEntry = props => <option>{ props.value }</option>;
        return (
            <select>
                { [...Array(10).keys()].map(x => (
                    <ListEntry key={x} value={Math.random()} />
                ))}
                <ListEntry value="basic" />
                <ListEntry value="another" />
            </select>
        );
    }
}

Here, the code for our ListEntry component is defined in the SomeList components' render. (disclaimer: I don't think render is the best place for this tho, it's just to illustrate the point).
Though, I don't really see the point in doing so. Since ListEntry doesnt contain any logic, why not use <option> directly instead of ListEntry?
It could be a simple as:
const SomeList = () => {
    return (
        <select>
            { [...Array(10).keys()].map(index => (
                <option key={index}>{ Math.random() }</option>
            ))}
            <option>Basic</option>
            <option>Another</option>
        </select>
    );
};

As for your SVG example: if you take the above and create functions for the components you need, it could be written like this:
const SomeSvg = () => {
    const SmallCircle = props => (
        <circle {...props} r="5" stroke="blue" fill="dodgerblue" strokeWidth="2" />
    );

    const BigCircle = props => (
        <circle {...props} r="100" strokeWidth="7" fill="grey" />
    );

    const randomCoords = (n, domain) => [...Array(n).keys()].map(() => ({
        x: Math.floor(Math.random() * domain + 1),
        y: Math.floor(Math.random() * domain + 1)
    }));

    return (
        <svg width="700" height="700">
            { randomCoords(5000, 700).map((xy, i) => <SmallCircle key={i} cx={xy.x} cy={xy.y} />) }
            <BigCircle cx="1" cy="1" stroke="orange" />
            <BigCircle cx="700" cy="700" stroke="green" />
            <BigCircle cx="1" cy="700" stroke="red" />
            <BigCircle cx="700" cy="1" stroke="blue" />
            <SmallCircle cx="200" cy="200" />
        </svg>
    );
};

Answer: React doesn't have any opinion on how much granular your component structures should be. It might be one component with some props or multiple components.
So Select component can be something like follows.
class Select extends Component {
  render() {
    return (
      <select>
        <option value="">Select...</option>
        {this.props.options.map(option =>
          <option key={option.value} value={option.value}>
            {option.text}
          </option>
        )}
      </select>
    );
  }
}

You can simply provide a JavaScript array as option and it will work nicely.
var options = [
  { value: 'one', text: 'One' },
  { value: 'two', text: 'Two' }
];

<Select options={options} />

Now let's say we got a new requirement to highlight some options of one Select component of your application based on some criteria. We got few options here.
The simplest option would be writing another similar component with highlighting logic. But this will duplicate most of our code and make it hard to maintain.
Another option is to pass an additional prop and conditionally enable highlighting logic based on the prop. Again, this isn't scalable. When we get several new requirements like this it will be hard to maintain our component's code and understand the interface of it.
However, if we make our component based on multiple composable components it will be easy to customize your component based on different requirements. In this case, we can introduce a highlight prop to Option component and simply conditionally pass the prop based on the criteria.
class Option extends Component {
  render() {
    return (
      <option
        value={this.props.value}
        className={this.prop.highlight ? "highlight" : ""}
      >
        {this.props.text}
      </option>
    );
  }
}

class Select extends Component {
  render() {
    return (
      <select className="my-select">
        {this.props.children} // render children of Select tag
      </select>
    );
  }
}

class HighLightingSelect extends Component {
  render() {
    return (
      <Select>
        {this.props.options((option, index) =>
          <Option key={option.value} value={option.value} highlight={index % 2}>
            {option.text}
          </Option>
        )}
      </Select>
    );
  }
}

The idea here is it's totally up to you to decide how much granularity you want in your component structures. It can be one component or a dozen of components which need be composed together to get the expected result.
If you make it more granular, it will be easy to customize and reuse your code in different situations. Especially, React promote composition over inheritance for code reuse. So granularity is key to reusability in React.
But having multiple components will make it harder to understand and use your component in simple scenarios.
Comment: This is an excellent answer too, @Tharaka Wijenbandara, but I must award to only one and the other answer just got an extra point. Thank you anyway. Very useful.


Find a weak solution of the ODE

Question: Find a weak solution to the following ODE:
$u' + u = H_0(x)$ where $H_0(x) = \begin{cases}
0 & x < 0 \\
1 & x \geq 0 \end{cases}$
My professor advised that we try to guess the solution and then verify it. My first guess was naive because I did not know the "derivative" (I put quotes here because this isn't really a derivative) of $H_0(x)$ was $\delta_0(x)$. I thought it was $0$. I still state this because something consistent is happening.
If you do guess $u = H_0$, we can go ahead and attempt to find the weak derivative. Consider $\phi \in C_{c}^{\infty}$ (continuous functions with compact support)
Then,
$\displaystyle-\int_{-\infty}^{\infty} \phi'(x)u(x)dx = -\int_{-\infty}^{0} \phi'(x) * 0 dx - \int_{0}^{\infty} \phi'(x) * 1 dx$
Using integration by parts,
$\displaystyle-[\phi(x) * 0 |_{-\infty}^{0} + \int_{-\infty}^{0} \phi(x) * 0 dx - [\phi(x) * 1 |_{0}^{\infty} + \int_{0}^{\infty} \phi(x) * 0 dx$
The first term is $0$ due to the multiplication. The third term only leaves the lower limit because $\phi$ is compactly supported. Therefore, I am left with
$\displaystyle\boxed{\phi(0)} + \int_{-\infty}^{\infty} \phi(x) * 0 dx$.
This is very close to what I wanted, but I have an extra $\phi(0)$.
After our next lecture, I found out that the weak derivative of $H_0(x)$ does not exist and we need the distribution derivative to make it $\delta_0(x)$. Therefore, I knew my initial guess was wrong.
My next guess was to solve the ODE for both "components." What I mean is solve $u'+u = 0$ and $u' + u = 1$. Just to see if this worked, I first plugged these into wolfram alpha and got $c e^{-x}$ and $c e^{-x} + 1$ respectively. Therefore, my guess was $u = \begin{cases}
ce^{-x} & x < 0 \\
ce^{-x} + 1 & x \geq 1 \end{cases}$.
Now, I attempted to find $u'$
\begin{align}&-\int_{-\infty}^{\infty} \phi'(x) u(x) dx = -\int_{-\infty}^{0} \phi'(x) ce^{-x} dx - \int_{0}^{\infty} \phi'(x) (ce^{-x}+1) dx \\&= -\int_{-\infty}^{0} \phi'(x) ce^{-x} dx - \int_{0}^{\infty} \phi'(x) ce^{-x} dx - \int_{0}^{\infty} \phi'(x) dx\\
&= -\int_{-\infty}^{\infty} \phi'(x) ce^{-x} dx - [\phi(x) |_{0}^{\infty} \\ &= -[\phi(x) ce^{-x} |_{-\infty}^{\infty} + \int_{-\infty}^{\infty} \phi(x) (-ce^{-x} dx) + \phi(0)\\
&= \boxed{\phi(0)} + \int_{-\infty}^{\infty} \phi(x) (-ce^{-x})dx\\ \end{align}.
Again. $\phi(0)$ is there, At this point, I asked my professor if he could give me a hint. He told me my initial guess should be the solution to the ODE involving each component, which is exactly what I did. Since I did get the solutions through wolfram alpha,I went ahead and solved both ODEs by hand just to make sure something weird didn't happen. I ended up with $ce^{-x}$ and $1 - ce^{-x}$ respectively.
While the second one is slightly different, it shouldn't make a difference because $c$ is a constant, so it could "absorb" the $-$ sign. I won't go through the details again, but one will end up with
$\displaystyle\boxed{\phi(0)} + \int_{-\infty}^{0} \phi(x) (-ce^{-x}) dx + \int_{0}^{\infty} \phi(x) (ce^{-x}) = \boxed{\phi(0)} + \int_{-\infty}^{\infty} \phi(x) u'(x) dx$ where $u'(x) = \begin{cases}
-ce^{-x} & x < 0 \\
ce^{-x} & x \geq 1 \end{cases}$.
Again, the $\phi(0)$ is still there and I'm not sure how to get rid of it! Does anyone see what I'm doing wrong? Is my initial guess still wrong?
Thanks!
Comment: I don't know that I should give you a hint or not? because I often give this example to my students, lol ^^
Comment: $u'+u$ is the sort of thing that should remind you of integrating factors: if $v= e^x u$ then $v'=e^x(u'+u)$. Then you can directly integrate for the guessing
Answer: In your attempt for the piecewise solution you get different constants for both regions and have to ensure the continuity of the solution
$$
u(x)=\begin{cases}c_1e^{-x}&x<0\\1+c_2e^{-x}&x\ge 0\end{cases}
$$
with
$$
c_1e^0=1+c_2e^0
$$
so that
$$
u(x)=\begin{cases}ce^{-x}&x<0\\1+(c-1)e^{-x}&x\ge 0\end{cases}
\\=ce^{-x}+H_0(x)(1-e^{-x})
$$

You could also work with an integrating factor
$$
(e^xu(x))'=H_0(x)e^x\implies e^xu(x)=c+H_0(x)(e^x-e^0)
$$
Comment: This perfectly explained what I missed! I would have never found that on my own, I wasn't even thinking about it. That literally slipped my mind. Thanks for clarifying!
Answer: This is what my knowledge allows me:
Given differential system $\dot{x} = A \, x + B \, u$,  and output $y = C \, x$, its solution is below.
$x(t, \tau) = e^{A(t - \tau)} x(\tau) + \int^{\tau}_{t} \, e^{A \, (t - s)} \, B \, u(s) \, ds$
Suppose $u(s) = H_0(s)$ as you state. Hence, the solution for it is the equality below. THem matrix $X$ corresponds to the integral $\int^{\tau}_{t} \, e^{- A \, s} ds$. Finally, the output is $y(t, \tau) = C \, e^{A(t - \tau)} x(\tau) + C \, e^{A \, t} \, X(t, \tau) \, B$
$
\begin{aligned}
    x(t, \tau) & = e^{A(t - \tau)} x(\tau) + \int^{\tau}_{t} \, e^{A \, (t - s)} \, B \, H_0(s) \, ds \\
    & = e^{A(t - \tau)} x(\tau) + e^{A \, t} \, \left( \int^{\tau}_{t} \, e^{- A \, s} ds \right) B \\
    & = e^{A(t - \tau)} x(\tau) + e^{A \, t} \, X(t, \tau) \, B
\end{aligned}
$
For your case, matrix $A$ is a scalar $-1$, B is the scalar $1$ and C is the scalar $1$. Therefore, the solution is
$
\begin{aligned}
u(t, 0) = u(t) & = e^{-t} x(0) + e^{-t} \, X(t, 0) \\
& = e^{-t} x(0) + e^{-t} \, (e^t - 1) \\
& = e^{-t} x(0) + e^{-t} \, (e^t - 1) \\
& = e^{-t} x(0) - e^{-t} + 1
\end{aligned}
$

Find a weak solution of the ODE


Mockito matchers | Correct Usage

Question: Mockito provides a lot of matchers like any(), anyClass() etc.
People can debate on their usage. But I feel that matchers should be used when we don't really care about what the input object contains as long as it is of the expected class.
I just want to know if this usage is correct? If not, what is the better way to use them?
For example:
Say we have a test that expects a Runtime Exception, when a method is called with some request object. Since we explicitly throw a runtime exception here when the mock is called, it does not matter what the request object's contents are. So this test seems logical.
@Test(expected = RunTimeException.class)
public void testExceptionOccurs() {
  when(mock.method(any(RequestObject.class))).thenThrow(new RuntimeException());

  mock.method(new RequestObject());
}

Is this the correct way?
Answer: You're right that allowing any object of a given type is a great use for Matchers, and that you're calling matchers correctly, but the code isn't doing what you're describing.
In Mockito 1.x, any(RequestObject.class) will not actually check the type of the parameter. Its behavior is identical to anyObject(), except that previous to Java 8, the Java compiler couldn't infer a generic type specified as a parameter. Instead, use isA(RequestObject.class) to check types.

Mockito's default behavior is to check argument equality—specifically equality using equals (or == for primitive types). I've found any (and anyInt etc) to be the most valuable, because they ignore an argument entirely for the purposes of matching, but there are plenty of reasons that you'd want to override that equals behavior with Matchers:

To only check an argument's type, using isA.
To check instances more specifically than equals is defined for, like checking for referential equality using same.
To check properties of arguments, like that a passed bean has a certain value for one of its properties.
To reuse Hamcrest matchers via intThat, argThat, and so forth.

Final note: make sure that if you're using matchers or captors anywhere in your list of arguments, that you use one for each and every argument in that call. Mockito needs that 1:1 mapping.

UPDATE: Mockito committer Brice has offered some historical background and future direction:

For historical reference, any is a shorthand alias of anything, at that time the API was forcing one to cast, and contributors and/or commiters thought about passing the class as a param to avoid this cast, without changing the semantic of this API. However this change eventually modified what people thought that this API was doing. This will be fixed in mockito 2+
Comment: @Templar Definitely not "always": `isA` [rejects null](https://github.com/mockito/mockito/blob/master/src/main/java/org/mockito/internal/matchers/InstanceOf.java#L22), which may not be necessary or desirable. More importantly, Mockito syntax favors flexibility-by-default, to reduce test brittleness in response to refactors and other changes; it is typically unlikely that a parameter value will have a _relevant type but irrelevant value_ (where `any` would cover a wholly irrelevant parameter, and other matchers would cover a relevant value).
Comment: isn't it better to always use `isA` rather than `any`?

Mockito matchers | Correct Usage


NFS server refusing hostname that is allowed

Question: I can't get a client to mount an NFS share that is being exported using a wildcard domain name.
Setup:
The NFS server is running DNSMasq for DHCP and DNS.
the NFS export file has
/export *.domain.com(rw)

the /etc/hosts on the NFS server (which is used by dnsmasq) has:
192.168.0.5 phobos

If I try to mount the export from phobos the server denies the request.
but nslookup on the NFS server:
>nslookup 192.168.0.5
188.8.131.52.in-addr.arpa    name = phobos.domain.com.

if I change the /etc/hosts too:
192.168.0.5 phobos phobos.domain.com

it works, but I feel like I shouldn't have to do this?  Is the NFS server not using DNS?
Comment: What's the output of `getent hosts 192.168.0.5`?
Comment: @mgorven Thanks, I think I know what you might be getting at.  The /etc/hosts file was shorting DNS lookup.
Answer: I got this to work by switching my /etc/nssswitch.conf:
hosts: dns files

from
hosts: files dns

Comment: You don't really want to do that, it's generally expected that `/etc/hosts` overrides DNS.
Comment: i suppose the other options is to move the list of hosts that dnsmasq uses to a file other than /etc/hosts?  Seems like more work.
Comment: Yup, that's probably the way to go.


Is $\sum_{n\ge0}(-1)^n\frac{\Gamma(\tfrac{n+1}{2})}{\Gamma(\tfrac{n}2+1)}=\frac{2}{\sqrt{\pi}}$ true?

Question:
Prove/disprove $$\sum_{n\ge0}(-1)^n\frac{\Gamma(\tfrac{n+1}2)}{\Gamma(\tfrac{n}2+1)}=\frac{2}{\sqrt{\pi}}.\tag 1$$

As far as I can tell, this is true, although it seems to converge very slowly.
I came up with a proof but I don't know if it's valid.
Let $$J=\int_0^\pi \frac{xdx}{1+\sin x}.$$
On one hand, we have
$$\frac1{1+\sin x}=\sum_{n\ge0}(-1)^n\sin(x)^n,$$
so that
$$J=\sum_{n\ge0}(-1)^n p_n,\tag 2$$
where
$$
\begin{align}
p_n&=\int_0^\pi x\sin(x)^ndx\\
&=\int_\pi^0 -(\pi-x)\sin(\pi-x)^ndx\\
&=\pi\int_0^\pi\sin(x)^ndx-p_n\\
\Rightarrow p_n&=\frac\pi2\int_0^\pi\sin(x)^ndx.
\end{align}
$$
And since $\sin(x)=\sin(\pi-x)$, $$p_n=\pi\int_0^{\pi/2}\sin(x)^ndx=\frac{\pi^{3/2}}{2}\frac{\Gamma(\tfrac{n+1}2)}{\Gamma(\tfrac{n}2+1)}.\tag 3$$
On the other hand, we have $1+\sin x=2\sin^2(\tfrac{x}2-\tfrac\pi4)$, so that
$$\begin{align}
J&=\frac12\int_0^\pi\frac{xdx}{\sin^2(\tfrac{x}2-\tfrac\pi4)}\\
&=2\int_{\pi/4}^{3\pi/4}\frac{tdt}{\sin^2t}-\frac\pi2\int_{\pi/4}^{3\pi/4}\frac{dt}{\sin^2 t}\\
&=2\left(\ln\sin x-x\cot x\right)\bigg|_{\pi/4}^{3\pi/4}-\frac\pi2\left(-\cot x\right)\bigg|_{\pi/4}^{3\pi/4}\\
&=2\pi-\frac\pi2\cdot2=\pi.
\end{align}$$
Then from $(2)$ and $(3)$, we have
$$\frac{\pi^{3/2}}{2}\sum_{n\ge0}(-1)^n\frac{\Gamma(\tfrac{n+1}2)}{\Gamma(\tfrac{n}2+1)}=\pi,$$
which is equivalent to $(1)$. $\square$
Can you come up with any other proofs to $(1)$? Thanks!

Edit (11/12/2020):
Here is a proof that the interchange of the sum and integral in $(2)$ is valid.
The partial sums $$S_M(x)=\sum_{n=0}^M(-1)^n\sin(x)^n$$
form a uniformly convergent sequence of functions for $x$ in $[0,\pi/2)$ or $(\pi/2,\pi]$, and they converge to the limit $$\lim_{M\to\infty}S_M(x)=\frac1{1+\sin x},\qquad x\in[0,\pi]\setminus\{\pi/2\}.$$
Choose $\varepsilon>0$ and notice that
$$J=\int_{0}^{\pi}\frac{xdx}{1+\sin x}=\int_{\pi/2-\varepsilon}^{\pi/2+\varepsilon}\frac{xdx}{1+\sin x}+\int_0^{\pi/2-\varepsilon}\frac{xdx}{1+\sin x}+\int_{\pi/2+\varepsilon}^\pi\frac{xdx}{1+\sin x}.$$
The sums $S_M(x)$ converge uniformly as $M\to\infty$ when $x\in[0,\pi/2-\varepsilon]\cup[\pi/2+\varepsilon,\pi]$, so we can interchange the sum and integral to get
$$J=\int_{\pi/2-\varepsilon}^{\pi/2+\varepsilon}\frac{xdx}{1+\sin x}+\sum_{n\ge0}(-1)^n(a_n(\pi/2-\varepsilon)+b_n(\pi/2+\varepsilon)),$$
where
$$\begin{align}
a_n(t)&=\int_0^t x\sin(x)^ndx\\
b_n(t)&=\int_t^\pi x\sin(x)^ndx.
\end{align}$$
We have $a_n(t)+b_n(t)=p_n$ for all $t\in[0,\pi]$. As $\varepsilon$ approaches $0$, $\int_{\pi/2-\varepsilon}^{\pi/2+\varepsilon}\frac{xdx}{1+\sin x}$ approaches $0$.
And since $a_n(t), b_n(t)$ are continuous, $a_n(\pi/2-\varepsilon)+b_n(\pi/2+\varepsilon)$ approaches $a_n(\pi/2)+b_n(\pi/2)=p_n$, so that
$$J=\sum_{n\ge0}(-1)^np_n$$
as desired. $\square$
Comment: One may verify $\sum _{n=0}^{\infty } \frac{z^n \Gamma \left(\frac{n+1}{2}\right)}{\Gamma \left(\frac{n}{2}+1\right)}=\frac{2 \sin ^{-1}(z)+\pi }{\sqrt{\pi } \sqrt{1-z^2}}$, let $z\to -1^+$. QED.
Comment: This is, in principle, a valid proof, except one typo, it should be $$\frac1{1+\sin x}=\sum_{n\ge0}(-1)^n\sin (x)^n,$$ Interchangeability of summation and integration should be demonstrated, too, but that's very simple in this case.
Comment: @ProfessorVector see the edit. :)
Comment: @clathratus  One may express the sum in terms of hypergeometric functions which both admit closed form, right?
Comment: @RiverLi yes that is the case. I have found a solution using this which I will post tomorrow
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\on}[1]{\operatorname{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
$\ds{\bbox[5px,#ffd]{\sum_{n\ \geq\ 0}\pars{-1}^{n}\,{\Gamma(\bracks{n+1}/2) \over \Gamma(n/2 + 1)} =
{2 \over \root{\pi}}} \approx 1.1284:\ {\Large ?}}$

\begin{align}
&\bbox[5px,#ffd]{\sum_{n\ \geq\ 0}\pars{-1}^{n}\,{\Gamma(\bracks{n+1}/2) \over \Gamma(n/2 + 1)}}
\\[5mm] = &\
{1 \over \root{\pi}}\sum_{n\ \geq\ 0}\pars{-1}^{n}\,{\Gamma(n/2 + 1/2)\Gamma\pars{1/2} \over
\Gamma(n/2 + 1)}
\\[5mm] = &\
{1 \over \root{\pi}}\sum_{n\ \geq\ 0}\pars{-1}^{n}
\int_{0}^{1}t^{n/2 - 1/2}\,\,\,
\pars{1 - t}^{-1/2}\,\,\dd t
\\[5mm] = &\
{1 \over \root{\pi}}\int_{0}^{1}{1 \over \root{t}\root{1 - t}}\sum_{n\ \geq\ 0}\pars{-\root{t}}^{n}\,\dd t
\\[5mm] = &\
{1 \over \root{\pi}}\int_{0}^{1}{1 \over \root{t}\root{1 - t}}{1 \over 1 + \root{t}}\,\dd t
\\[5mm] \stackrel{t\ \mapsto\ t^{2}}{=} &\
{2 \over \root{\pi}}\int_{0}^{1}{1 \over
\root{1 - t^{2}}}{1 \over 1 + t}\,\dd t
\\[5mm] \stackrel{t\ \mapsto\ \sin\pars{\theta}}{=} &\
{2 \over \root{\pi}}\int_{0}^{\pi/2}
{\dd\theta \over 1 + \sin\pars{\theta}}
\\[5mm] = &\
{2 \over \root{\pi}}\int_{0}^{\pi/2}
\bracks{\sec^{2}\pars{\theta} - \sec\pars{\theta}\tan\pars{\theta}}\dd\theta
\\[5mm] = &\
{2 \over \root{\pi}}\
\underbrace{\bracks{\sin\pars{\theta} - 1 \over \cos\pars{\theta}}_{0}^{\pars{\pi/2}^{\,-}}}
_{\ds{=\ 1}}\ =\
\bbx{2 \over \root{\pi}} \approx 1.1284 \\ &
\end{align}
Comment: Fantastic. Thank you very much (+1)
Comment: @clathratus Thanks. Glad to see that was useful.
Answer: Based on this answer:
$$\frac{2}{\sqrt{\pi }}\int_{0}^{\infty }{\frac{1}{{{\left( 1+{{x}^{2}} \right)}^{\frac{n}{2}+1}}}dx}=\frac{\Gamma \left( \frac{n+1}{2} \right)}{\Gamma \left( \frac{n}{2}+1 \right)}$$
so the sum in question
$$\begin{align}
  & =\sum\nolimits_{n=0}^{\infty }{\left\{ {{\left( -1 \right)}^{n}}\frac{2}{\sqrt{\pi }}\int_{0}^{\infty }{\frac{1}{{{\left( 1+{{x}^{2}} \right)}^{\frac{n}{2}+1}}}dx} \right\}} \\
 & =\frac{2}{\sqrt{\pi }}\int_{0}^{\infty }{\sum\nolimits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}}{{{\left( 1+{{x}^{2}} \right)}^{\frac{n}{2}+1}}}}dx} \\
 & =\frac{2}{\sqrt{\pi }}\int_{0}^{\infty }{\frac{dx}{\sqrt{1+{{x}^{2}}}\left( 1+\sqrt{1+{{x}^{2}}} \right)}} \\
 & =\frac{2}{\sqrt{\pi }}\left. \frac{\sqrt{1+{{x}^{2}}}-1}{x} \right|_{0}^{\infty } \\
 & =\frac{2}{\sqrt{\pi }} \\
\end{align}$$
Comment: I think that you should add the part for interchange of integration and summation, as an answer.
Comment: Interchangeability of summation and integration should be demonstrated, but that's very simple in this case.
Comment: I'm not sure if interchanging the sum and integral is valid!!!!….yet i got the answer?
Answer: Using the well-known Maclaurin expansions for $\arcsin$ and its square, we first obtain
$$\begin{align*}
\arcsin x &= \sum_{n=0}^\infty \frac{\binom{2n}n}{2^{2n} (2n+1)} x^{2n+1} \\
\implies \frac1{\sqrt{1-x^2}} &= \sum_{n=0}^\infty \frac{\binom{2n}n}{2^{2n}} x^{2n} \color{red}{=: F(x)} \\[2ex]
\arcsin^2x &= \sum_{n=1}^\infty \frac{2^{2n-1}}{n^2 \binom{2n}n} x^{2n} \\
\implies \frac{2x\arcsin x}{\sqrt{1-x^2}} &= \sum_{n=1}^\infty \frac{2^{2n}}{n \binom{2n}n} x^{2n} \\
\implies \frac{2x^2}{1-x^2} + \frac{2x\arcsin x}{\left(1-x^2\right)^{3/2}} &= \sum_{n=1}^\infty \frac{2^{2n+1}}{\binom{2n}n} x^{2n} \\
\implies \frac{2\arcsin x}{\sqrt{1-x^2}} &= \sum_{n=0}^\infty \frac{2^{2n+1}}{(2n+1) \binom{2n}n} x^{2n+1} \color{blue}{=: G(x)}
\end{align*}$$
Now in the sum of interest, convert from gamma to binomial coefficient, then the sum to a limit.
$$\begin{align*}
& \sum_{n\ge0} (-1)^n \frac{\Gamma\left(\frac n2+\frac12\right)}{\Gamma\left(\frac n2 + 1\right)} \\
&= \sum_{n\ge0} \left[\frac{\Gamma\left(n+\frac12\right)}{\Gamma\left(n + 1\right)} - \frac{\Gamma\left(n+1\right)}{\Gamma\left(n+\frac32\right)}\right] \\
&= \sum_{n\ge0} \left[\Gamma\left(\frac12\right) \frac{\binom{2n}n}{2^{2n}} - \frac1{\Gamma\left(\frac12\right)} \frac{2^{2n+1}}{(2n+1) \binom{2n}n}\right] \\
&= \frac1{\sqrt\pi} \lim_{x\to1^-} \left[\pi \color{red}{F(x)} -  \color{blue}{G(x)}\right] = \boxed{\frac2{\sqrt\pi}}
\end{align*}$$
Answer: Under the Legendre duplication formula,
$$\Gamma(z)\Gamma(z+\frac12)=2^{1-2z}\sqrt{\pi}\Gamma(2z)$$
making:
$$\Gamma(z+\frac12)=2^{1-2z}\sqrt{\pi}\frac{\Gamma(2z)}{\Gamma(z)}$$
and so:
$$\frac{\Gamma(z+\frac12)}{\Gamma(z+1)}=2^{1-2z}\sqrt{\pi}\frac{\Gamma(2z)}{\Gamma(z)\Gamma(z+1)}=2^{1-2z}\sqrt{\pi}\frac{\Gamma(2z)}{z\Gamma^2(z)}$$
could you use this?
Comment: the only way I could think this would be helpful is if it helped express the sum in question as a hypergeometric series


Melhor estrutura HTML - Loja Virtual

Question: Fala galera, blz ?
Minha duvida é a seguinte, qual a melhor estrutura HTML para se montar uma loja virtual ? Levando em conta padrões de semântica e SEO.
Por exemplo:

Eu devo usar divs, li ou articles na listagem dos produtos ?
Ou devo utilizar articles apenas nas paginas de categorias e no restante divs ou li ?
Posso utilizar sections dentro de sections, para separar os produtos em uma mesma pagina ?

Seria algo parecido com isso ?
...

        Header Pagina

            Categoria 1

            Produto

            Categoria 2

            Produto

...

Comment: Isso não existe: _"Minha duvida é a seguinte, qual a melhor estrutura HTML para se montar uma loja virtual ? Levando em conta padrões de semântica e SEO."_ - Você tem que fazer a estrutura de acordo com o que vai acontecer com seu site, não tem como dar uma resposta pronta pra isso. Não teria como alguém te dar uma resposta que servisse pra qualquer situação. Já considerou a possibilidade de contratar um profissional da área?
Comment: Outra alternativa, se realmente está procurando uma "solução enlatada" é olhar os sites existentes no mercado e "se inspirar" pelo fonte deles, mas já adianto: muitos dos grandes portais nacionais de comércio eletrônico são forrados de serviço porco, então há o risco de você copiar porcaria. Notar que eu acho boa sua iniciativa em aprender a fazer certo, o alerta do primeiro comentário tem a intenção de você entender que não é simples assim, e que vai ter que se empenhar um bocado se quiser fazer por conta própria. Mas aí, vai ter que ser mais específico e pontual nas perguntas.
Comment: Aqui tem umas dicas pra fazer a pergunta ficar mais relevante: [ask] - Note que enquanto não tem respostas, você pode [edit] a pergunta à vontade e torná-la mais específica, dividindo sua dúvida em partes menores e possíveis de serem respondidas no formato Pergunta Objetiva -> Resposta Objetiva
Answer: Cara a tua pergunta não tem resposta porque não existe HTML estruturado para sites do tipo a ou b, o HTML é para estruturar como os elementos vão ser exibidos. Tentando te ajudar vou dizer o seguinte:

Pensando em otimizar o teu código para SEO sempre use HTML5, já que suas tags são procuradas pelos motores de busca por conta da semântica.
Estuda bem a finalidade de cada tag nova do HTML5 para não usá-las em contextos errados.
Código não é a coisa mais importante em se tratando de SEO, pense nisso e da uma pesquisada.
Eu devo usar divs, li ou articles na listagem dos produtos ? Ou devo utilizar articles apenas nas paginas de categorias e no restante divs ou li ? Não sei te responder porque isso depende de como vai ser estruturada a página.
Posso utilizar sections dentro de sections, para separar os produtos em uma mesma pagina ? Sim, section pode ficar dentro de outra section, isso não tem restrição, mas se vai atender a tua necessidade isso depende do conteúdo e da estrutura da página.

Melhor estrutura HTML - Loja Virtual


How Can I Understand this Vendor-Specific SMART Attribute?

Question: There are two contexts for this question, a general and a specific.
Generally, how does one find the meaning for vendor-specific S.M.A.R.T. attributes? I have searched the web high and low but found only partial information. Are there hard-to-find repositories that document this information?
Specifically, for the Western Digital drive pictured below (WDC WD4003FZEX-00Z4SA0), how should I interpret the vendor-specific SMART attribute ID 10 (10 Hex, 16 Decimal)?
From my understanding, a lower value indicates a more serious problem, but I can find no information on this particular ID.
Answer: I can't phrase it better than Wikipedia:

The term "S.M.A.R.T." refers only to a signaling method between internal disk drive electromechanical sensors and the host computer. Because of this the specifications of S.M.A.R.T. are entirely vendor specific and, while many of these attributes have been standardized between drive vendors, others remain vendor-specific.
...
issues remain due to attributes intentionally left undocumented to the public in order to differentiate models between manufacturers
...
manufacturers do not necessarily agree on precise attribute definitions and measurement units
...

So your best bet to understand all attributes of a specific disk and their implication is to use the vendor supplied tool, such as for instance the Western Digital Dashboard
Generic tools, although they can read all the supplied S.M.A.R.T. attributes, may not have the complete picture to interpret non-standard attributes in a meaningful way; displaying those as Vendor Specific is technically correct.
https://kb.acronis.com/content/9110 ;

Attribute ID: 10 (0x0A)
Hard drives, supporting this attribute: Samsung, Seagate, IBM (Hitachi), Fujitsu, Maxtor, Western Digital
Description:  Spin Retry Count S.M.A.R.T. parameter indicates the count of retry of spin start attempts. This attribute stores a total count of the spin start attempts to reach the fully operational speed (under the condition that the first attempt was unsuccessful). Spin attempts are counted for the entire hard drive's lifetime so far.


Joint density of $X_{(n)}-X_{(1)}$ and $X_{(n)}$ for Uniform distribution $[0,1]$

Question: I am trying to find the Joint density of $X_{(n)}-X_{(1)}$ and $X_{(n)}$ for Uniform distribution $[0,1]$, where $X_{(1)}$ and $X_{(n)}$ are the smallest and largest observation (of $n$ samples).
Firstly, I found the density of $X_{(n)}, X_{(1)}$. Let $U=X_{(n)}$ and $V = X_{(1)}$.
$$
\begin{aligned}
f_{U,V}(u,v)=n(n-1)(u-v)^{n-2} \qquad ; 0<v<u<1
\end{aligned}
$$
Also the density of $X_{(n)}$ is
$$
\begin{aligned}
f_{U}(u)=nu^{n-1} \qquad ; 0<u<1
\end{aligned}
$$
Now, I need to find the density of $R= X_{(n)}-X_{(1)}$.
Could you please give me an idea to proceed?
Answer: You can obtain the desired joint distribution by integrating like below.  Note that for the sake of my sanity I have switched $U$ and $V$ :)
First, an aside for future readers who don't spot where your joint density $f_{U,V}$ comes from.  Observe that $\mathbb{P}(U \ge u, V \le v) = \mathbb{P}(u \le X_i \le v$ for all $i) = (v-u)^n$ by independence of the variables.  Now take the (negative) derivative in both variables.
Suppose $a < b$ (you will see how to get the full answer with a simple modification below).  We have:
$$
\mathbb{P}(V - U \ge a, V \ge b)  = \int_b^1 \mathbb{P}(U \le v - a, V \in dv)\\
= \int_b^1 \int_0^{v-a} n(n-1)(v-u)^{n-2} du dv \\
= -n\int_b^1 \left.(v-u)^{n-1}\right|_0^{v-a} dv \\
= (1-b^n) - n(1-b)a^{n-1},
$$
where we used the condition $a < b$ to to ensure $v > b> a$ so that $v-a > 0$ in the integration limit in the second line.  If $a > b$ you can split up the outer integral and see the part between $a$ and $b$ vanishes.
Towards the end of your post you refer only to $R = V-U$, the marginal.  The density can be obtained by taking $b=0$ and then taking the (negative) derivative in $a$ after you include the case $a > b$ above.  You find it is:
$$
n(n-1)(1-a)a^{n-2}
$$
When $n=10$, this looks like the below.  The histogram is from $50k$ simulations.

The next plot is the density for $n$ up to 10.