Obter recurso do sistema dentro do arquivo Jar (getSystemResource)

Question: Desenvolvi um projecto no qual preciso de aceder a alguns ficheiros de configuração e algumas imagens. Dentro do projecto tenho uma pasta (resources) na qual tenho todos estes recursos de que preciso.
O problema é o seguinte:
Depois do projecto finalizado criei um jar e dentro do mesmo encontra-se todo o codigo e a pasta resouces.
Fui tentar correr o programa numa directoria onde so tenho duas coisas:
1 pasta (lib) onde tenho outros jar de que preciso
1 .jar com o meu projecto
executei no command prompt a seguinte linha:
java -cp myProject.jar;lib/*; project.entry.point.App
e obtive o seguinte erro

acho que o problema esta em descobrir a path de um ficheiro, estou a fazer:
ClassLoader.getSystemResource("resources/CREATE_DB.sql");
mas como pode ver ali na imagem no erro que da apos o nome do .jar esta o caracter '!' nao percebo o porquê
Alguma ideia de como resolver o problema?
Comment: Tente colocar a pasta `resources` no mesmo diretório que está o jar, e execute novamente e veja se o problema persiste.
Comment: Kyllopardiun obrigado pela resposta, sim antes de colocar a questão eu fiz isso e funcionou mas supostamente a pasta esta dentro do .jar devia de haver maneira de conseguir fazelo sem ter a pasta resouces na directoria corrente
Answer: Eu tive um problema similar e o neste caso recomendo que use this.getClass().getResourceAsStream("") para poder manipular sem problemas.
Exemplo
stack.Config.java:
package stack;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

public class Config {
    private String usuario;
    private String db;
    private String website;
    private String path;
    public void setConfigPorStream(boolean flag){
        try{
            InputStream is;
           if(flag){
                 // stack.res/conf.txt
                 is =  this.getClass().getResourceAsStream("res/conf.txt");
           }
           else{
                 //res/conf.txt
                 is = ClassLoader.getSystemResourceAsStream("res/conf.txt");
           }
            //O tamanho do arquivo provavelmente será o mesmo sempre
            // e por isso BufferedReader é desnecessário.
           byte[] b = new byte[1024];
            is.read(b);
            String config = new String(b,"UTF-8");
            this.db = parseConfig(config, "dbUrl");
            this.website = parseConfig(config, "website");
            this.usuario = parseConfig(config, "usuario");

        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public void setConfig_PastadoJar(boolean flag) {
        URL arquivo;
        if(flag)
            arquivo = ClassLoader.getSystemResource("res/conf.txt");
        else{
            arquivo = this.getClass().getResource("res/conf.txt");
        }
        FileInputStream fis  = null;
        try {
            fis = new FileInputStream(arquivo.getFile());
            byte[] b = new byte[1024];
            fis.read(b);
            String config = new String(b,"UTF-8");
            this.db = parseConfig(config, "dbUrl");
            this.website = parseConfig(config, "website");
            this.usuario = parseConfig(config, "usuario");
            } catch (Exception e) {
               e.printStackTrace();
            }
        }
        public String getUsuario(){
            return this.usuario;
        }
        public String getDB(){
            return this.db;
        }
        public String getWebsite(){
            return this.website;
        }
    public static String parseConfig(String linha,String campo){
        linha = linha.replaceAll("\"","");
        int indice = linha.indexOf(campo) + 3 + campo.length();
        int ultimo_char = linha.indexOf(",", indice)!=-1?linha.indexOf(",", indice):linha.indexOf("}", indice);
        return linha.substring(indice,ultimo_char);
    }
}

stack.StackOverflow
package stack;
public class StackOverflow{

    public static void main(String[] args) {
            Config conf = new Config();
            System.out.println("-----------------------\n\tPasta onde está o jar\n-----------------------\n");
            conf.setConfig_PastadoJar(true);
            printConfig(conf);
            System.out.println("");
            conf.setConfig_PastadoJar(false);
            printConfig(conf);
            System.out.println("-----------------------\n\tDentro do jar\n-----------------------\n");
            conf.setConfigPorStream(false);
            System.out.println("StackOverflow.jar\\!res\\conf.txt");
            printConfig(conf);
            System.out.println("");
            System.out.println("StackOverflow.jar\\!stack\\res\\conf.txt");
            conf.setConfigPorStream(true);
            printConfig(conf);
        }
        public static void printConfig(Config c){
            System.out.println("Usuario: " + c.getUsuario());
            System.out.println("DB: " + c.getDB());
            System.out.println("Website: " + c.getWebsite());
        }

}

res.conf.txt  && res.stack.conf.txt
{eg{usuario = "dbAdmin", dbUrl = "http://db.pt.stackoverflow.com", website = "pt.StackOverflow"}}

Note que neste exemplo não terá erros ao rodar em uma IDE (Netbeans/Eclipse) mas as duas primeiras configurações não rodar-se-ão diretamente se iniciar somente o Jar i.e.
java -jar StackOverflow.jar

Caso queira baixar o projeto o mesmo se encontra no GitHub


Let $A$ be a nonempty bounded subset of $\mathbb R$ and let $B$ be the set of all upper bounds for $A$. Prove that $\sup A=\inf B$

Question: Let $A$ be a nonempty bounded subset of $\mathbb R$ and let $B$ be the set of all upper bounds for $A$. Prove that $\sup A= \inf B$. Can someone please help me? I'm very confused as to what to do.
Comment: How do you define $\sup A$?
Answer: Well, by definition of supremum, $\sup A\in B$ and for all $x\in B$, $\sup A\leq x$. Then $\sup A=\min B=\inf B$.


Capture generated Drupal 7 html output into a variable

Question: Trying to hook into Drupal 7 from an external php file by using various variants of ...
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
ob_start();
menu_execute_active_handler();
$contents = ob_get_clean();
return $contents;

However, it seems D7 just spits out the HTML to the browser on the menu_execute_active_handler() call.
Any ideas how to get the html output into my variable?
Answer: Tracking the Drupal flow line by line and function by function reveals the culprit to be ob_flush in the drupal_page_footer function
Using the following instead of ob_flush would make the application a bit more friendly
$data = ob_get_contents();
ob_clean();
print $data;

Expanding on this,
Finally solved by adding a delivery callback to my module_menu function and handling things there to bypass the problem function.
/**
 * Implements hook_menu().
 */
function MODULE-NAME_menu()
{
    $items = array();
    $items['MODULE-NAME'] = array(
        'page callback'     =>  'MODULE-NAME_output',
        'access arguments'  =>  array('access content'),
        'delivery callback' =>  'MODULE-NAME_deliver_html_page',
        'type'              =>  MENU_CALLBACK
    );

    return $items;
}

/**
 * Page callback: Display MODULE-NAME HTML Output
 *
 * @see MODULE-NAME_menu()
 */
function MODULE-NAME_output()
{
    return 'Some Output HTML';
}

/**
 * Delivery callback: Render MODULE-NAME Page
 *
 * @see MODULE-NAME_menu()
 */
function MODULE-NAME_deliver_html_page($page_callback_result) {
    /* Adapted from "drupal_deliver_html_page" */
    // Menu status constants are integers; page content is a string or array.
    if (is_int($page_callback_result))
    {
        // Integers mean an error page is required!
        // Send to the default Drupal function and exit.
        // Note use of exit instead of drupal_exit (not needed here).
        drupal_deliver_html_page($page_callback_result);
        exit;
    }
    elseif (isset($page_callback_result))
    {
        /* Print anything besides a menu constant if not NULL or undefined. */
        // Send the correct charset HTTP header if code running
        // for this page request has not already set the content type header.
        if (is_null(drupal_get_http_header('Content-Type')))
        {
            drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
        }
        // Send appropriate HTTP-Header for browsers and search engines.
        global $language;
        drupal_add_http_header('Content-Language', $language->language);
        // Render page
        print drupal_render_page($page_callback_result);
    }
    /* Adapted from "drupal_page_footer" */
    // Perform end-of-request tasks.
    global $user;
    module_invoke_all('exit');
    // Commit the user session, if needed.
    drupal_session_commit();
    if (variable_get('cache', 0) && ($cache = drupal_page_set_cache()))
    {
        drupal_serve_page_from_cache($cache);
    }
    else
    {
        $data = ob_get_contents();
        ob_clean();
        print $data;
    }
    _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
    drupal_cache_system_paths();
    module_implements_write_cache();
    system_run_automated_cron();
}


How to find the subnet for a single IP?

Question: I have always used the subnet tools on the web when our datacenters provide us with new ip blocks for our machines. However, I recently ordered more IPs from our European DC and they apparently just hand you random single IPs instead of blocks, which has left me confused.
How can I get the subnet for these IPs?
220.127.116.11
184.108.40.206
126.96.36.199
22.214.171.124
Comment: i'd suggest opening a ticket with your provider they can just tell you the subnet mask to use... its probably 255.255.255.0 anyway
Answer: You can not. You can get the possible smallest one but without knowing more information you can not deduce which subnet you have because the "subnet" may be LARGER than the Class network.
Comment: What "Class" would that be?
Comment: The ones abandoned when CIDR was introdued that many still think of - like "class C network".
Answer: If they're assigning you random IPs, one of two things should be the case:
1) You already have some routing scheme arranged with them, and they can route a simple /32 to you.
2) You already have an interface in a subnet that includes that IP address. They are basically just giving you permission to take that additional IP address as well as the ones you already have.
If neither of these two things are the case, ask for clarification.

How to find the subnet for a single IP?


Finding an optimal wage

Question: Hiring a doctor costs $600$ dollars a day and hiring a nurse costs $200$ dollars a day. When d doctors and n nurses are hired, a clinic can serve $p=10d+nd+6n$ patients each day. Suppose a clinic budgets $9,000$ dollars a day for wages. What combination of nurses and doctors serves the greatest number of patients$?$
I'm not sure how to go about starting this problem.
Comment: Start by observing the equation $9000=600d+200n$. You now have a system of two equations and can maximize $p$.
Comment: Then solve for one variable in terms of another, plug in to the equation for $p$, take derivative, set = 0, and solve.
Answer: We have to pay $600d + 200n$ in salaries per day. This can at most be $9000$, we may assume it will be exactly $9000$ (we obviously want to spend as much as possible, since there isn't any penalty in hiring more staff as long as we can afford it). This can be used to find an expression for $n$ given $d$. Or, said differently, a formula that given how many doctors we have hired on a given day, tells us how many nurses we can afford.
Finally, since we now know what $n$ is given $d$, we can swap out all the $n$'s in $p = 10d + nd + 6n$ with that one expression. Then we get an expression for $p$ using only $d$. This can be maximized using differentiation. If you for some reason have the formula specifically tailored to finding maxima and minima of second-degree polynomials, you may of course use that instead.

Finding an optimal wage


Relabelling a permutation

Question: I'm trying to understand the proof of lemma 3.2 of this article by Keith Conrad on proofs of the simplicity of $A_n$. There is a step I don't follow.
When he says "Relabelling, we may write $\sigma=(1 2 \dots r) \pi$", I don't see why we could do that. Relabelling what?
As I tried to understand the statement, I thought of this: if $(i_1 \dots i_r)$ is a cycle appearing in $\sigma$, then we can conjugate $\sigma$ to $\sigma'=(1 \dots r) \pi$. If we show that $\sigma'$ coincides with $\sigma$ at some index, then we're fine. But why would it coincide, and where?
Comment: I updated that file (11 years later) to be a bit more descriptive in that sentence, but it is not as formal as Arturo's "formal explanation" below.
Answer: Two explanations:
Informal one. You are thinking of the elements of $A_n$ as acting on the set $\{x_1,x_2,\ldots,x_n\}$, by letting $\sigma$ map $x_i$ to $x_{\sigma(i)}$.
So say that $\sigma$ maps $x_3$ to $x_5$, and $x_5$ to $x_2$, and $x_2$ to $x_3$. Stick new labels on your elements, so that what you used to call "$x_3$" is now called $x_{1_{\mathrm{new}}}$, what you used to call $x_5$ is now called $x_{2_{\mathrm{new}}}$, and what you used to call $x_2$ is now called $x_{3_{\mathrm{new}}}$. Of course, you'll also need a new identity for $x_1$, say $x_{5_{\mathrm{new}}}$, since $5$ is no longer being used; and keep the other elements with their old names, so that $x_{i_{\mathrm{new}}} = x_i$ if $i\notin\{1,2,3,5\}$. Then $\sigma$ now acts on $\{x_{1_{\mathrm{new}}},x_{2_{\mathrm{new}}},\ldots,x_{n_{\mathrm{new}}}\}$ by looking at their "old" identities and acting as before.
But now $\sigma$ maps $x_{1_{\mathrm{new}}}\mapsto x_{2_{\mathrm{new}}}\mapsto x_{3_{\mathrm{new}}}\mapsto x_{1_{\mathrm{new}}}$, so if we write its cycle decomposition in terms of the "new" labels, we have that
$$\sigma = (1_{\mathrm{new}},2_{\mathrm{new}},3_{\mathrm{new}})\pi$$
for some $\pi$.
Formal one. Suppose the longest cycle of $\sigma$ is $(i_1,i_2,\ldots,i_r)$. Consider a permutation $\tau\in S_n$ with $1\mapsto i_1$, $2\mapsto i_2,\ldots,r\mapsto i_r$, and which acts in some (unspecified but irrelevant) way on the remaining elements of $\{1,\ldots,n\}$. Then consider the automorphism of $S_n$ given by conjugation by $\tau$, $\psi\mapsto \tau\psi\tau^{-1}$. You've probably seen already that if $\psi$ sends $k$ to $\ell$, then $\tau\psi\tau^{-1}$ sends $\tau(k)$ to $\tau(\ell)$. So we can look at $\tau A_n\tau^{-1}$ and $\tau\sigma\tau^{-1}$ instead of $A_n$ and $\sigma$ (they are isomorphic copies, after all, so we can just "translate back" to $A_n$ by using the inverse automorphism when needed).
But in $\tau A_n\tau^{-1}$, the longest cycle of $\tau\sigma\tau^{-1}$ is just $(\tau(i_1),\tau(i_2),\ldots,\tau(i_r)) = (1,2,\ldots,r)$. So, by switching to this isomorphic copy of $A_n$, we may assume that the longest cycle of $\sigma$ is in fact $(1,2,\ldots,r)$.
Comment: Outstanding, as usual. What an excellent answer, thank you, Arturo, your contributions to this site are of the utmost quality! Now I'm fully convinced. I had the informal idea as to what is 'relabelling', but I wasn't sure it was 'legal' to do that, so I started thinking about conjugation, but not in the correct way, which is your formal explanation and which completely satisfies my skepticism.

Relabelling a permutation


MySQL; get all cards & all decks associated for each cards in one request

Question: I want to be able to see each decks where a card is and display it as following.
A card can be in multiple decks. And there will be many cards/decks.
The server is in php.
|List of cards|   In decks        |
|-------------|-------------------|
|CardA        |DeckA, DeckC       |
|CardB        |DeckC, DeckF, DeckY|
|CardC        |                   |

The database as is:
CREATE TABLE `card` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(100) NOT NULL
);

CREATE TABLE `deck` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(100) NOT NULL
);
CREATE TABLE `deck_card` (
  `deck_id` INT NOT NULL ,
  `card_id` INT NOT NULL ,
  PRIMARY KEY (deck_id, card_id),
  FOREIGN KEY (card_id) REFERENCES card(id),
  FOREIGN KEY (deck_id) REFERENCES deck(id)
);

I want to avoid having to do a request for each card.
Is there a way to request all the cards and each associated deck in one request using MySQL?
Comment: Use join + group_concat
Comment: Your api call to your db can return any and everything you need it to. .... Do you have any code to show other than this data structure?
Answer: The next simple query can solve your problem:
SELECT
    `c`.`name` `card_name`,
    COALESCE(GROUP_CONCAT(`d`.`name`),'') `deck_names`
FROM `card` `c`
LEFT JOIN `deck_card` `dc` ON `c`.`id` = `dc`.`card_id`
LEFT JOIN `deck` `d` ON `d`.`id` = `dc`.`deck_id`
GROUP BY `c`.`name`
;

Result from SQLize.online
+===========+=============+
| card_name | deck_names  |
+===========+=============+
| CardA     | DeckA,DeckB |
+-----------+-------------+
| CardB     | DeckC,DeckE |
+-----------+-------------+
| CardC     |             |
+-----------+-------------+


Left-floated div place below another div

Question: I have two divs whereas (div 1) is floated left while (div 2) is floated right. I am creating a responsive layout where when the viewport changes, (div 1) will go under (div 2). I created a simple image via MS Paint for an easier illustration and also some code. Also, both contain dynamic content so their heights must not be fixed.
No javascript (if possible) just plain CSS. I only know how to put div 2 under div 1 but not the other way around.
Does anyone know how I could achieve this?

HTML:

   //dynamic content

  //dynamic content

HTML is auto generated so in the markup, div1 originally comes first than div2. Not advisable to change the order (place div2 above div1) since many pages use the same layout. See code above
Comment: SEE HERE PLEASE: http://stackoverflow.com/questions/9485493/css-floats-change-order-on-mobile-layout/9485567#9485567
Comment: Wait, so you want the thing that semantically comes first in the layout to be presented second visually?
Comment: @Elmer which  is the sidebar? Since the left and right floats will not be affected by order in your HTML, you can simply put  HTML in front of  (or vice versa) to achieve the desired effect
Comment: put `float:left` on both, and then move div2 above div1 :) I doubt this is possible without moving the div2 up
Comment: @Doorknob Hm. in that case, how do I put div 2 on top? :) What's important is that div1 must always be underneath
Comment: why doesn't div1 come after div2 in the document?
Comment: use media queries for smaller screens and remove the floats
Comment: Select the code in the HTML file, cut, and paste above div1. :)
Comment: @LegoStormtroopr Yup, because div1 is a sidebar and must it below div2 which is the main content.
Comment: @SetSailMedia I already checked that but the HTML markup is autogenerated. sidebar comes before the content.
Comment: You can combine the answer in the link I gave with media queries as @box86rowh suggests, and should solve your issue :)
Comment: @JoshC The HTML markup is auto generated. sidebar comes before content.
Comment: http://stackoverflow.com/questions/11962837/how-do-i-dynamically-adjust-css-stylesheet-based-on-browser-width This could also help.
Comment: @SetSailMedia div1 is the sidebar :) and the html is created by a joomla template.
Comment: @JoshC Sidebar(div1) comes before the content div (div2). I cannot change the order because it is auto generated via php. I am using media queries that is why I am trying to achieve this only using CSS :)
Comment: @KeithNicholas Some pages use the same PHP layout. Just wondering if this can be done with CSS only :)
Comment: wild suggestion, considering i don't know what the divs contain etc. what happens if you float:right both the divs
Comment: @om_deshpande div1 will go above div2. i am trying to put div2 above div1 without changing the html
Answer: There is my proposition. Using media queries, find the largest width that you want your divto stay side by side.
In your html, place your div like this (the right one before):

    div 2

    div 1

The css used to display those div should look like this:
.div1 {
    float: left;
    width: 25%;
}
.div2 {
    float: right;
    width: 75%;
}

Finally, to display your left div below the right one, your should add in you css something like this:
@media all and (max-width: 480px) {
    .div1, .div2 {
        float: none;
        display: block;
    }
}

Here is a jsfiddle that demonstrate this coding. You only have to resize your browser to see your left div going right under your right one.
Comment: The HTML must not be rearranged :( Other pages use the same order. Div1 must always come before Div2 in the HTML. HTML order must not be changed. Only the CSS.
Comment: Even if the html is rearranged and that div2 is written before div1, div1 will always be at the left of div2. See the jsfiddle.
Answer: I would use a media query to change the CSS styles applied to each of those divs when the viewport is sized to where you want the change to occur. Then float div 1 to the right, float div 2 to the left and give div 2 a big enough right margin that it pushes div 1 down to the next row.


How does DRF turn off CSRF-token check for JWT-based authentication?

Question: I'm using Django Rest Framework with JWT as authentication mechanism. As far as I've understood, using JWT authentication makes the CSRF-token check not necessary as long as the token is not stored in a cookie.
However, checking the django-rest-framework-jwt code and the Django CsrfViewMiddleware I don't understand which part of the code turns off the CSRF-token check for JWT-based authentication.
Does somebody know and can point to the relevant parts of the code?
Comment: did you find answer if yes please help me i also facing same
Answer: CSRF exemption happens in APIView.as_view provided by Django REST Framework.
Comment: Note: As the comment indicates, the CSRF Django automatic validation is deactivated for all views and checked explicitly only for `rest_framework.authentication.SessionAuthentication`: https://github.com/encode/django-rest-framework/blob/master/rest_framework/authentication.py#L129


Inappbrowser usando Phonegap build

Question: tenho uma aplicação que roda no mobile compilado no PG build Cli 5.2.0
nesse app tenho alguns links externos pra abrir. implementei o inappbrowser para poder fechar o navegador aberto e retornar para o app. no entanto são varios links diferentes. Tem alguma forma onde eu posso fazer uma função sem o link especifico e so especificar no botão quando eu for fazer a chamada da função? pra q eu não tenha que fazer uma função pra cada link diferente.
Ex: que estou usando.

o botão fica no corpo do app e precisa ter varios botões desse com links diferentes...

<button onclick="face()">Pagina do face</button>

Comment: Podes colocar o link aqui `onclick="face(link...)"` e depois fazer dentro da função `... ction face(link) {window.open(link, ...` será isso que queres? Repara que o teu `` está em falta.
Comment: Vlws irmão acredito que isso vai resolver meu problema, depois do link saiu com ... ali no windows open, o que vai depois?
Comment: Sergio pode ajudar onde eu estou errando?...

No corpo...

Ofertastes
Comment: Obrigado irmao deu certo achei o erro... estava usando 'link' dentro de windows.open... e nao precisa de '   '
Answer: Podes usar a mesma função mas passares-lhe como argumento o link que queres abrir.
Assim no HTML podes ter:

<button onclick="face('http://um.link.com')">Pagina do Um</button>

<button onclick="face('http://outro.link.com')">Pagina do Outro</button>

e a função ficaria assim:
function face(meuLink) {
    window.open(meuLink, '_blank', 'location=yes');
}

Eu chamei meuLink à variável, mas podes dar o nome que quiseres.

Inappbrowser usando Phonegap build


Drupal Commerce: Create advanced add to cart form block in views

Question: With Drupal Commerce product variations, certain values will update without a page refresh based on an attribute selection. For example, changing a color attribute may update the product image.
I want to the display the add to cart form in a views block using the method described in the following video https://drupalcommerce.org/questions/10801/display-add-cart-separate-block . At the same time I would also like to include other product fields in the block, such as price.
I am finding that the block is static and does not update based on an attribute selection. And I have tried enabling Ajax for the block without success.
Is is possible to create a dynamically updating views block to replicate some of the functionality of a commerce product display?
Comment: Does you add to cart form work when you don't use the way described in the thread you link to?
Comment: @PontusNilsson The cart from works and changes any affected values is the product display. But it does not change any values within the block
Answer: Ajax on the block only works for the views pager and the table sorting. You have to simulate that behaviour by triggering the ajax call when an attribute is selected.
Alternatively try with Ajax Block, Block Refresh, or Authcache Blocks, and see how they trigger the Ajax load on page load, and do the same on attribute selection.


What are topoi?

Question: I have been hearing a lot about the concept of "topos". I asked a friend of mine in the know and he said that topoi are a generalization of sheaves on a topological space. In particular, topoi were usefull when an actual topology was not available. Can anyone elaborate on this or make this idea more clear?
Comment: have you googled for "what is a topos?"?
Comment: A naive comment, but maybe still useful, consists in saying that a topos is a category that looks like the category Sets of sets and maps between them. A Grothendieck topos is a category equivalent to a category of sheaves on a site. There are also the so-called elementary topoi. Every Grothendieck topos is an elementary topos but there are some elementary topoi that are not Grothendieck ones.
Answer: Topoi can be looked at from many points of view.

Topoi can be seen as categories of sheaves on (generalized) spaces. Indeed, the premier example of a (Grothendieck) topos is the category $\mathrm{Sh}(X)$ of set-valued sheaves on a topological space $X$. Instead of spaces, also sites work.
Topoi can be seen as generalized spaces. For instance we have a functor from the category of topological spaces to the category of topoi, namely the functor $X \mapsto \mathrm{Sh}(X)$. This functor is fully faithful if we restrict to sober topological spaces. (Soberness is a very weak separation axiom. Every Hausdorff space is sober and so is every scheme from algebraic geometry.)
Many geometrical concepts generalize to topoi, for instance there are: point of a topos, open and closed subtopos, connected topos, continuous map between topoi, coverings of topoi, ...
Topoi can be seen as alternate mathematical universes. The special topos $\mathrm{Set}$, the category of sets and maps, is the usual universe. Any topos admits an "internal language" which can be used for working inside of a topos as if it consisted of plain sets. Any theorem which admits an intuitionistic proof (a proof not using the law of excluded middle or axiom of choice) is valid in any topos.
For instance the statement "For any short exact sequence $0 \to M' \to M \to M'' \to 0$ of modules, the module $M$ is finitely generated if $M'$ and $M''$ are" is such a theorem and therefore also holds in the topos of sheaves on a ringed space. In this way it automatically yields the statement "For any short exact sequence $0 \to \mathcal{F}' \to \mathcal{F} \to \mathcal{F''} \to 0$ of sheaves of $\mathcal{O}_X$-modules, the sheaf $\mathcal{F}$ is of finite type if $\mathcal{F}'$ and $\mathcal{F}''$ are".
In the internal language of some topoi, exotic statements such as "any map $\mathbb{R} \to \mathbb{R}$ is smooth" or "there exists a real number $\varepsilon$ such that $\varepsilon^2 = 0$ but $\varepsilon \neq 0$" hold.  This is useful for synthetic differential geometry.
Topoi can be seen as embodiments of logical theories: For any (so-called "geometric") theory $\mathbb{T}$ there is a classifying topos $\mathrm{Set}[\mathbb{T}]$ whose points are precisely the models of $\mathbb{T}$ in the category of sets, and conversely any (Grothendieck) topos is the classifying topos of some theory. The classifying topoi of two theories are equivalent if and only if the theories are Morita-equivalent.

I learned this from the nLab entry on topoi. The main examples for topoi are:

The category $\mathrm{Set}$ of sets and maps.
The category $\mathrm{Sh}(X)$ of set-valued sheaves on any site. Grothendieck conceived topoi because of this example – he needed it for etalé cohomology. The "etalé topology" on a scheme is not an honest topology, but a Grothendieck site.
The effective topos associated to any model of computation. In the internal language of such a topos, the statement "for any natural number $n$, there is a prime number $p > n$" holds if and only of there is a program in the given model of computation which computes, given any number $n$, a prime number $p > n$. The statement "any map $\mathbb{N} \to \mathbb{N}$ whatsoever is given by a Turing machine" is true in many of those topoi.

Topoi can for instance be used

in algebraic geometry to work with generalized topologies like the etalé topology,
in logic to construct interesting models of theories,
in computer science to compare models of computation,
as tools to build bridges between different subjects of mathematics.

Very fine resources for learning about topoi include:

Tom Leinster's informal introduction to topos theory. Start here!
The textbook Sheaves in Geometry and Logic by Saunders Mac Lane and Ieke Moerdijk.
The reference Sketches of an Elephant: A Topos Theory Compendium by Peter Johnstone.

If you are in a hurry, then enjoy Luc Illusie's two-page note in the AMS series "What is …?".

What are topoi?


Solr Search - Adding taxonomy to Search results

Question: I'm using the 'Solr Search' module ( not Apache solr search ) .
What I need to do is return results that have a taxonomy term relationship.
In my search indexes 'fields'  I have the taxonomy I want 'Keywords'  selected. The type for this is 'Taxonomy term'  .  I have also added 'Keywords » Name' through 'Add Related Fields'  .  This is type 'Fulltext'  and after reindexing and saving this field appears in views/search/page / search 'full text' / Searched fields.
However when I search for a keyword through the exposed filter the results are not being returned. They can however been seen in Facets.
Any idea what I might be missing.
Comment: When you said Solr Search you mean search api ? Did you re-index your content ? Usually when I'm using Search api module and I make changes I need to re-index my content in order to see the changes.
Comment: Hi. Yeah I had been re indexing. It might have been something obvious tho as I rebuilt the search view and this worked fine.
Comment: Common mistakes it happen to me all the time.
Answer: I rebuilt the view and this time it worked fine.


Integrate $\int \frac{\arccos\frac{x}{2}}{\sqrt{(4-x^2)}}$

Question: I need suggestions on how to integrate this integral:
$$\int \frac{\arccos\frac{x}{2}}{\sqrt{(4-x^2)}}dx$$
I tried putting $\arccos$ or $\sqrt{4-x^2}$ into the differential, but that gave me nothing. Any ideas? Thanks.
Comment: After a little massage, this is basically $\int f'f$, for an appropriate $f$.
Answer: HINT:
Let $\arccos\dfrac x2= y\implies dy=-\dfrac1{\sqrt{1-(x/2)^2}}\dfrac{dx}2=-\dfrac{dx}{\sqrt{4-x^2}}$


How can I remove the empty line break at the bottom of my textarea after appending text using jQuery?

Question: This is could be a very basic question, as what I'm wishing for here doesn't seem that crazy -- I looked throughly for some existing answer or better solution to this already, so I apologize in advance if this is any form of duplicate!
My question regards append()ing data to an existing textarea element:
jSFiddle:
https://jsfiddle.net/natureminded/7w3rmggp/
My HTML:
<textarea id='chat'></textarea>

My JS/jQuery:
//note: 'chatMsg' data is provided back from the server
$('#chat').append(chatMsg.name+': '+chatMsg.message+'
');
$('#chat').scrollTop($('#chat')[0].scrollHeight); // focuses on bottom of textarea

My desired output: New lines append to the textarea, each new message as a new line. No extra lines at the bottom of the texarea.
What I'm experiencing: Indeed, new lines append to the textarea, each as a new line (due to the use of the
 HTML carriage return). However, because of this new line character being at the end of my append() string, a blank line is added beneath my last message (see: https://biturl.io/VCjaj5 for a screenshot). Adding the carriage return to the front of the string would fix the extra line break at the bottom, but would create a line break at the very top when the first message is sent.
I understand another way to approach this is by grabbing the .val() of $('#chat'), adding my new data as a new line, such as:
var oldChat = $('#chat').val();
var newChat = oldChat + '
' + chatMsg.name + ': ' + chatMsg.message;
$('#chat').val(newChat);

However, when I try this approach, hoping to add the new message as a new line beneath the oldChat, the HTMl carriage characters do not display and instead show as text (see: https://biturl.io/VCjmZ3). I also tried using the \n character but this actually killed my javascript prompt (not shown) and my chat broke.
Is there some better way to add new lines to my chat while not ending up with an extra white space at the bottom?
Note: Another possible solution I thought of was to try and somehow use regex to grab the last line and remove it, but I thought I would ask here if there was a simpler way to do this, or if I'm being too picky wanting my textarea to append text nice and clean (no extra line breaks).
Comment: You could simply use `.trim()` when you retrieve the value. This will remove all whitespace at the beginning and end, including newlines.
Comment: Build a jsfiddle or a stack snippet
Comment: @Barmer I did try and use the .trim() but the carriage return character doesn't seem to be working properly in the second way I outlined...I'm not exactly sure why, but thank you for putting .trim() under my radar!
Answer: You could have the newLine BEFORE instead of after, and in order to make sure there's no new line above the very first line, check if the textarea is empty.
so (pesudo code here but hopefully you get the idea)
string = chatmessage
// Prepend newline to string if the textarea already contains content
if textarea.value.length !== 0
  string = '
' + string

textarea.value = string

Answer: Try this:
var strt = $('#chat').text().replace(/[\s\r\n\t]/g,"").length == 0 ? "" : "&#10";

$('#chat').append(strt + chatMsg.name+': '+chatMsg.message);

scenario: detect if #chat has messages append break line + message if #chat hasn't append only message.
Comment: I appreciate your response and how clean the code was! I tried this method but unfortunately the carriage return showing up in the text: https://biturl.io/VCaGh5


Proof by induction; inequality $1\cdot3+2\cdot4+3\cdot5+\dots+n(n+2) \ge \frac{n^3+5n}3$

Question: Ok so I'm kind of struggling with this:
The question is:
"Use mathematical induction to prove that
1*3 + 2*4 + 3*5 + ··· + n(n + 2) ≥ (1/3)(n^3 + 5n) for n≥1"
Okay, so P(1) is true as 1(1+2)=3 and (1/3)(1^3 + 5)=2
Assuming P(k) is true for k≥1 gives:
1*3 + 2*4 + 3*5 + ... + k(k+2) ≥ (1/3)(k^3 + 5k)
And we want to show that P(k+1) is true, that is;
1*3 + 2*4 + 3*5 + ... + (k+1)(k+3) ≥ (1/3)((k+1)^3 + 5(k+1)) (inequality 1)
This is where I'm not sure if I'm thinking along the right lines or not. Surely, by P(k) and the rules for inequalities we get:
(1*3 + 2*4 + 3*5 + ... + k(k+2)) + (k+1)(k+3) ≥ (1/3)(k^3 + 5k) + (k+1)(k+3) (inequality 2)
but the right hand side in this inequality does not equal (1/3)((k+1)^3 + 5(k+1)) which is what I am trying to show. There's obviously a flaw in my thinking somewhere so any help would be greatly appreciated.
Thanks
Edit: As far as I understand it the right hand side of inequality 1 should equal the right hand side of inequality 2 but this isn't the case when expanded
Comment: because they are not equal. you should show that one is greater than the other
Comment: If your know $x \geq y$ and you find $y \geq z$, then you've established $x \geq z$. You'll find the expansion of the right-hand side of $(2)$ is greater than the right-hand side of $(1)$. So you simply need to show that.
Comment: I don't understand why they wouldn't be equal? I thought that if x>y then (x+a)>(y+a) which is how inequality 2 comes about
Answer: Assume that statement is true for number unto k. We need to show that it is true for k+1.
$$
1*3+...+k(k+2)+(k+1)(k+3)\geq \frac{k^3+5k}{3}+(k+1)(k+3)=\frac{k^3+3k^2+17k+9}{3}\geq\frac{k^3+3k^2+8k+6}{3}=\frac{(k+1)^3+5(k+1)}{3}
$$
for last inequality expand both sides and see that
$$
\frac{(k+1)^3+5(k+1)}{3}=\frac{k^3+3k^2+8k+6}{3}
$$
and
$$
\frac{k^3+5k}{3}+(k+1)(k+3)=\frac{k^3+3k^2+17k+9}{3}
$$
put it in original inequation and get the result
Comment: I'm not sure how this proves the result? I know the equations are different but surely we're trying to show that the last inequality is the same as the RHS of P(k+1)? I'm confused lol
Comment: Just forget the middle part and see far LHS $\geq$ far RHS. Do you see the statement P(k+1)?
Answer: Here's the meat of the argument:
\begin{align}
1\cdot3+2\cdot 4+\cdots+(k+1)(k+3)&\geq \frac{k^3+5k}{3}+(k+1)(k+3)\tag{ind. hyp.}\\[1em]
  &= \frac{k^3+5k+3(k^2+4k+3)}{3}\tag{simplify}\\[1em]
  &= \frac{k^3+3k^2+17k+9}{3}\tag{simplify}\\[1em]
  &\geq \frac{k^3+3k^2+8k+6}{3}\tag{since $k\geq 1$}\\[1em]
  &= \frac{(k+1)^3+5(k+1)}{3}.
\end{align}
The last equality is what you want. The key is in realizing that since $k\geq 1$ you can obtain the desired expression on the right-hand side to show that
$$
1\cdot3+2\cdot 4+\cdots+(k+1)(k+3) \geq\frac{(k+1)^3+5(k+1)}{3}.
$$
Comment: ahhh I see now lol. Thanks for the explanation!
Comment: @Michael You're welcome 8^)


Can a .gitignore file in a subdirectory of a repo ignore items further up the directory tree?

Question: I have a respository that contains 2 different apps. I used to manage them both at the same time, so having to ignore one or the other was never a problem, but now i have to give one of the subsites to another person, and we are both are going to be working on the same repository at the same time.
Both apps are made with Angular, so they both already have a .gitignore ready for the node_modules folder.
Here are the paths for both .gitignore files:

Code\Ventas\APP\Code\Client
Code\Productor\APP\Code\Client

What i want to ask is: Is it possible to modify the .gitignore from the "Ventas" path in order to ignore everything from the "Productor" path? In that way me and the other person could treat both subsites as if they were hosted in different repositories, so 2 people can work on the same repository.
Answer: No, a .gitignore file can only ignore files in the same directory or below it.
Even if it could, it wouldn't work as you imagine it, because as each of you work on your two separate apps, you will be making commits to the same repo. Each of you would would have to pull and merged the commits of the other unless you are working on separate branches (see below). I'm not sure if the merges would even work right with such a .gitignore
Below are three alternative solutions for you, from easiest to hardest. Easiest does not mean best.
use your IDE's ability to ignore directories
If you are using an IDE, you can configure your IDE project to ignore the other directory. It will still exist in your git worktree, but it will be invisible in the IDE.
You still have to be careful not to make and commit changes to the other directory, but it should be easy to avoid. You will still have to deal with pulling and merging the other persons commits, though those merges should be trivial.
make separate branches in the repo for each app

Create two new branches: Ventas and Productor. Keep the current main branch if the two apps have shared code.

In each of the branches delete the unwanted directory.

You can now work independently.

BUT it's not so pretty if you make changes to the shared code. You will have to patch the shared main branch with your changes to the shared code. There are many ways to do that, but it ain't trivial.

So the right way to do this is...
break up the repo
The fact that you want to .gitignore a whole directory branch of the repo indicates that you should split the repo. If there is shared code, you would split the repo into three repos and each of you would use git-submodule or git-subtree to incorporate the shared repo into your individual app repos.


Use Redis for Drupal sessions

Question: I've been looking online for a while and I haven't seen anything on setting up Drupal to use Redis for session handling. I've found tutorials and blogs about settings Redis up as a replacement for Memcached for caching.
Anyone know how to do this? I was hopping there was something in the $conf variable in the settings.php file that would allow me to override where sessions are stored and retrieved.
Thanks for any help in advance,FatGuyLaughing
Answer: a quick google search: http://lmgtfy.com/?q=drupal+redis+sessions
and the 2nd result talks about redis session handling:
https://www.drupal.org/node/2250195
from that issue thread i recommend looking Session Proxy. This allows you to override the default session handler by Drupal -- which is explained in the above issue:

This is because Drupal will override your session handler and use its
  own, it goes straight to the database. I'd recomend that you try using
  this module: https://drupal.org/project/session_proxy

Session Proxy provides the following, I believe your attempting #2:

ships three different session managing implementations:

Database session handling: core default, ported to the object oriented
  API. It comes with an additional SQL query done more than core
  session.inc default implementation due to the API strong
  encapsulation.
Native PHP session handling: by selecting this session
  management mode, you explicitely remove any core session management,
  and let PHP manage it. This can be useful if you intend to use
  low-level PHP extensions, such as Memcache or PhpRedis to handle
  session in PHP low-level layer instead of core. This allow to use any
  PHP native session storage to work gracefully: some of them are high
  performance.
Cache based storage engine: Using the same session
  handling than core, but deporting raw session storage into a cache
  backend instance. You can use any already-functionning cache backend
  to store sessions. Sessions will use their own bin, and won't be
  cleared at cache clear all time.

Again from the linked issue after installing session proxy you likely need to configure your php.ini to something like:
<code>session.save_handler = redis
session.save_path = "tcp://localhost:6379"
</code>
Comment: Sorry about that, I already googled that phrase and apparently in the mist of looking through all the links I somehow skipped the 2nd one.

Thanks for pointing that back out to me, it is greatly appreciated.

Use Redis for Drupal sessions


Asymptotic Normality of MLE when data is modelled with covariates

Question: Say I have data vector $X_1,\ldots,X_n$ which I want to model with some parametric distribution function $f(X_i;\theta,Z_i)$ and covariates $Z_i$. In this case, how can I prove the asymptotic normality of the maximum likelihood $\hat{\theta}$?
Many proofs of MLE's asymptotic normality focus on the situation where $X_1,\ldots,X_n$ are i.i.d. (e.g., Asymptotic normal-behaviour of the MLE, question about proof.). Let $S_i(\theta)=\frac{\partial}{\partial \theta} \ln f(x_i,\theta)$, $S'_i(\theta)=\frac{\partial^2}{(\partial \theta)^2} \ln f(x_i,\theta)$,
$S_n(\theta)=\sum_{i=1}^n S_i(\theta)$ and $S'_n(\theta)=\sum_{i=1}^n S'_i(\theta)$. When $X_i$'s are i.i.d., the proof roughly takes the following steps:
(1) MLE is consistent $\hat{\theta}_n \rightarrow \theta$ where $\theta$ is the true value. The proof (e.g., http://ocw.mit.edu/courses/mathematics/18-443-statistics-for-applications-fall-2006/lecture-notes/lecture3.pdf) often uses LLN and $\ln f(X_i;\theta)$ needs to be i.i.d.
(2) $\sqrt{n}(\hat{\theta}_n-\theta) \approx \frac{\frac{1}{\sqrt{n}}S_n(\theta)}{\frac{1}{n}S'_n(\theta)}$. The approximation holds for large $n$ because of (1)
(3) The numerator converges in distribution to
$$
N(0,\operatorname{Var}(S_i(\theta))) \tag{$*$}
$$ by CLT.
(4) The denominator converges in probability to $E(S'_i(\theta))$ by LLN.
(5)$E(S'_i(\theta))=\operatorname{Var}(S_i(\theta))=I_1(\theta)$
(6) By Slutsky theorem and (2),(3),(4),(5), and letting Z is from $(*)$:
$$\sqrt{n}(\hat{\theta}_n-\theta) \rightarrow E(S'_i(\theta))^{-1} Z \sim N(0,E(S'_i(\theta))^{-1}
\operatorname{Var}(S_i(\theta))
E(S'_i(\theta))^{-1})
=N(0,I_1(\theta)^{-1}).$$
However when the data is modelled with covariates, the data is no longer identically distributed. Therefore, the LLN and CLT used in (1), (3), (4) do not hold. Can anyone explain how to prove the asymptotic normality of MLE in this circumstance?
Answer: I guess, one way to convince myself for the asymptotic normality of MLE when $X_1,\cdots, X_N$ are independent but not identical is to use roughly the same arguments as i.i.d. scenario except the following two changes:
[Change 1] The classical i.i.d. CLT is replaced with Lyapunov CLT (http://en.wikipedia.org/wiki/Central_limit_theorem#cite_ref-6) which does not require identical observations (but independent is required). It states that under some conditions, if $Z_i \overset{ind}{\sim} (\mu_i,\sigma^2_i)$ then:
$$
\frac{1}{(\sum_{i=1}^{n}Var(Z_i))^{1/2}}\sum_{i=1}^{n} (Z_i-\mu_i) \overset{d}{\rightarrow} N(0,1)
$$
[Change 2]
Let $Z_i \overset{ind}{\sim} (\mu_i,\sigma^2_i)$ and $c_i,i=1,2,\cdots$ be the sequence of constants.
Instead of using the regular SLLN, use arguments similar to WLLN with a condition that $\frac{\sum_{i=1}^n \sigma_i^2}{ (\sum_{i=1}^n c_i)^2}
\rightarrow 0 $ as $ n\rightarrow \infty$.
By Chebychev's inequality for all $\epsilon$:
$$
Pr(|\frac{\sum_{i=1}^n Z_i}{\sum_{i=1}^n c_i}-\frac{\sum_{i=1}^n\mu_i}{\sum_{i=1}^n c_i}|\ge \epsilon)
\le
\frac{Var(\frac{\sum_{i=1}^n Z_i}{\sum_{i=1}^n c_i}-\frac{\sum_{i=1}^n\mu_i}{\sum_{i=1}^n c_i})}{\epsilon^2}
=\frac{Var(\sum_{i=1}^n Z_i)}{(\sum_{i=1}^n c_i)^2\epsilon^2}=\frac{\sum_{i=1}^n \sigma_i^2}{  (\sum_{i=1}^n c_i)^2\epsilon^2}
$$
So if the condition is satisfied, then we have WLLN for non-identical scenario for the sequence of random variables $Z_1,Z_2,\cdots$. The LLN used in Step (1) and (4) of the proof for i.i.d. case above is replaced with this assuming the condition is satisfied.
In summary, we can (roughly) show the asymptotic normality of MLE when the observations are not identically distributed taking the following steps:
(1) $\hat{\theta}\rightarrow \theta$ in probability under the condition discussed in [Change 2].
(2) The following approximation holds for large $n$ because of (1):
$$
[\sum_{i=1}^n Var(S_i(\theta))]^{1/2}
(\hat{\theta}-\theta)
\approx-
\frac{
\frac{1}{[\sum_{i=1}^n Var(S_i(\theta))]^{1/2}} S_n(\theta)
}{
\frac{1}{[\sum_{i=1}^n Var(S_i(\theta))]} S_n'(\theta)
}
=-
\frac{
\frac{1}{[\sum_{i=1}^n Var(S_i(\theta))]^{1/2}} \sum_{i=1}^n S_i(\theta)
}{
\frac{1}{[\sum_{i=1}^n Var(S_i(\theta))]} \sum_{i=1}^n S'_i(\theta)
}
$$
(3) The numerator converses to $N(0,1)$ by Lyapunov CLT [Change 1].
(4) By LLN of [Change 2], for large $n$ the denominator is approximately $\frac{1}{\sum_{i=1}^n Var(S_i(\theta))} \sum_{i=1}^n E(S'_i(\theta))$
(5)
$
Var(S_i(\theta)) = E(S'_i(\theta))= I_i(\theta)
$
for all $i$.
(6) By Slutsky theorem and (2),(3),(4),(5), for large $n$,
$$
[\sum_{i=1}^n Var(S_i(\theta))]^{1/2}
(\hat{\theta}-\theta)\approx
N(0,[\frac{ \sum_{i=1}^n E(S'_i(\theta))   }{\sum_{i=1}^n Var(S_i(\theta))} ]^{-2})
$$
Therefore:
$$
\hat{\theta}\approx
N(0,\frac{\sum_{i=1}^n Var(S_i(\theta))}{ [\sum_{i=1}^n E(S'_i(\theta))]^2 } )
=
N(0,\frac{1}{ \sum_{i=1}^n I_i(\theta) } )
$$
Answer: You can do this with central limit theorems for the non iid case. For example, check out "Estimation, inference, and specification analysis" book by halbert white. However easy way is to simply assume covariate distribution specifies a sequence of iid covariate patterns and this covariate distribution is not functionally dependent on theta


Why are pivot columns the basis of A?

Question: Why is it that when we determine the pivot columns of an m x n matrix $A$, the pivot columns form a basis for the $Range(A)$? I understand that the pivot columns are linearly independent (the reason why we chose them as the pivot columns), but how do we know that they also span the range of $A$?
Also, why is that we're choosing the columns of $A$ to be the vectors that form a basis for $Range(A)$ rather than the columns of $U = rref(A)$?
Comment: Basically a duplicate of https://math.stackexchange.com/q/2521737/265466.
Comment: @Jonathan Wang  If you are ok, you can set as solved. Thanks!
Answer: The pivot columns form a basis for the $Range(A)$ since they are linearly independent.
We're choosing the columns of $A$ to be the vectors that form a basis for $Range(A)$ rather than the columns of $U = rref(A)$ because $U$ is generally obtained by row operations which modify the column space.
Comment: Aren't the requirements for a basis:
1) Linearly independent vectors
2) Span the given subspace

How do we know that the pivot columns span the subspace as well (in this case, the subspace is Range(A). I get the part on how they're linearly independent.
Comment: Column of A span always a certain subspace with dimension n, to span that subspace you require numbers n of columns linearly independent.
Answer: With regards to showing that the "pivot columns" span the range of $A$:
Can you show that the non-pivot columns can be written as linear combinations of the pivot columns?

Why are pivot columns the basis of A?


Mongoid not persisting associations

Question: Consider the following:
class Parent
  include Mongoid::Document
  field:name
  references_one :child

  before_create :initialize_child

  protected

  def initialize_child
    self.child = Child.create
  end

end

class Child
  include Mongoid::Document
  field:name
  referenced_in :parent
end

In a console, i get the following weird behavior:
> p = Parent.create
 => #<Parent _id: 4d811748fc15ea355d00000b, name: nil>
> p.child
 => #<Child _id: 4d811748fc15ea355d00000c, name: nil, parent_id: BSON::ObjectId('4d811748fc15ea355d00000b')>

All good so far.  Now when I try to fetch the parent, and then find the child -- no luck ...
> p = Parent.last
 => #<Parent _id: 4d811748fc15ea355d00000b, name: nil>
> p.child
 => nil

This happens for me with both mongoid rc6 and rc7
Am I doing something wrong (I am new to mongoid) or this a bug?  Any work arounds?
Thanks!!
Jonathan
Answer: Since the child isn't embedded, it won't auto-save it on its own
Try
class Parent
  include Mongoid::Document
  field:name
  references_one :child, autosave: true

  before_create :initialize_child

  protected
  def initialize_child
    self.child ||= Child.new
  end
end

Also -- you may be expected the Child to be embedded in the Parent document. If so, you'll want to switch to "embedded_in"
Comment: Boom!  I love stackoverflow -- thanks man.  i didn't know about that autosave mode.

Mongoid not persisting associations


propriedade window.onload interfere no carregamento de diversos scripts?

Question: A propriedade
window.onload () = () => {
  //Executa algo
}

Só pode ser em um script? Vou dar um exemplo para o melhor entendimento.
Se eu tenho 3 scripts chamados:
mail.js
teste.js
algo.js
e os três (separadamente) eu coloco:
mail.js
window.onload () = () => {
  //Função de mail.js
  alert("Teste 1");
}

teste.js
window.onload () = () => {
  //Função de teste.js
  alert("Teste 2");
}

algo.js
window.onload () = () => {
  //Função de algo.js
  alert("Teste 3");
}

na hora de eu carregar meu html e colocar:
<!Doctype HTML>


If $G=G_1\times\dots\times G_n$ for abelian $G_i$, then ${\rm Aut}(G)$ is isomorphic to a specific general linear group.

Question: This is Exercise 1.5.10 of Robinson's, "A Course in the Theory of Groups (Second Edition)". According to Approach0, it is new to MSE.
The Details:
On page 11, ibid., the set product of subsets $X,Y$ of a group is defined as
$$XY=\{xy\mid x\in X, y\in Y\}.$$
On page 17, ibid., for groups $G,H$, the definition of ${\rm Hom}(G, H)$ is given as the set of all homomorphisms from $G$ to $H$.
The definition of a direct product on pages 20 to 21, ibid., is a little more involved.

Let $\{G_\lambda\mid \lambda\in\Lambda\}$ be a given set of groups. The cartesian (or unrestricted direct) product,
$$C=\underset{\lambda\in\Lambda}{{\rm Cr}}\, G_\lambda,$$
is the group whose underlying set is the set product of the $G_\lambda$s [. . .] and whose group operation is multiplication of components: thus
$$(g_\lambda)(h_\lambda)=(g_\lambda h_\lambda),$$
$g_\lambda, h_\lambda\in G_\lambda$. [. . .]
The subset of all $(g_\lambda)$ such that $g_\lambda=1_\lambda$ for almost all $\lambda$ [. . .] is called the external direct product,
$$D=\underset{\lambda\in\Lambda}{{\rm Dr}}\, G_\lambda,$$
[. . .] In case $\Lambda=\{\lambda_1,\dots,\lambda_n\}$, a finite set, we write
$$D=G_{\lambda_1}\times\dots\times G_{\lambda_n}.$$
Of course $C=D$ in this case.

On page 26, ibid., we have that

The set of all automorphisms of [a group] $G$ is denoted by
$${\rm Aut}(G).$$

It is a group under function composition.
The Question:
This is on page 30, ibid.

Let $G=G_1\times\dots\times G_n$ where the $G_i$ are abelian groups. Prove that ${\rm Aut}(G)$ is isomorphic with the group of all invertible $n\times n$ matrices whose $(i,j)$ entries belong to ${\rm Hom}(G_i, G_j)$, the usual matrix product being the group operation.

Thoughts:
I'm used to thinking of the direct product of groups as the group defined by a certain presentation, or else simply as the obvious generalisation of $$H\times K=\{(h,k)\mid h\in H, k\in K\}$$ under the operation $(h,k)\cdot(h',k')=(hh', kk')$.
My linear algebra is a little rusty, which is probably why I'm struggling here.

Examples:
When $n=1$:
We have just the abelian group $G$. The automorphism group is
$${\rm Aut}(G)=\{\varphi\in {\rm Hom}(G,G)\mid \varphi \text{ is an isomorphism}\}$$
and the $1\times 1$ matrices are simply $(\varphi)$ with $(\varphi)^{-1}=(\varphi^{-1})$.
The isomorphism is trivial.
When $n=2$:
We have $G=G_1\times G_2$. Now the $(i,j)$ entries of the $2\times 2$ matrices are such that . . .
Wait a Minute . . .

What operation is the addition of the homomorphisms?

I guess this is my main stumbling block.
Let's try working it out & see . . .
So, we have
$${\rm Aut}(G)\stackrel{?}{\cong}\left\{
\begin{pmatrix}
\varphi_{(1,1)} & \varphi_{(1,2)}\\
\varphi_{(2,1)} & \varphi_{(2,2)}
\end{pmatrix} : \varphi_{(1,1)}\stackrel{?}{\times}\varphi_{(2,2)}\stackrel{?}{-} \varphi_{(1,2)}\stackrel{?}{\times}\varphi_{(2,1)}\neq \stackrel{?}{0} \right\}.$$
Okay, so I'm not sure on multiplication either, nor am I sure of what the zero element is.
This is a mess. I'm sorry.
Please help :)
Comment: I don't think the determinant formula for invertability is helpful here, as it would need to be adapted. And you want to write the abelian groups additively with the product in the matrix multiplication be composition of mappings.
Answer: Hints:

When $G$ is any group and $B$ is an abelian group, then $\mathrm{Hom}(G,B)$ is more than just a set, it is actually an abelian group. The operation is "pointwise addition", so that $(f+g)(a) = f(a)+g(a)$ for all $a\in G$. This is a homomorphism as well, since
$$\begin{align*}
(f+g)(a+a') &= f(a+a') + g(a+a')\\
&= f(a)+f(a') + g(a)+g(a')\\
&= f(a)+g(a)+f(a')+g(a')\\
&= (f+g)(a)+(f+g)(a').
\end{align*}$$
The identity element of this abelian group is the zero map, sending everything to $0_B$, and the additive inverse of $f$ is the function $g(a)=-f(a)$ for all $a\in A$. (When $G=B$, this is actually a ring, with the multiplication being composition of functions).

For any family of groups $\{G_i\}_{i\in I}$, a morphism $f$ from a group $H$ into the direct product $\prod_{i\in I}G_i$ is equivalent to a family of morphisms $\{f_i\}_{i\in I}$, with $f_i\colon H\to G_i$. This is the universal property of the product: given the family $\{f_i\}_{i\in I}$, there exists a unique morphism $F\colon H\to \prod G_i$ such that $f_i =\pi_i\circ F$, where $\pi_i$ is the projection onto the $i$th coordinate. Namely, $F(h) = (f_1(h),\ldots,f_n(h))$.

For a finite family of abelian groups, we also have maps going the other way. The embeddings $\iota_i\colon A_i\to \prod_{j\in J}A_j$ that sends $a\in A_i$ to the element of the product that has $a$ in the $i$th coordinate and $0$s in all the other coordinates have the following universal property: given any abelian group $K$, and given any morphisms $g_i\colon A_i\to K$ for each $i$, there exists a unique morphism $G\colon \prod A_i\to K$ such that $g_i = G\circ \iota_i$ for each $i$. Namely, $G(a_1,\ldots,a_n) = g_1(a_1)+\cdots + g_n(a_n)$. Thus, maps from a finite direct product of abelian groups are equivalent to a family of maps from the factors.

Putting those together, it should be clear that any homomorphism $G_1\times\cdots\times G_n\to G_1\times\cdots\times G_n$ corresponds to a family of morphisms $\varphi_{ij}\colon G_j\to G_i$. You should then verify that if you arrange them in a matrix in the "obvious" way, and what the corresponding morphism is, then the image of an element $(g_1,\ldots,g_n)$ under the corresponding morphism $\varphi\colon G_1\times\cdots\times G_n\to G_1\times\cdots\times G_n$ is given by computing
$$\left(\begin{array}{ccc}
\varphi_{11}& \cdots & \varphi_{1n}\\
\vdots & \ddots & \vdots \\
\varphi_{n1} & \cdots & \varphi_{nn}
\end{array}\right)
\left(\begin{array}{c}
g_1\\ \vdots\\ g_n\end{array}\right).$$
That will give you a description of the homomorphisms. It also tells you that the composition of homomorphisms "should" correspond to matrix multiplication. And that will tell you exactly when a homomorphism is actually an automorphism.
Answer: Given an abelian group $G$ noted additively (or more generally a module over any ring), its endomorphisms form a ring $\text{End}(G)$ under pointwise addition ($(\phi+\psi)(x)=\phi(x)+\psi(x)$ and composition (you can check the axioms yourself; distributivity follow from the functions being morphisms). An automorphism is an invertible endorphism, so $\text{Aut}(G)$ is the Group of units of $\text{End}(G)$.
Now, you just want to represent an endomorphism of the direct sum $G_1\oplus \cdots \oplus G_n$ with a matrix (direct sum is the same as direct product in this case but its more common to talk about sums when working with abelian groups/modules and it makes clearer the analogy with linear algebra).
You can see elements of $G_1\oplus \cdots \oplus G_n$ as column vectors with an element of $G_i$ in the $i$'th coordinate.
Then a matrix of endomorphisms acts on such column vectors just by usual matrix multiplication. For example when $n=2$:
$$\left(\begin{array}{ccc}
\varphi_{11} & \varphi_{12}\\
\varphi_{21} & \varphi_{22}
\end{array}\right)
\left(\begin{array}{c}
x_1\\ x_2\end{array}\right)=\left(\begin{array}{c}
\varphi_{11}(x_1) + \varphi_{12}(x_2)\\ \varphi_{21}(x_1) + \varphi_{22}(x_2)\end{array}\right)$$
It's not too hard to show that all endormorphims can be written in matrices. The proof is very similar to the analogous result in linear algebra that every linear map is given by a matrix.


Ringing or string muting in Carulli

Question: I am trying to get back into classical guitar after a break of a few years (my main instrument in my retirement is now piano).  I only ever played for fun, and only had about a year of formal lessons, and that was many more years ago then I care to remember.
Looking at some simple pieces by Carulli, as a decent (re-) starting point, I wondered if anyone has any thoughts about playing this bit:

From the notation, it would seem that Carulli is indicating that the repeated A notes on the open fifth string should last only for a quaver. I don't recall deliberately muting these repeated notes, so that I am sure I played them as whole notes rather than eight notes.
My question is this: do classical guitarists believe that Carulli was being very precise, and intended these notes to be muted at the same time that thirds are played on the upper strings? Put it another way: would a modern guitar examiner (e.g. ABRSM) deduct marks if one were to let these notes ring longer?
P.S. I have no intention of actually taking lessons or exams at my age, and am doing this purely for fun!
Answer: Carulli meant the lower notes to be exactly what he wrote. They are a separate line - a bass part, if you like, and he put rests between each open A string note.Rests are always there to be played, and if he was happy to let the A notes ring out as crotchets, surely he would have written them as crotchets.
They are not actually muted, but played as a sort of ping-pong against the thirds in the melody above. Can't find my Carulli book right now, but I suspect this motif occurs several times in the piece. And, yes, examiners would dock marks for a bass line such as this, if played legato.
EDIT: Found my copy of Andante, in  a Fred. Noad compilation - no quaver rests there! However, the low As are marked as quavers, so they would not be expected to play fo any longer than your example. Maybe your transcription is underlining the points I make.
Comment: I had suspected that, and if it had been Bach, I would expect to have to play them very precisely. However, this piece (I believe) comes at a very early stage in his method, and I am not sure if he has talked about muting strings at such an early stage. When you say "they are not actually muted", then how do you stop them sounding longer than the eighth notes they are written as?
Comment: Muting involves placing part of the hand ( and it could be either) on a string to be played, so the sound comes out as anything but a ringing. More a dull thud with a pitch. Play each note, then stop it dead. Much easier if it was 5th fret 6th string, as you could pulse the fretting finger to stop the note each time, but this is early stages, so thumb plucks and goes back on string. A funny sort of rest stroke, I suppose. A more advanced technique than I'd expect for this level, though.
Comment: So, with this "funny sort of rest stroke" you are saying that you DO actually mute the string (with the thumb) to stop it continuing to sound?
Comment: Only in as much as you let the note ring out for as long as it's supposed to. To me, a muted note is a palm-mute, which never sounds like a clear note. But, yes, if you like, almost every note played is muted by your definition, as it has to be stopped to leave space for the following note! Thinking about it, the note could be cut short (maybe a better description) using a fretting hand finger each time. There are a couple spare at that point.

Ringing or string muting in Carulli


Counter example for a norm relationship

Question: Function $w(x)$, $x\in[0,1]$ is four times differentiable, and its forth derivative is absolutely continuous. In addition, it satisfies the boundary conditions $w(0)=w(1)=w''(0)=w''(1)$. I am wondering if $\| w\|_2<C$ gives $\| w\|_p<K_C$ and vice versa.
Answer: The differentiability of $w$ and the boundary conditions do not really matter here. First, using Hölder's inequality, it is easy to check that
$$
\Vert w\Vert_{L^p([0,1])}\leq \Vert w\Vert_{L^q([0,1])}
$$
for any $1\leq p\leq q$. If $p>q$, then it is known that $w\in L^p$, since it is continuous on a compact, thus $L^\infty$, but there is no control of the $L^p$ norm in terms of the $L^q$ norm. Indeed, choose any $\rho\in C^\infty(\mathbb R)$ with compact support in $[0,1]$ and such that $\Vert \rho\Vert_q=1$. Then, for $\epsilon>0$, define
$$
\rho_\epsilon:x\mapsto \epsilon^{-1/q}\rho(x/\epsilon).
$$
It is easy to check that $(\rho_\epsilon)_{0<\epsilon\leq1}$ verifies the conditions you asked for, and $\Vert \rho_\epsilon\Vert_q=1$, but $\Vert \rho_\epsilon\Vert_p=\epsilon^{1/p-1/q}\Vert \rho\Vert_p\to+\infty$ as $\epsilon \to 0$.
Comment: Would the limit of the function $\rho$ not a member of $C^\infty$?
Comment: The sequence $\rho_\epsilon$ has no limit in $L^p$ indeed, the purpose of this is just to show that there can not be a constant $K$ depending only on $C$ such that $\Vert w\Vert_2 < C \implies \Vert w\Vert_p < K$, as $\Vert w\Vert_p$ can be as big as we want it to be.
Comment: True; that's clear; but, I have restricted my functions to be in a much smaller subspace. I mean both $L_p$ and $L_q$ norms are defined for all members of this subspace.
Comment: I hear you, but the set of $C^\infty$ functions with compact support in $[0,1]$ is a subset of the subspace you are considering. For all $0<\epsilon\leq 1$, the functions $\rho_\epsilon$ definitely are in the required subspace.
Comment: So having said this; I am guessing the function $f: L^2\to L^2 , \; w\mapsto w^3$ is not even locally Lipschitz function since we cannot write $\|w\|_6 \le K_C \|w\|_2, \, \forall \|w\|_2\le C$; true?
Comment: That is true, since in any neighbourhood of any point in $L^2$, following the reasoning, it is possible to find a function with as big an $L^6$ norm as you want it to be. That is also true in the particular subspace you desvribed.

Counter example for a norm relationship


Search and replace using the filename

Question: I'm trying to do a search and replace over multiple files where I find something like: <form> and replace it with something like: <form id="fileNameForm">
So for example if the filename was "helloWorld.html" it would replace <form> with <form id="helloWorldForm">
Comment: What's langue you used, shell script or others ? Is there just on form in the file?
Comment: Any language that could do it. Shell script if that'll work.  And yes, just one form per file.
Answer: [kerwin@fedori ~]$cat replace.sh
#!/bin/bash
for file in `find -name '*.html'`
do
id=`echo $file | sed -r 's#.*\/([a-z]+)\.[a-z]+#\1#i'`
`sed -i "s#<form>#<form id=\"$id\">#i" $file`
echo $file -----ok!
done

execute it in the same folder

Search and replace using the filename


Definindo uma margem em uma background image

Question: Considere o seguinte código html: http://jsfiddle.net/qt7dsx7b/
No fiddle foi definida uma div com uma imagem localizada no canto superior direito. Ocorre que eu gostaria de adicionar uma margem entre a imagem e a borda da div (simulando um padding de 10px na div). Tentei colocar padding na div, mas a imagem de fundo não se mexe. Também poderia colocar um background-position: rigth 95%, mas nesse caso eu precisaria saber de antemão o tamanho da div e o tamanho da imagem, e ambas as informações eu não possuo. A única informação conhecida é o espaço de 10px entre a imagem e a borda.
Comment: Excelente pergunta. Esse é um dos efeitos de coisa criada por comitê (CSS, por exemplo). Os caras enchem de detalhe que não precisa na especificação, mas não pensam nas coisas óbvias necessárias no dia-a-dia.
Answer: Não é bem o que você está pedindo, pois o CSS é muito limitado nesse aspecto, mas se você tiver controle sobre o padding do elemento, e ele for o mesmo do conteúdo da
, uma possibilidade é usar o background-origin para acrescentar o valor do padding como margem:
div.box{
    padding:10px;
    background-image: url(/minha/imagem.png);
    background-repeat: no-repeat;
    background-position: right top;
    background-origin: content-box;
}

Suporte: IE9+ (IE8 dependendo do uso), Opera 10.5+, Firefox 4+, Webkit (com prefixo), Konkeror (com prefixo). Em Mobile não sei dizer a compatibilidade.
Veja aplicado ao seu JS Fiddle.
Comment: @Borachio só tem que ver se o padding vai ser compatível com o conteúdo da DIV. Tem várias outras soluções, mas sem conhecer o caso real em que será aplicado, corro o risco de propor coisa incompatível. Se o padding servir, é a solução mais limpa das que eu vi. Lembrando que vc pode aplicar 2 fundos diferentes ou mais nos browsers recentes, e dá pra especificar separado o comportamento de cada um (um deles pegando o retangulo todo, o outro com margem). Basta separar por virgula.
Comment: Interessante essa propriedade background-origin. É uma boa saída para o meu problema.


Gun at start of run

Question: When I see track athletics on TV, for example at the Olympics, I see a gun is used to start a race. Why is a gun is used instead of, for example, a whistle?
Comment: Are you asking more about the relative advantages of the "guns" used in current Olympics ([which aren't guns now at all](http://mentalfloss.com/article/31429/why-they-stopped-using-real-pistols-start-olympic-races)), or more about the traditions of why guns were historically used rather than something else?
Comment: I don't think, I see. My ex sport teacher used a whistle.
Comment: Why do you think a whistle is preferable to a gun?
Comment: I aske About the traditions of why guns were historically used rather than something else.
Answer: A gun provides a single, relatively discrete sound at a relatively constant volume throughout a meeting. The volume of a whistle will vary from blow to blow, depending on how it's blown. Also, a whistle is not a sharp sound; it's harder to pinpoint the exact moment of race starting, which is both challenging to the athletes and also difficult for the race timers in events where finish times are sliced to thousandths of a second. (Results are listed to hundredths with automatic timing, but the systems can time to thousandths; the extra precision is used to separate ties.)
This last is perhaps more important: in the days of Fully Automatic Timing (FAT) the starting signal needs to trigger the timing system. A specially configured starter's pistol can do that, but there have also been systems using a different audible signal, e.g. a loud handclap.
Comment: I think we might have slightly different concepts of what a "whistle" should sound like. If you're thinking of something like what an official in a football game would blow - "TWEEEET" - the problem is that we really need just the "T" and any extended "EE" is ambiguous to the system. But yes, notice the various noises used in starting swim races.
Comment: if just about "relatively discrete sound at a relatively constant volume" so theoretically one can use artificial / electrical whistle ?

Gun at start of run


Creating a Twitter-like timeline using loops, rails

Question: At the moment I have Fans that can follow Artists. Now I want to display Artist's microposts of the Artists the Fan is following.
I want to sort Artist's microposts by created_at as they are created.
<% @fan.artists.each do |artist| %>
  <% artist.artist_microposts.sort_by{ |micropost| micropost.created_at }.each do |micropost| %>
   <%= micropost.content %>
  <% end %>
<% end %>

It's sorting by created_at, but since it's looping through each artist first, it's displaying all microposts that belong to one artist, then displaying all mircoposts that belong to the next artist, and so on.
I want it to be more of a timeline, like Twitter, that displays microposts at they come in.
Answer: This is not how you implement this feature. If you want to update the timeline as new tweets arrive, then you need to listen to changes using Jquery. Watch this [http://railscasts.com/episodes/229-polling-for-changes][1]
It will show you how to implement the feature you are looking for.
Hint : Don't sort by created_at, it's a bad practice, because create_at is not an index and will be slower. Instead sort by id, it's auto incremented and indexed.
artist.artist_microposts.order('id DESC')

Answer: I was able to solving by first fetching the artist ids and then selecting the posts that was associated with those artists.
irb(main):019:0> fan = Fan.first
#<Fan id: 1, name: "Tony">

irb(main):020:0> ids = fan.artists.pluck(:id)
#=> [1, 2]

irb(main):022:0> posts = Post.where(:artist_id => ids).order("created_at DESC")
#=> #<ActiveRecord::Relation [
 #<Post id: 3, text: "Third Post", artist_id: 1, created_at: "2015-02-10 12:54:32">,
 #<Post id: 2, text: "Second Post", artist_id: 2, created_at: "2015-02-09 12:53:14">,
 #<Post id: 1, text: "First Post", artist_id: 1, created_at: "2015-02-08 12:52:51">  ]>

Answer: I was able to accomplish this by creating a join table between fans, artists, and artist_microposts. I then did
<% @fan.artist_microposts.sort_by{ |micropost| micropost.id }.each do |micropost| %>
   <%= micropost.content %>
<% end %>

Worked perfectly.


Cricket stumps that don't need to be pushed into the ground

Question: I'm looking for a set of cricket stumps that don't need to be pushed into the ground or some other way to use the traditional set of cricket stumps on a hard surface such as a tennis court.
Anybody have any ideas how I can achieve this?
Answer: Your best bet is to get the kind of stumps used in indoor cricket. You can see some in use for instance here. The stumps are connected to a flat solid base and are spring loaded so they return to the upright positions by themselves after being knocked over by the ball.
I'm sure these could be purchased online if you can't find any at your local sports stores.


Contagem de numero de acordo com scroll da página jQuery!

Question: Pessoal tenho uma PROGRESS BAR que exibe números de 0% até 100%, preciso que quando o scroll for maior que 900px, seja iniciado a contagem dos números por exemplo de 0% a 70% no tempo de 2 segundos.. tenho um código aqui esta funcionando porem.. ele faz a contagem só que se eu mover o scroll da página novamente ele refaz a contagem.. preciso que a animação seja feita só uma unica vez apos o usuário ultrapassar os 900px de scroll.. segue o código:
if(scrollTop > 900) {
  $('#front-bar').animate({ width: "70%" }, 2000);
  // Percent count
  $({ counter: 0 }).animate({ counter: 70 }, {
    duration: 2000,
    step : function(){
      $('#front-bar-count').text(Math.ceil(this.counter) + ' %');
    }
  });
}

Answer: Pode utilizar uma variável auxiliar para controlar se já fez a animação e testar a variável antes de animar.
Exemplo:
var animacaoFeita = false;

$(window).scroll(function(){ //função de interpretação de evento de scrolling
  ...
  if(scrollTop > 900 && animacaoFeita == false) {
    animacaoFeita = true; //colocar como já feita para não fazer da próxima vez
    $('#front-bar').animate({ width: "70%" }, 2000);
    // Percent count
    $({ counter: 0 }).animate({ counter: 70 }, {
      duration: 2000,
      step : function(){
        $('#front-bar-count').text(Math.ceil(this.counter) + ' %');
      }
    });
  }
  ..
}

Comment: Deu certo aqui brother.. vlw!


Inserindo mensagem de erro ao usuário

Question: Faça um programa que receba dois números. Calcule e mostre: A soma dos números pares desse intervalo, incluindo os números digitados. A multiplicação dos números ímpares desse intervalo, incluindo os digitados.
Resolvi da seguinte forma:
x = int(input('Digite um número: '))
y = int(input('Digite um número: '))

par = 0
impar = 1

for i in range(x-1, y+1):
    if i % 2 == 0:
        par = par + i
    elif i % 2 != 0:
        impar = impar * i

print('A soma dos números pares entre', x, 'e', y, 'é', par, '.')
print('A multiplicação dos números impares entre', x, 'e', y, 'é', impar, '.')

Porém se o usuário informa o primeiro número maior que o segundo, ou os dois números iguais, o resultado retornado é errado.
Resolvi da seguinte forma.
while True:
    x = int(input('Digite um número: '))
    y = int(input('Digite um número: '))
    if x < y:
        break
    else:
        continue

    if x == y:
        break
    else:
        continue

par = 0
impar = 1

for i in range(x-1, y+1):
    if i % 2 == 0:
        par = par + i
    elif i % 2 != 0:
        impar = impar * i

print('A soma dos números pares entre', x, 'e', y, 'é', par, '.')
print('A multiplicação dos números impares entre', x, 'e', y, 'é', impar, '.')

Porem, Gostaria de colocar uma mensagem de erro, para que o usuário saiba o que tem que fazer.
while True:
    x = int(input('Digite um número: '))
    y = int(input('Digite um número: '))
    if x < y:
        "Acredito que aqui deveria estar a mensagem de erro, porem colocando o print com erro aqui não da certo."
        break
    else:
        continue

    if x == y:
        break
    else:
        continue

Answer: Não precisa usar continue. Basta colocar o print nos casos de erro e só chamar o break se não entrar em nenhum desses casos:
while True:
    x = int(input('Digite um número: '))
    y = int(input('Digite um número: '))
    if x == y: # se forem iguais
        print('Números não podem ser iguais')
    elif x > y: # se x for maior que y
        print('x deve ser menor que y')
    else: # x é menor que y, sai do loop
        break

Se forem iguais, imprime a primeira mensagem. Se x for maior que y, imprime a segunda mensagem. Senão, sai do loop.
Nesse caso, se cai em um dos casos de erro, o while continua executando e ele pede que os números sejam digitados novamente. Mas se a ideia for sair do programa, você pode usar sys.exit:
import sys
x = int(input('Digite um número: '))
y = int(input('Digite um número: '))
if x == y:
    print('Números não podem ser iguais')
    sys.exit(1)
elif x > y:
    print('x deve ser menor que y')
    sys.exit(2)

O número passado para sys.exit é opcional (se nenhum for passado, será zero), e é geralmente usado para indicar o código de erro (eu usei códigos diferentes para indicar cada situação).
E nesse caso, nem precisa de loop, já que ou o programa é encerrado, ou ele prossegue (não há o "tente novamente").

Outro detalhe é que se você quer os números entre x e y (com y incluso), então deve usar range(x, y + 1).
E o seu for não precisa do elif, podendo ser trocado por else:
soma_pares = 0
produto_impares = 1
for i in range(x, y + 1):
    if i % 2 == 0:
        soma_pares += i
    else:
        produto_impares *= i

Isso porque se i % 2 for zero, entra no if. Se não entrou no if, que dizer que com certeza não é zero, então no else eu não preciso testar se é diferente de zero (nesse ponto fazer elif i % 2 != 0 é redundante e desnecessário).
Também usei += (que já soma e atribui o resultado à variável) e *= (que faz o mesmo com a multiplicação), e dei nomes melhores para as variáveis. Pode parecer um detalhe besta, mas dar nomes melhores ajuda na hora de programar.

Por fim, vale lembrar que int dá erro se não for digitado um número válido. Se quiser validar isso, uma alternativa é:
def ler_numero(mensagem='Digite um número'):
    while True:
        try:
            return int(input(mensagem))
        except ValueError:
            print('Não foi digitado um número válido')

x = ler_numero()
y = ler_numero()

Assim, a função fica tentando converter o que foi digitado para número. Se não der certo, é lançado o ValueError e ele pede que digite novamente.
Answer: Você pode tentar usar a função "try" e "except", caso o "try" dê errado, a função "except" entrará em jogo printando o que você quiser na tela, o except também tem alguns argumentos que ele só ativa caso o erro seja por exemplo "ValueError", aconselho você a dar uma pesquisada sobre. Ficaria nesse estilo:
while True:
    try:
        x = int(input('Digite um número: '))
        y = int(input('Digite um número: '))
        if x < y:
            exit()
        if x == y:
            exit()
    except:
        print("O valor de 'x' não pode ser menor ou igual a 'y', saindo...")

A função exit() automaticamente acionará o que está dentro da "except", printando assim o erro para quem está usando

Inserindo mensagem de erro ao usuário