Listen and respond to ajax_command_replace()

Question: I have a page where a block is dynamically reloaded when the user clicks a link. Rather than writing my own js, I'm trying to do this the Drupal way and using Drupal's own ajax_command_replace() like so:
function page_callback($type = 'ajax') {
    if ($type == 'ajax') {
    // Load block
    // ....
    $commands[] = ajax_command_replace('#block-watch-notifications', $output);
    $page = array(
       '#type' => 'ajax',
       '#commands' => $commands,
    );
    ajax_deliver($page);
}

And all this works just fine.
The problem is that I need to respond to this event on my page. The js event DOMSubtreeModified would work here if it were reliably implemented by browsers, but it's not.
However, jQuery's AJAX command also issues its own series of global events, including ajaxComplete. The problem is that, however Drupal is doing its AJAX magic, it isn't raising this event.
How can I listen for ajax_command_replace() having done its work on my page?
Answer: From what I can tell, Drupal behaviors are simply callback functions that are called in two cases: 1. when the page is loaded initially, and 2. when content is added/removed via ajax.
You add your callback function to the global js object Drupal.behaviors (US spelling), namespaced by your module's name. My module is called 'watch' so I attach my callback functions to Drupal.behaviors.watch. Drupal.behaviors.MODULE_NAME is itself an object and has two elements that may be named 'attach' and 'detach'.
'Attach' is called during the initial page load and whenever Drupal's ajax adds new content. 'Detach' is called when is Drupal's ajax removes content, either before adding replacement content or removing it forever.
For the record my javascript looked like this:
(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      // This code is fired both when the page is 'ready'
      // in the jquery sense, and when new content
      // is 'attached' via Drupal ajax. The settings
      // values that are available to us here
      // are provided in the third parameter of
      // ajax_command_replace() as an associative array.
      // My new content is already part of the dom
      // so I can act on it here.
    },
    detach: function(context, settings, trigger) {
      // Example detach callback.
    }
  }
})(jQuery);

I'm guessing Drupal behaviors can be extended to include all sorts of other behaviors beyond attach and detach and is probably very flexible besides, but that's beyond me right now.
Answer: The API documentation tells us that ajax_command_replace() is handled in javascript by Drupal.ajax.prototype.commands.insert. At the end of the javascript insert function, Drupal attaches behaviors to the newly added content, passing any settings set in ajax_command_replace().
From this we know that you can add your own behavior and check for a specific setting you set to know that your acting on your content. This will allow you to do some action when the AJAX is "complete".
The other option is to register a Global jQuery AJAX Event Handler. These event handlers are fired for every single AJAX event on a page (assuming of course that jQuery is used for sending the request) and requires a lot of checking and rechecking to make sure you're acting on the request you want.
Answer: There is   hook_ajax_alter: http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_ajax_render_alter/7
This works on php level, but if you do it there, you could search the commands and add your custom command if wanted.
Comment: The question is specific about responding to a JavaScript event.
Comment: Except I've issued the ajax commands myself (see above). hook_ajax_render_alter() doesn't let me alter the nitty gritty js (eg. to cause it to trigger an event), it just lets me reissue the commands differently (eg. change the selector). Or am I missing something?
Comment: Well you could scan through the commands and look for ajax_command_replace. If there is, replace it with your ajax_command_custom_replace which allows does ajax_command_replace and some random custom stuff.


Grinder - Auto generated jython test case scripts are not working

Question: I created jython test cases scripts with TCPProxy Console. But those are not working, while I am trying to run.
My test cases is
Sample33.py
# The Grinder 3.11
# HTTP script recorded by TCPProxy at 29 Jul, 2014 10:19:35 AM

from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest
from HTTPClient import NVPair
connectionDefaults = HTTPPluginControl.getConnectionDefaults()
httpUtilities = HTTPPluginControl.getHTTPUtilities()

# To use a proxy server, uncomment the next line and set the host and port.
# connectionDefaults.setProxyServer("localhost", 8001)

def createRequest(test, url, headers=None):
    """Create an instrumented HTTPRequest."""
    request = HTTPRequest(url=url)
    if headers: request.headers=headers
    test.record(request, HTTPRequest.getHttpMethodFilter())
    return request

# These definitions at the top level of the file are evaluated once,
# when the worker process is started.

connectionDefaults.defaultHeaders = \
  [ NVPair('Accept-Encoding', 'gzip, deflate'),
    NVPair('Accept-Language', 'en-US,en;q=0.5'),
    NVPair('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0'), ]

headers0= \
  [ NVPair('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
    NVPair('Referer', 'http://mycompany.com/'), ]

url0 = 'http://mycompany.com:80'

request101 = createRequest(Test(101, 'GET /'), url0)

request201 = createRequest(Test(201, 'POST home'), url0, headers0)

request202 = createRequest(Test(202, 'GET home'), url0, headers0)

request203 = createRequest(Test(203, 'GET /'), url0, headers0)

request301 = createRequest(Test(301, 'GET holidays-2014'), url0, headers0)

request302 = createRequest(Test(302, 'GET Untitled_3.png'), url0)

request303 = createRequest(Test(303, 'GET Untitled_3.png'), url0)

class TestRunner:
  """A TestRunner instance is created for each worker thread."""

  # A method for each recorded page.
  def page1(self):
    """GET / (request 101)."""
    result = request101.GET('/', None,
      ( NVPair('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
        NVPair('If-Modified-Since', 'Mon, 28 Jul 2014 10:47:07 +0000'),
        NVPair('If-None-Match', '\"1406544427\"'), ))
    self.token_form_build_id = \
      httpUtilities.valueFromHiddenInput('form_build_id') # 'form-MvE2-tuZ5-faR4EyZ0XSU6qaOpz8rex1-4u...'
    self.token_form_id = \
      httpUtilities.valueFromHiddenInput('form_id') # 'user_login_block'

    return result

  def page2(self):
    """POST home (requests 201-203)."""
    self.token_destination = \
      'node/103'

    # Expecting 302 'Found'
    result = request201.POST('/home' +
      '?destination=' +
      self.token_destination,
      ( NVPair('name', 'myuser'),
        NVPair('pass', 'mypassword'),
        NVPair('form_build_id', self.token_form_build_id),
        NVPair('form_id', self.token_form_id),
        NVPair('op', 'Log in'), ),
      ( NVPair('Content-Type', 'application/x-www-form-urlencoded'), ))

    grinder.sleep(27)

    # Expecting 301 'Moved Permanently'
    request202.GET('/home')

    grinder.sleep(18)
    request203.GET('/', None,
      ( NVPair('If-Modified-Since', 'Tue, 29 Jul 2014 04:47:09 +0000'),
        NVPair('If-None-Match', '\"1406609229\"'), ))

    return result

  def page3(self):
    """GET holidays-2014 (requests 301-303)."""
    result = request301.GET('/content/holidays-2014')
    self.token_form_build_id = \
      httpUtilities.valueFromHiddenInput('form_build_id') # 'form-VWPMyhphM5Lg3O6qyQx1iS_uc6p20Scw7cY...'
    self.token_form_token = \
      httpUtilities.valueFromHiddenInput('form_token') # 'DT9Ya9GCdGKlSNIEMLP4noRGMnd4Dvs2WVgMsEsw...'
    self.token_form_id = \
      httpUtilities.valueFromHiddenInput('form_id') # 'search_block_form'

    grinder.sleep(47)
    request302.GET('/sites/default/files/Untitled_3.png', None,
      ( NVPair('Accept', 'image/png,image/*;q=0.8,*/*;q=0.5'),
        NVPair('Referer', 'http://mycompany.com/content/holidays-2014'), ))

    return result

  def __call__(self):
    """Called for every run performed by the worker thread."""
    self.page1()      # GET / (request 101)

    grinder.sleep(279)
    self.page2()      # POST home (requests 201-203)

    grinder.sleep(147)
    self.page3()      # GET holidays-2014 (requests 301-303)

# Instrument page methods.
Test(100, 'Page 1').record(TestRunner.page1)
Test(200, 'Page 2').record(TestRunner.page2)
Test(300, 'Page 3').record(TestRunner.page3)

My Properties file: test.properties
grinder.script=sample33.py
grinder.processes=1
grinder.threads=1
grinder.runs=0
grinder.logDirectory=log
grinder.numberOfOldLogs=2
grinder.useConsole=false

My output:
2014-07-29 11:01:10,579 INFO  myuser-0 thread-0 [ run-193, test-301 ]: http://mycompany.com/content/holidays-2014 -> 403 Forbidden, 18674 bytes
2014-07-29 11:01:10,579 INFO  myuser-0 thread-0 [ run-193 ]: sleeping for 48 ms
2014-07-29 11:01:10,652 INFO  myuser-0 thread-0 [ run-193, test-302 ]: http://mycompany.com/sites/default/files/Untitled_3.png -> 200 OK, 130429 bytes
2014-07-29 11:01:10,996 INFO  myuser-0 thread-0 [ run-194, test-101 ]: http://mycompany.com/ -> 403 Forbidden, 17617 bytes
2014-07-29 11:01:10,997 INFO  myuser-0 thread-0 [ run-194 ]: sleeping for 263 ms
2014-07-29 11:01:11,686 INFO  myuser-0 thread-0 [ run-194, test-201 ]: http://mycompany.com/home?destination=node/103 -> 302 Found, 0 bytes [Redirect, ensure the next URL is http://mycompany.com/home]
2014-07-29 11:01:11,686 INFO  myuser-0 thread-0 [ run-194 ]: sleeping for 27 ms
2014-07-29 11:01:11,973 INFO  myuser-0 thread-0 [ run-194, test-202 ]: http://mycompany.com/home -> 301 Moved Permanently, 0 bytes [Redirect, ensure the next URL is http://mycompany.com/]
2014-07-29 11:01:11,973 INFO  myuser-0 thread-0 [ run-194 ]: sleeping for 17 ms
2014-07-29 11:01:12,229 INFO  myuser-0 thread-0 [ run-194, test-203 ]: http://mycompany.com/ -> 403 Forbidden, 17617 bytes
2014-07-29 11:01:12,229 INFO  myuser-0 thread-0 [ run-194 ]: sleeping for 141 ms
2014-07-29 11:01:12,681 INFO  myuser-0 thread-0 [ run-194, test-301 ]: http://mycompany.com/content/holidays-2014 -> 403 Forbidden, 18674 bytes
2014-07-29 11:01:12,682 INFO  myuser-0 thread-0 [ run-194 ]: sleeping for 46 ms
2014-07-29 11:01:12,751 INFO  myuser-0 thread-0 [ run-194, test-302 ]: http://mycompany.com/sites/default/files/Untitled_3.png -> 200 OK, 130429 bytes
2014-07-29 11:01:13,033 INFO  myuser-0 thread-0 [ run-195, test-101 ]: http://mycompany.com/ -> 403 Forbidden, 17617 bytes
2014-07-29 11:01:13,034 INFO  myuser-0 thread-0 [ run-195 ]: sleeping for 307 ms
2014-07-29 11:01:13,937 INFO  myuser-0 thread-0 [ run-195, test-201 ]: http://mycompany.com/home?destination=node/103 -> 302 Found, 0 bytes [Redirect, ensure the next URL is http://mycompany.com/home]
2014-07-29 11:01:13,938 INFO  myuser-0 thread-0 [ run-195 ]: sleeping for 27 ms
2014-07-29 11:01:14,223 INFO  myuser-0 thread-0 [ run-195, test-202 ]: http://mycompany.com/home -> 301 Moved Permanently, 0 bytes [Redirect, ensure the next URL is http://mycompany.com/]
2014-07-29 11:01:14,224 INFO  myuser-0 thread-0 [ run-195 ]: sleeping for 18 ms
2014-07-29 11:01:14,480 INFO  myuser-0 thread-0 [ run-195, test-203 ]: http://mycompany.com/ -> 403 Forbidden, 17617 bytes
2014-07-29 11:01:14,480 INFO  myuser-0 thread-0 [ run-195 ]: sleeping for 149 ms
2014-07-29 11:01:14,931 INFO  myuser-0 thread-0 [ run-195, test-301 ]: http://mycompany.com/content/holidays-2014 -> 403 Forbidden, 18674 bytes
2014-07-29 11:01:14,932 INFO  myuser-0 thread-0 [ run-195 ]: sleeping for 49 ms
2014-07-29 11:01:15,003 INFO  myuser-0 thread-0 [ run-195, test-302 ]: http://mycompany.com/sites/default/files/Untitled_3.png -> 200 OK, 130429 bytes
2014-07-29 11:01:15,277 INFO  myuser-0 thread-0 [ run-196, test-101 ]: http://mycompany.com/ -> 403 Forbidden, 17617 bytes
2014-07-29 11:01:15,278 INFO  myuser-0 thread-0 [ run-196 ]: sleeping for 301 ms
2014-07-29 11:01:15,332 INFO  myuser-0 : communication shut down
2014-07-29 11:01:15,340 INFO  myuser-0 thread-0 [ run-196 ]: shut down
2014-07-29 11:01:15,341 INFO  myuser-0 thread-0: finished 196 runs
2014-07-29 11:01:15,341 INFO  myuser-0 : elapsed time is 404648 ms
2014-07-29 11:01:15,341 INFO  myuser-0 : Final statistics for this process:
2014-07-29 11:01:15,350 INFO  myuser-0 :
             Tests        Errors       Mean Test    Test Time    TPS          Mean         Response     Response     Mean time to Mean time to Mean time to
                                       Time (ms)    Standard                  response     bytes per    errors       resolve host establish    first byte
                                                    Deviation                 length       second                                 connection
                                                    (ms)

(Test 100    197          0            286.38       35.05        0.49         0.00         0.00         0            -            -            0.00)         "Page 1"
Test 101     197          0            285.10       34.57        0.49         17617.00     8576.71      197          0.10         2.25         265.98        "GET /"
(Test 200    196          0            970.07       233.03       0.48         0.00         0.00         0            -            -            0.00)         "Page 2"
Test 201     196          0            453.68       223.42       0.48         0.00         0.00         0            0.03         2.51         453.05        "POST home"
Test 202     196          0            219.01       30.85        0.48         0.00         0.00         0            0.02         2.26         218.58        "GET home"
Test 203     196          0            250.14       22.02        0.48         17617.00     8533.17      196          0.02         2.20         230.47        "GET /"
(Test 300    196          0            379.49       33.35        0.48         0.00         0.00         0            -            -            0.00)         "Page 3"
Test 301     196          0            302.42       32.69        0.48         18674.00     9045.16      196          0.01         2.20         283.80        "GET holidays-2014"
Test 302     196          0            28.66        4.78         0.48         130429.00    63176.10     0            0.01         2.19         6.21          "GET Untitled_3.png"

Totals       1177         0            256.53       157.42       2.91         30711.70     89331.14     589          0.03         2.27         243.03
             (589)        (0)

  Tests resulting in error only contribute to the Errors column.
  Statistics for individual tests can be found in the data file, including
  (possibly incomplete) statistics for erroneous tests. Composite tests
  are marked with () and not included in the totals.

all pages it is showing 403 error only.
I tried recording(saving every page) also. Only login page only recording(saving) no other pages. not coming
Please help me, is it need to change any thing in the auto generated code?
what is 'name' and 'pass' fields, is it stable for every url or else, I have to change corresponding to my site?
Answer: Refer this link Error 403
I believe you have to go and talk to your server / network team .This is more local network issue rather than grinder thing.
You can try recording without using DNS since its in your network type in the ipaddress then record your interactions or change the URL to IP Address .
However do remeber if you switch to ip you wont be able to reap the benefits of load balancing.


How do I change certain page titles?

Question: How do I change certain page titles in Drupal, most notably the create new account, log in, and request new password tab headings?
Answer: you can create a module. inside the module you can use the function form_alter to modify the form, and specifically use the function drupal_set_title() to add the title, for example:
create a module with the name "change_title".
add a form_alter function (note that the name of the module is added to the _form_alter name function)
function change_title_form_alter(&$form, &$form_state, $form_id) {

 //dsm($form_id) this function is to know the $form_id

   if ($form_id == 'content_type_node_form') {
       drupal_set_title('this is my new title');
   }

}

note: about how to get the $form_id value, you can use Devel module to use the function dsm($form_id), then the return of this function will show you the $form_id value.
Comment: sorry, I do not know other easy way, but if you review how to start a module, you will find that is very easy, in few words is just to create one directory and also create two files, then add the code inside one of this files (the .module file): see a 'howto' http://drupal.org/node/231276
Comment: OK... but is there a simpler way to achieve this? I'm not really the module-creating type ;-)
Comment: Thank you, I will look into this as it may be helpful for other projects...
Answer: If you want to change the strings used in Drupal, you can use string overrides: Add code similar to the following one, at the bottom of the settings.php file used by your Drupal site.
$conf['locale_custom_strings_en'] = array(
  'forum'      => 'Discussion board',
  '@count min' => '@count minutes',
);

The description given for strings overrides in the settings.php file is the following:

String overrides:
To override specific strings on your site with or without enabling locale module, add an entry to this list. This functionality allows you to change a small number of your site's default English language interface strings.
Comment: @kiamlaluno Do you know why it works on 'User account' title, but not the 'Request new password'? The 'Request new password' only change the tabs title and not the page title.
Answer: The String Overrides module will do this.
From the project page:

Provides a quick and easy way to replace any text on the site.

It also has versions for both D6 and D7.

How do I change certain page titles?


proof of identity theorem

Question: Let f and g be holmorphic on the area D, where there is a $z_o \in D$ in the area with $f^{(n)}(z_o)=g^{(n)}(z_o)$ for all $n\in \mathbb{N}$ greater than a certain $n_1\in \mathbb{N}$. I've got show the existence of a polynomial $p\in \mathbb{C}[z]$, so that $f(z)=g(z)+p(z)$ for $z\in D$. Unfortunately I've got no idea. I thought f and g have to be equal by the identity theorem, but obvously I'm false. Any help is appreciated.
Answer: Since both are holomorphic both are equal to their Taylor series in a neighborhood around $z_0$, and by your assumption, these Taylor series are equivalent except for a finite number of terms, which gives you your polynomial $p(z)$. Since you then get $f(z)=g(z)+p(z)$ in some neighborhood, they much in fact be equal on $D$.
Answer: By the identity theorem, $f^{(n_1)}=g^{(n_1)}$. Therefore, $(f-g)^{(n_1)}=0$ and so $f-g$ is a polynomial function.

proof of identity theorem


Using CausalImpact in R, observed data affected by event that could not affect priors

Question: I am just starting out using the Causal Impact package in R. I am looking at observed data where I know there will be periods of extra traffic due to outside forces. However I cant find any unbiased priors to feed this in. Is there a way to say, 'At this point during the timescale, we expect to see and uplift' to help the model map it more efficiently.
Thanks
Answer: It is possible to have a gap between pre- and post-period by specifying the arguments such pre.period[1] does not immediately follow pre.period[2]. With this, it is possible to exclude some time period around the intervention that is known to be affected by external factors.
Apart from that, there is currently no possibility to exclude e.g. specific time points of some covariates.


Relatively compact subsets of a manifold.

Question: So I'm going through Otto Forster's "Lectures on Riemann Surfaces", and I need another hint (shame).  This is in the "Cohomology Groups" sections, as part of a problem to show that for $X$ a compact Riemann Surface, $H^1(X,\mathbb{C})$ is a finite dimensional $\mathbb{C}$-vector space.
Question
Suppose $X$ is a manifold, $U \subseteq X$ is open, and $V \subseteq U$ is relatively compact in $U$.  Show that $V$ meets at most finitely many connected components of $U$.
My Attempt (so far)
Let $\{U_i\}_{i \in I}$ be the connected components of $U$, with the $U_i$ disjoint, and $I$ perhaps infinite.  Since all the $U_i$ are open (in $U$), and $V \subseteq U$, $\{V \cap U_i\}_{i \in I}$ is an open cover of $V$ (relative to $V$). Since, by assumption, the closure of $V$, which I'll denote $\overline{V}$, is compact in $U$, and $\{\overline{V} \cap U_i\}_{i \in I}$ is an open cover of $\overline{V}$, there exists a finite subcover $\{\overline{V} \cap U_i\}_{i=1}^n$ (sorry for the run-on sentence...).
I then (want to) claim that $V$ meets only the finite set of components $\{U_i\}_{i=1}^n$ given by the finite subcover of $\overline{V}$.  This is where I'm getting stuck.  Obviously, I need to work in the assumption that $X$ is a manifold someone in here, but I'm not seeing it yet.
Am I on the right track, or should I scrap it?
Comment: Sorry fot the late question, how to prove that the space $H^1(X,\mathbb{C})$ is finite dimensionel? Thanks.
Answer: Finitely many $\bar{V} \cap U_i$ covers $\bar{V}$, and remember that $U_i$ are disjoint to start with. What can you say about all the $\bar{V} \cap U_j$ that does not show up in your finite subcover?
P.S. You already used that $X$ is a manifold when you say that $U_i$ are open. Connected components in general may not be open.
Comment: Ahhh, thank you.  So, suppose there is some $j$ such that $\overline{V} \cap U_j \neq \emptyset$, with $j \neq 1,\cdots, n$.  Then $x \in \overline{V}$, and since the $\{\overline{V} \cap U_i\}_{i=1}^n$ cover $\overline{V}$, there is some $i=1,\cdots, n$ such that $x \in \overline{V} \cap U_i \cap U_j$.  But the $U_i$ are disjoint, so this is a contradiction.  Gotcha.  And since $V \subseteq \overline{V}$, this means $V$ meets only finitely many of the $U_i$.


Como funcionam as pastas temporárias?

Question: Eu estive hoje me questionando a respeito disso. Tanto em sistemas operacionais Unix como Windows, temos um local específico onde são jogados arquivos temporários de toda espécie.
É óbvio pensar que, se a pasta é temporária, os dados ficarão ali apenas por determinado tempo.
Mas agora surgem várias dúvidas:

Como e quando esses arquivos são removidos? Existe alguma configuração no sistema operacional quanto a isso?
Tem alguma coisa a ver com a reinicialização do sistema? Se for, como fica o caso dos servidores, que geralmente são raramente reiniciados?
Existe alguma forma de assinalar no sistema operacional (pelo menos no Windows e Linux) que outras pastas também serão consideradas temporárias?
Answer: Depende de sistema operacional.

Como e quando esses arquivos são removidos? Existe alguma configuração no sistema operacional quanto a isso?

No Windows não tem algo automático, deve remover manualmente. Limpar o que é temporário deve ser responsabilidade da aplicação. Colocar algo ali só quer dizer que ele pode desaparecer a qualquer momento sem controle da aplicação. Obviamente que se o arquivo estiver em uso ninguém poderá removê-lo.
No Linux depende do lugar onde coloca e da distribuição. No /tmp, embora seja recomendado apagar quando há boot, nada garante que seja feito na sua distribuição. No var/tmp fica o tempo que for necessário até alguma intervenção da aplicação ou do "dono" da máquina, igual ao Windows.
Se não adicionar uma aplicação específica para cuidar disso e sua aplicação não cuidar, em geral ele vai enchendo.
Isto é só uma convenção para não deixar arquivos temporários espalhados para todo lado e você saber que apagando ali se livra deles. Pena que muitos programadores ignoram essa recomendação e espalham arquivos para todo lado.

Tem alguma coisa a ver com a reinicialização do sistema? Se for, como fica o caso dos servidores, que geralmente são raramente reiniciados?

Tem no Linux, mas de qualquer forma é problema seu resolver isso, então pouco importa se é um servidor.

Existe alguma forma de assinalar no sistema operacional (pelo menos no Windows e Linux) que outras pastas também serão consideradas temporárias?

Que eu saiba não tem de forma padrão, mas no Linux sempre pode ser mexido se a pessoa quiser muito e for capacitada. E nem tem importância existir algo assim. O Windows permite mudar o local da pasta.

Como usar esta pasta na minha aplicação?

Esta era a pergunta mais importante que não foi feita em um Q&A de programação.
No Linux é seguro sempre usar /tmp e /var/tmp para colocar seus arquivos temporários.
No Windows o correto é consultar onde a pasta está já que ela pode ser configurada pelo usuário (só pode existir uma), através de API disponibilizada na linguagem que está usando ou pela variável de ambiente TEMP.
Se não o fizer e achar que deve por em outro lugar pelo menos garanta a limpeza deles em qualquer circunstância, mesmo quando a aplicação quebra.
Coloquei no GitHub para referência futura.

Como funcionam as pastas temporárias?


Prove: If $x$ is not a left zero divisor and $xy=1$, then $yx=1$.

Question: Let $R$ be a ring with unity, and let $x,y \in R$ with $xy = 1$. Assume
that $x$ is not a left zero-divisor. Prove that $x$ is a unit.
$$xy = 1$$
$$\begin{gather}
xyx = x \\
xyx - x = 0 \\
x(yx-1) = 0
\end{gather}$$
Since $x$ is not a left zero divisor, $yx-1 = 0$.
Thus $yx=1$.
As $xy=1$ as well, $x$ is a unit.
Is this right?
Comment: Yes, it looks correct.
Comment: Looks good to me as well.
Answer: Your solution is correct.
(I'm posting this CW answer to get this off the unanswered queue.)


Grails package bypassing certificate

Question: I would like to ignore certificate when building my project. I am trying to do somenthing like that.
<code>grails -Dgrails.env=production -Dserver.ssl.enabled=false package --stacktrace
</code>
And I receive the message below. Could anyone help me to ignore certificate while building process is running?
Unzipping /root/.gradle/wrapper/dists/gradle-3.5-bin/daoimhu7k5rlo48ntmxw2ok3e/gradle-3.5-bin.zip to /root/.gradle/wrapper/dists/gradle-3.5-bin/daoimhu7k5rlo48ntmxw2ok3e
3700Set executable permissions for: /root/.gradle/wrapper/dists/gradle-3.5-bin/daoimhu7k5rlo48ntmxw2ok3e/gradle-3.5/bin/gradle
3701FAILURE: Build failed with an exception.
3702* What went wrong:
3703A problem occurred configuring root project 'cmberp'.
3704> Could not resolve all dependencies for configuration ':classpath'.
3705 > Could not resolve org.grails:grails-gradle-plugin:3.3.11.
3706 Required by:
3707 project :
3708 > Could not resolve org.grails:grails-gradle-plugin:3.3.11.
3709 > Could not get resource 'https://repo.grails.org/grails/core/org/grails/grails-gradle-plugin/3.3.11/grails-gradle-plugin-3.3.11.pom'.
3710 > Could not GET 'https://repo.grails.org/grails/core/org/grails/grails-gradle-plugin/3.3.11/grails-gradle-plugin-3.3.11.pom'.
3711 > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
3712 > Could not resolve org.grails.plugins:hibernate5:6.1.12.
3713 Required by:
3714 project :
3715 > Could not resolve org.grails.plugins:hibernate5:6.1.12.
3716 > Could not get resource 'https://repo.grails.org/grails/core/org/grails/plugins/hibernate5/6.1.12/hibernate5-6.1.12.pom'.
3717 > Could not GET 'https://repo.grails.org/grails/core/org/grails/plugins/hibernate5/6.1.12/hibernate5-6.1.12.pom'.
3718 > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
3719 > Could not resolve org.grails.plugins:views-gradle:1.2.9.
3720 Required by:
3721 project :
3722 > Could not resolve org.grails.plugins:views-gradle:1.2.9.
3723 > Could not get resource 'https://repo.grails.org/grails/core/org/grails/plugins/views-gradle/1.2.9/views-gradle-1.2.9.pom'.
3724 > Could not GET 'https://repo.grails.org/grails/core/org/grails/plugins/views-gradle/1.2.9/views-gradle-1.2.9.pom'.
3725 > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
3726 > Could not resolve io.github.robwin:jgitflow-gradle-plugin:0.6.0.
3727 Required by:
3728 project :
3729 > Could not resolve io.github.robwin:jgitflow-gradle-plugin:0.6.0.
3730 > Could not get resource 'https://repo.grails.org/grails/core/io/github/robwin/jgitflow-gradle-plugin/0.6.0/jgitflow-gradle-plugin-0.6.0.pom'.
3731 > Could not GET 'https://repo.grails.org/grails/core/io/github/robwin/jgitflow-gradle-plugin/0.6.0/jgitflow-gradle-plugin-0.6.0.pom'.
3732 > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Comment: Why ignore the certificate, instead of trusting it?  Alternatively, you can reference http://repo.grails.org to connect insecurely, if you're OK with that.  (It would be better to trust the certificate.)
Answer: That was a network problem and it is already resolved.

Grails package bypassing certificate


og_members block & og_nodes block won't display content

Question: OG Version: 7.x-1.x-dev
My problem is that I can't get the og_members block & og_nodes block to show up under a group page.
Breakdown of my process:

A fresh install of D7, necessary modules
Created a new Content Type: Country: Specified as "Group type", "Not a group content type".
Add a new country: "England".
Createt a new Content Type: News: Specified as "Not a group type", "Group content type".
Add a News, title "Hello World", select England in "Group audience".
In Views page, I add block display for og_members, og_nodes. (All use default setting, no modification to the Views)
Assign og_members block, og_nodes block to sidebar left. (Bartik)
I go to "England" page, og_members block not show up, og_nodes block shows me "There is no content in this group."

I am pretty sure that the views setup correctly, as I pass the gid into the live preview, it does show the result. (See screent shot)
But the block just can't show up in a group page. I am guessing in the page, gid not passed to the block or what?
Am I missing any steps?
Thanks in advanced!!
Update: I found the solution by enabling the OG context module.
Answer: og_nodes and og_members did not exist prior to views 3 beta 3's release.  The user must have been using a dev version at this time because I was unable to reproduce this until views beta 3 came out today.


Meaning of drum TAB notation: horizontal line with upward stroke

Question: I came across the following notation which I couldn't find in any guides to drum TAB notation:

It resembles a small x note lying directly on the 2nd stave line from the top (i.e., a D4 in the treble clef), with a mark above it like a tenuto line but rising up at the end like __/
Any ideas what this means?
For audio reference, this score is from "3 Libras" by A Perfect Circle.
Comment: What does it sound like when you listen to the recording at that point?
Comment: @Tim https://youtu.be/EoqXDPbivFs?t=66 it does indeed sound like a ride cymbal.
Answer: It means to play the cymbal (ride, in this case) on its edge, as opposed to on the bell.
As per the drum guides at MIT and at Online Drummer.
From the MIT guide

From the Online Drummer guide
Comment: As an erstwhile drummer, I play ride cymbal on its edge as the usual situation. I'd expect the dots to say otherwise, not the norm.


Show limit converges using Taylor's series (Advanced Calc.)

Question: Question Statement
Using Taylor's series show that
$$ \lim_{t\to \infty}\int_{0}^{t} \frac{x^{2/3}}{e^{x}-1}$$
converges.
Attempt at Solution
I know that from Taylor's expansions, we can expand at $x_{0}=0$
$$ f(x) = f(0) + f_{x}(0)x + \frac{f_{xx}(0)x^{2}}{2} + R_{2}(x)$$
The given function is not defined at $x_{0} =0 \ (f(0))$, so i set $x_{0} = 1$.
I computed the first derivative and the second but then I get a series of constants , which I would then integrate from $0 \to t$ and get
$$= \lim_{t \to \infty} \left(\frac{t}{e-1} + \frac{(e-2)t^{2}}{6(e-1)^{2}} + \frac{(1+e(2e-9))t^{3}}{18(e-1)^3} + \int_{0}^{t} R_{2}(x)\right)$$
From here I'm confused and can't seem to get further.

I also tried initially reformulating the expression as
$$ \lim_{t\to \infty}\int_{0}^{t} x^{2/3} e^{-x} \left(\frac{1}{1-\frac{1}{e^{x}}}\right)$$
$$ = \sum_{k=0}^{\infty} \binom{2/3}{k} (x-1)^{k}\sum_{k=0}^{\infty} \frac{(-x)^{k}}{k!} \sum_{k=0}^{\infty}  \left(\frac{1}{e^{x}}\right)^{k}$$
but with no more success.
Answer: By the Taylor series of the exponential function,
$$
\frac{{x^{2/3} }}{{e^x  - 1}} = \frac{{x^{2/3} }}{{x + O(x^2 )}} = \frac{1}{{x^{1/3} }} + O(x^{2/3} ),
$$
which is integrable at $0$.


What do ellipses of PCA analysis (factoextra) mean?

Question: Biological question: do plants that have been attacked by insects differ in their characteristics from plants that have not been attacked by insects?
Data frame includes six numerical variables describing different plant traits and one categorical defining plant status (with insects/ withouth insects)
To answer this I performed a PCA analysis in R using the "factoextra" package. I plotted individuals with "fviz_pca_ind" function separated by the category "with insects" and "without insects" and included ellipses.
My problem: what does the argument "ellipse.level = 0.68" from "fviz_pca_ind" function mean? Confidence intervals? Standard deviations? Or simply percentage of individuals inside the ellipse?
library(factoextra)
res.pca <- prcomp(PCA2, scale = TRUE)
treat <- as.factor(treat) #categorical variable (with insects, without insects)

fviz_pca_ind(res.pca, pointsize=2, geom="point", palette = c("palegreen3","black") , habillage = treat, addEllipses = TRUE, ellipse.level = 0.68) +
theme_minimal()enter code here

My next question is: what analyses would you recommend me to show whether these two groups are statistically different? (in this case they are not, but anyway) Thanks!
Answer: Welcome to the site AndresD.
I would suggest you instead use the vegan package using the rda function to build your PCA, as this package has the ordihull function that can produce your group centroids - here is a tutorial. The documentation for ordihull is a little clearer than the factoextra package from what I can see and details that the ellipsoid is defined by a 95% confidence interval and you can manually change this if desired. The second reason I point you to vegan is the adonis2 function (don't use adonis, it is deprecated). This allows you to carry out a permutational multivariate analysis of variance (PERMANOVA) that will allow you to test if the two group centroids are statistically different from one another. Essentially this test will take your PCA object and then allow you to test whether the two groups are statistically different in n-dimensional space (i.e. do their traits differ). It does carry with it the assumption of homogeneity of multivariate dispersions, which is analogous to the equality of variance assumption that (univariate) linear models holds; you can test this using the vegan::betadisper function. The data you showed likely violates this assumption though and probably aren't different as you pointed out...
Let me know if anything is unclear.
Answer: One way to answer your questions is to start by adding the corresponding argument indicating what the ellipses are. For example:
ellipse.type = c("confidence")

will made ellipses of confidence intervals and thus, the argument ellipse.level now indicates the confidence interval level set at 0.68. Another option for ellipse type is "convex", which will plot the convex hull.
Another way of plotting individuals and their corresponding ellipses is using fviz_ellipses(), for example:
fviz_ellipses(res.pca, treat,
graph.type = "ggplot", ggtheme = theme_minimal(),
pointsize=2, geom="point", palette = c("palegreen3","black") ,
ellipse.level = 0.95, ellipse.type = c("confidence"))


Somar Valores no AngularJS

Question: Tenho 5 inputs onde entro com alguns valores, porém quando tento fazer a soma o resultado total não é exibido no ultimo input.
HTML:

    Valor 1
    <input type="number" ng-model="var1"> </input>

    Valor 2
    <input type="number" ng-model="var2"> </input>

    Valor 3
    <input type="number" ng-model="var3"> </input>

    Valor 4
    <input type="number" ng-model="var4"> </input>

    Valor 5
    <input type="number" ng-model="var5"> </input>

    Total
    <input type="number" ng-model="total"> </input></input>

Controller:
.controller('Total', function ($state, $scope) {

$scope.var1 = 0;
$scope.var2 = 0;
$scope.var3 = 0;
$scope.var4 = 0;
$scope.var5 = 0;

var total = $scope.var1 + $scope.var2 + $scope.var3 + $scope.var4 + $scope.var5;

$scope.total = total;

})

Como faço pra exibir valor total em um input?
Answer: A afirmação da outra resposta é verdadeira e funciona, porém como alternativa, caso queira colocar o valor na propriedade total, pode ser utilizada uma função auto-executável, como:
$scope.total = (function(){
   $scope.var1 + $scope.var2 + $scope.var3 + $scope.var4 + $scope.var5;
})();

Comment: Eu preciso exibir esse Total no ultimo input.
Answer: Não está funcionando pois você não chama nenhuma ação (função) que faz a soma.
Tente o seguinte:
No seu ultimo input coloque um ng-blur ou ng-click
<input type="number" ng-click="somarValores()" ng-blur="somarValores()" ng-model="var5"> </input>

E no seu Controller:
$scope.somarValores = function(){
    $scope.total = $scope.var1 + $scope.var2 + $scope.var3 + $scope.var4 + $scope.var5;
}

Exemplo funcionando:
http://codepen.io/anon/pen/KdJmwq
OBS: Um trecho do seu html pode apresentar problemas também, não sei como está a estrutura inteira porém reparei que você chama o Controller apenas no final do html. Dessa maneira todas as variáveis declaradas no Controller só são "enxergadas" no final.
Comment: Cara, já estou conseguido somar, mas ele só ta preenchendo o campo total depois q eu coloco o valor em todos os campos... Da uma olhada aqui: http://codepen.io/anon/pen/JYxJEG   eu quero exatamente assim, só quero q ele some cada vez q preencho um campo, sem precisar preencher todos.
Comment: No seu Controller você tem que inicializar a variável com 0 e não " ": http://codepen.io/anon/pen/KdJmwq
Comment: Não posso exibir os números 0 nas input.
Comment: Então você vai ter que mudar um pouco sua lógica. Vai tentando, vou almoçar já volto pra te ajudar
Comment: Tentei algumas coisas mas nenhuma deu certo... aquele link foi o mais perto q eu cheguei haha
Comment: Cara ai eu já n sei se funciona, pois pelo que eu analisei você precisa inicializar a variável como 0. Você quer atualizar em "tempo real" ou seja, ao entrar com um numero ele começa a soma, mas se você não inicializar a variável não vai funcionar
Comment: Aqui está algo mais próximo do que você precisa: http://codepen.io/anon/pen/KdJmwq
Comment: Mas só funciona se você definir todos os numeros
Comment: Baah cara, valeu pela ajuda, vou continuar tentando aqui... Se tiver alguma ideia pode avisa, se eu conseguir também te aviso.
Comment: Tudo bem, boa sorte :D
Comment: Consegui cara: http://codepen.io/anon/pen/JYxJEG
Answer: Se alguém ainda estiver com duvida, está Resolvido: http://codepen.io/anon/pen/JYxJEG.

Somar Valores no AngularJS


Diferença entre Merge() e getInstace() no JPA/Hibernate

Question: Gostaria de saber quando devo utilizar merge() para atualizar o objeto ao invés de alterá-lo através de sua referência.
Exemplo:
Produto p = new Produto();
p.setNome("Bola");
p.setvalor("32);
manager.persist(p);
manager.getTransation().begin();
manager.getTransation().commit();

Atualizando com merge()
Produto p2 = p;
p2.setNome("Bola Editado");
manager.merge(p2);
manager.getTransation().commit();

Atualizando com getInstance()
Produto p2 = manager.getReference(Produto.class, p.getId());
p2.setNome("Bola Editado")
manager.getTransation().begin();
manager.getTransation().commit();

Answer: TL;DR
O merge() recebe um objeto "comum", que não está no contexto de persistência, e copia as propriedades deste objeto para a verdadeira instância da entidade. Use-o quando você não quer recuperar a entidade e alterar seus atributos manualmente.
Objetos vs. Entidades e o funcionamento do JPA
O primeiro passo para compreender melhor como funciona o JPA é entender exatamente como ele trata as entidades e os estados que esses objetos podem assumir.
Para isso, sugiro que leia minha outra resposta sobre o assunto.
Usando o merge
Basicamente, o merge() recebe um objeto criado fora do JPA, seja diretamente no seu código ou em algum processo automático como algum JSON deserializer ou um framework MVC que mapeia o request para um Java Bean.
Ao receber este objeto, o JPA verifica se já existe uma instância no contexto ou então recupera uma a partir da base de dados.
Depois ele pega os valores da instância que você passou e atribui para a instância do contexto de persistência, efetivamente atualizando os dados da entidade verdadeira. Note que ele vai atualizar todos os atributos e não somente os que possuem valor.
Então o método merge() retorna para você a entidade atualizada. Neste ponto, o objeto que você passou para ele pode ser descartado.
Quando usar o getReference()
O getReference() retorna um proxy para uma entidade que está no banco de dados. Os dados não são carregados do banco imediatamente, a não ser a chave primária. Esse proxy funciona como um objeto lazy que só vai carregar os atributos da entidade quando você chamar algum método getter.
Enfim, use esse método quando você quer evitar carregar muitos dados do banco desnecessariamente, como em casos em que você vai usar apenas um ou dois campos de uma entidade apenas se uma determinada condição for satisfeita ou quando você precisar passar uma entidade como parâmetro e possivelmente ela não é usada dentro do método receptor.
Enfim, a vantagem é postergar a transferência de dados que você provavelmente não vai usar. A desvantagem é que, se for usar os dados, o "custo" é maior já que vai ter que fazer mais consultas ao banco.
Sinceramente, nunca vi necessidade real do uso desse método.
Quando usar o find()
O método find() também retorna uma entidade, porém já com os dados carregados, exceto é claro relacionamentos lazy.
Considerações
Para recuperar uma entidade, o método find() quase sempre é o que você vai precisar. Use o find() por padrão e, se tiver problemas de desempenho, então verifique qual outro método pode ajudar.
Para atualizar uma entidade, use o merge() quando você já tem um objeto populado com todos os novos valores que seja gravar no banco.
Para atualizações parciais, use o find() ou getReference() e o respectivo setter da propriedade que deseja atualizar.


Fill missing date-time values in output vector

Question: I performed a unique extraction on my date-time values for extracting unique seconds in my time-series data.
unique_seconds <- unlist(unique(all_secondsDayData))

I have missing values in my output as follows:
(see "2015-12-03 09:51:26")
[1116] "2015-12-03 09:51:24" "2015-12-03 09:51:25" "2015-12-03 09:51:27" "2015-12-03 09:51:28" "2015-12-03 09:51:29"

How do I fill my vector with these missing values?
Do not worry about date because it is one day's data. The issue is filling the vector with missing seconds values.
Comment: `seq(strptime("2015-12-03 09:51:24", format="%Y-%m-%d %H:%M:%S"), strptime("2015-12-03 09:51:27", format="%Y-%m-%d %H:%M:%S"), by=1)` for example ?
Answer: Looks like you just want a regular time sequence by 1 second. You may try using seq.POSIXt:
x <- c("2015-12-03 09:51:24", "2015-12-03 09:51:25", "2015-12-03 09:51:27",
       "2015-12-03 09:51:28", "2015-12-03 09:51:29")

x <- strptime(x, "%Y-%m-%d %H:%M:%S")

RANGE <- range(x)
seq.POSIXt(RANGE[1], RANGE[2], by = 1)

#[1] "2015-12-03 09:51:24 GMT" "2015-12-03 09:51:25 GMT"
#[3] "2015-12-03 09:51:26 GMT" "2015-12-03 09:51:27 GMT"
#[5] "2015-12-03 09:51:28 GMT" "2015-12-03 09:51:29 GMT"

You can read ?seq.POSIXt for specification of by. If it is given as a single number, it is interpreted as "second".


Fundamental Theorem of Calculus for Lebesgue Integrable functions

Question: I am trying to prove the following statement:
If $f$ is Lebesgue integrable on $[a,b]$ and if  $F(x)=\int_{a}^x f(t)dt$
then $′=()$ .. on $[,]$.
If $f$ is Riemann integrable it can be shown using the theorem that -"If $f$ is Riemann integrable, it is discontinuous in the set of measure of zero."
How to prove this statement for non-Riemann integrable functions?
Comment: See https://en.wikipedia.org/wiki/Lebesgue_differentiation_theorem
Answer: This theorem is definitely nontrivial and is at the basis of the theory that was published originally in Lebesgue's dissertation Intégrale, longueur, aire ("Integral, length, area") at the University of Nancy during 1902.
The main idea is to rephrase this statement in terms of measures and, with the help of measure-theoretic machinery, to solve the corresponding "paraphrased" problem with the help of Radon-Nikodym theorem and the notion of absolute continuity of measures. Finally, one goes back to the functional setting and gets the result.
A formal proof needs a bit of work, so I suggest that you consult books like Modern Real Analysis, by Ziemer or Real Analysis: Modern Techniques and Their Applications, by Folland.


Variance of $X + \alpha^\top Y$ where $X$ is a scalar random variable and $Y$ is a random vector

Question: Consider a scalar random variable $X\in\mathbb{R}$, a vector random variable $Y\in\mathbb{R}^n$ and a constant (non-random) vector $\alpha\in\mathbb{R}^n$. I want to compute
$$
\mathbb{V}[X + \alpha^\top Y]
$$
but I can't find any material on this. I have checked here and in various lecture notes.
Attempt
$$
\begin{align}
    \mathbb{V}[X + \alpha^\top Y]
&= \mathbb{V}[X] + \alpha^\top\mathbb{V}[Y]\alpha + 2\text{Cov}(X, Y)\alpha
\end{align}
$$
However things here get confusing because $\mathbb{V}[Y]\in\mathbb{R}^{n\times n}$ and the covariance seems weird. Is it a vector in this context?
$$
\begin{align}
    \text{Cov}(X, Y)
    &= \mathbb{E}[(X - \mathbb{E}[X])(Y - \mathbb{E}[Y])^\top)
\end{align}
$$
where here $X - \mathbb{E}[X]$ is a scalar and $Y - \mathbb{E}[Y]$ is a vector..
Comment: $X+\alpha^\prime Y$ is explicitly a linear combination of random variables with coefficients $1,\alpha_1,\ldots, \alpha_n.$ If it helps, write $Z = (X, Y^\prime)^\prime$ (an $n+1$-vector) and let $\beta = (1,\alpha^\prime)^\prime,$ so that $X+\alpha^\prime Y = \beta^\prime Z$ and go from there.
Answer: You calculation is actually correct.  To clarify, by convention, $Y$ and $\alpha$ are column vectors, so that $\operatorname{Cov}(X, Y) = E[(X - E[X])(Y - E[Y])^\top]$ is a row vector, after multiplying with the column vector $\alpha$, $\operatorname{Cov}(X, Y)\alpha$ becomes a scalar, as expected.


Converting mean deviation to standard deviation

Question: I am using a stock trading platform which only has a mean deviation function. I have to use standard deviation for some calculations and I want to know how we can convert mean deviation to standard deviation. In some websites they have provided this formula
MAD:SD=SQRT (2/pi)

But warned that it is just an approximation? Why it is difficult to convert mean deviation to standard deviation and vice versa?
Answer: The factor of $\sqrt{\frac{2}{\pi}}$ is based on assuming a normal distribution.
If that was a good value to use, this would mean that if you wanted to compute sd from md in large samples you'd multiply by $\sqrt{\frac{\pi}{2}}$
If the data are not close to normal, using that scale factor may not yield a suitable estimate of sample standard deviation.
Considered in terms of sample features, the two respond differently to large and small deviations, so in some samples the ratio of mean deviation (md) to sd may be very close to 1, while in other samples it may be far from 1. [I use md for mean deviation because MAD is often used to stand for median absolute deviation from the median.]
i) consider a sample of 1000 0's and 1000 1's. md/sd $\approx$ 1
ii) consider a sample of one "0", one "1" and 998 "$\frac{_1}{^2}$". md/sd $\approx$ 0.0447
If you were in case (i) and multiplied md by $\sqrt{\frac{\pi}{2}}$ you'd get a number that was 57% too big. If you were in case (ii) and multiplied md by  $\sqrt{\frac{\pi}{2}}$ you'd get a number that was only about 7% as big as it should be.
Mean deviation won't exceed standard deviation, but in some cases it can be quite a lot smaller than it. In particular, if tails are heavier than normal, md/sd might be a good deal smaller than in the normal case.
If you also have other information than the mean deviation, you might be able to approximate it a little better.
Comment: +1. To see where this property comes from, check out the $p$-th central absolute moments section for $p=1$ on the [Wikipedia article](https://en.wikipedia.org/wiki/Normal_distribution).
Answer: Because two sets of data can have the same MAD but different SD. Indeed, this is one of the reasons for using MAD.
For example:
set.seed(123)
x <- rnorm(1000,0,1)
sd(x) #0.99
mad(x) #0.96
y <- rpois(1000,1)
sd(y) #1.00
mad(y)#1.48


Delta Dirac Function

Question: Show that $\delta$, function of Dirac, defined than $\left<{\delta_0,\phi}\right> = \phi(0)$ belongs to $W^{-1,p}(]-1,1[)$ and $\delta_0 \notin L^p(-1,1)$ $\forall p\geq 1$.
How I will be able to start?
Answer: If $u$ is a test function (smooth function with compact support), then
$$|\delta_0(u)|=|u(0)|=\left|\int_{—1}^0u'(t)dt\right|\leq \lVert u'\rVert_p\leq \lVert u\rVert_{W^{1,p}(-1,1)}.$$
By density of test function, we can extend $\delta_0$ to the functions of $W^{1,p}(-1,1)$.
Assume that $\delta_0$ can be represented by $u\in L^p$. Take $\phi_n\in C^{\infty}_0(-1,1)$ such that $\phi_n=1$ on $(-1/2,1/2)$, $\phi_n$ is supported in $(-1/n,1/n)$ and $0\leq \phi_n\leq 1$. Then
$$\int_{(-1,1)}u(t)\phi_n(t)dt=\delta_0(\phi_n)=1.$$
But by the dominated convergence theorem the LHS should converge to $0$ as $n\to +\infty$.
Comment: I know that this question is well done, only a one comment according to my lecture

$$W^{-1,p}(]-1,1[) = \left\{{u\in L^p(\Omega); D^{a}u\in L^p(\Omega) \forall |\alpha|\leq -1}\right\}$$

in ohter words. If $\delta_0 \in W^{-1,p}(]-1,1[)$ then $\delta_0\in L^p(]-1,1[)$. Then exist a condradictory?
Comment: I need show that $\delta_0 \in W^{-1,p}(-1,1)$ but you wrote $\delta_0 \in W^{1,p}(-1,1)$
Comment: How I will be able to prove the linearity of $\delta_0$?
Comment: It's the same as showing that the map $f\mapsto f(0)$ is linear, which is a consequence of the definition of the sum (and the multiplication by a scalar) of functions.
Comment: in your map ... $f$ belong what space?
Comment: The space of test functions.
Comment: understand, and Why $\delta_0(\phi_n)=\phi_n(0)=1$?,
Comment: The first equality is by definition of $\delta_0$ and the fact that $\phi_n$ is a test function. The second one is because $\phi$ is equal to $1$ in a neighborhood of $0$.
Comment: understand the first equality, but in the second $\phi$ is a function? or not?, $\phi$ is a unitary function?
Comment: Sorry, I meant $\phi_n$.

Delta Dirac Function


C: How to read a file (of any format) byte by byte?

Question: I'm attempting to write a code which will read a file byte by byte, of any type/format.
For starters I want to be able to read and write the same file, but I'm having trouble doing that for any file other than text files.
After searching here, I figured that fread/fwrite should work
unsigned char buff;
fopen_s(&input, "input_file_of_any_kind", "r");
fopen_s(&output, "new", "w");
while (!feof(input))
{
    fread(&buff, 1, 1, input);
    fwrite(&buff, 1, 1, output);
}
fclose(input);
fclose(output);

But when I'm trying to "copy" a jpg or pdf file, it reads only a few bytes (out of KB), so I guess my understanding here is flawed. Could you point me to the right direction?
The point of that is to reach the representation of those bytes in bits and manipulate them (and it should work for a file of any size).
Comment: `"r"` -> `"rb"`. On some systems reading a file in text-mode could do some translations that either remove or add bytes, or could mean a premature end-of-file.
Comment: Beyond that, you're going to get a lot closer to epsilon performance if you're really doing this byte at a time with [`getc`](https://en.cppreference.com/w/c/io/fgetc) and [`putc`](https://en.cppreference.com/w/c/io/fputc). And FYI, [`while (!feof(input))` is wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). You're going to end up with a duplicate final byte in your output file. It would/could be circumvented with the right control loop and/or actually validating your IO (which you should be doing anyway) rather than ignoring the function call results.
Comment: Try `"rb"` and `"wb"` mode.
Comment: Use fgetc and fputc.
Comment: "it reads only a few bytes" --> Curious, how was that determined?
Comment: Slightly OT: reading and writing one byte at a time is probably might not be the most efficient way.
Comment: Note that `fopen_s()` is effectively Microsoft-only and therefore non-portable.  And it doesn't actually make your code more secure.  See http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm  Note that when MSVC says `fopen()` is "deprecated", it's pretty much lying to you - [`fopen()` is standard C](https://port70.net/~nsz/c/c11/n1570.html#184.108.40.206) and hasn't been and won't be deprecated.
Answer: To read a file of any size (byte by byte) a simple approach uses fgetc().
Open the files in binary and check results.
// fopen_s(&input, "input_file_of_any_kind", "r");
if (fopen_s(&input, "input_file_of_any_kind", "rb")) {
  ; // Handle error
}

Do not use while (!feof(input)).
int ch;
while ((ch = fgetc(input)) != EOF) {
    fputc(ch, output);
}


Atualizar tabela após Inserir em outra

Question: Tenho uma tabela chamada Consumo, nessa tabela tenho uma coluna Quantidade.
Tenho outra tabela chamada Produto, nessa tabela tenho uma coluna Estoque.
Sempre que um novo consumo for inserido, deve-se escolher um produto e a quantidade que foi consumida daquele produto.
Preciso fazer uma trigger onde a cada consumo feito diminui o estoque do produto escolhido de acordo com a quantidade informada.
Exemplo: Produto 1 tem 10 em estoque. Consumo do Produto 1, 2 quantidades.
Atualizar o estoque do produto 1 para 8.

Não cheguei a conclusão de nenhum código. Obrigado.
Comment: Esta trabalhando com qual bando de dados? MySQL?
Comment: Procure por Trigger
Comment: uma `trigger` não garante que o valor vá ser mesmo atualizado, me parece um processo transacional, já pensou em atualizar tudo dentro de uma `transaction` para garantir?
Comment: Estou usando o Sql Server
Comment: Está trabalhando com qual Servidor? C#?
Comment: Não cheguei a ver transaction
Comment: Estou trabalhando com C#, porém preciso disso no Sql Server
Comment: Ou você trabalha com Trigger, ou você implementa a solução em C#, nem tem outra alternativa.
Comment: o certo nessa situação seria trigger, maaaaaaas, faz uma tabela de estoque cara... simplifica muito
Comment: tabela: `movimento_estoque`
...
`produto | valor | quantidade | saldo_anterior | saldo_atual`

nessa tabela só faz inserts, nenhum update. Assim você mantém todo o histórico de movimentação;
Comment: Consegui resolver com trigger, vou postar o código
Comment: @RicardoPontual, acho que por padrão os triggers tem uma transação implícita. Se der erro no update, o insert também não seria executado
Comment: interessante @DiegoRafaelSouza vou dar uma pesquisada, valeu
Answer: CREATE or ALTER TRIGGER DiminuirEstoque
ON Consumo
AFTER INSERT
AS
BEGIN
    UPDATE PRODUTO SET ESTOQUE = ESTOQUE - C.QUANTIDADE
    FROM INSERTED C JOIN PRODUTO P ON C.CODIGOPRODUTO = P.CODIGO
END

Acho que fica melhor assim
Answer: Consegui resolver com a seguinte Trigger
CREATE or ALTER TRIGGER DiminuirEstoque
ON Consumo
AFTER INSERT
AS
BEGIN
    declare @qtdEstoque int
    select @qtdEstoque = Quantidade from Inserted
    declare @codigoProduto int
    select @codigoProduto = CodigoProduto from Inserted
    Update Produto set Estoque = (Select Estoque from Produto where Codigo = @codigoProduto) - @qtdEstoque where Codigo = @codigoProduto
END

Atualizar tabela após Inserir em outra


Trying to sort by count of association in rails

Question: I have a User model and a PullRequest model - a user has many PullRequests and a PullRequest belongs to User. I have a counter column for keeping track of the total number of PullRequests a user has - but I want to be able to find how many a user has after a specified date. I do this using:
  has_many :pull_requests_as_creator_sprint, -> {where("merged_at >= ?", "2015-10-22")}, class_name:'PullRequest', foreign_key: 'creator_id', dependent: :destroy

but how can I use this to sort my data in the pull request controller?
Currently I have @team_members = User.order(sort_column + " " + sort_direction, 'pull_requests_created_count DESC').includes(:pull_requests_as_merger_sprint, :pull_requests_as_creator_sprint)

which displays by total created count - but I'd like to order by created by since
  has_many :pull_requests_as_creator, class_name:'PullRequest', foreign_key: 'creator_id', dependent: :destroy
  has_many :pull_requests_as_creator_sprint, -> {where("merged_at >= ?", "2015-10-22")}, class_name:'PullRequest', foreign_key: 'creator_id', dependent: :destroy
  has_many :pull_requests_as_merger, class_name:'PullRequest', foreign_key: 'merger_id', dependent: :destroy
  has_many :pull_requests_as_merger_sprint, -> {where("merged_at >= ?", "2015-10-22")}, class_name:'PullRequest', foreign_key: 'merger_id', dependent: :destroy

Is my user model - The :pull_requests_as_creator/merger relations are fine, they just use a counter cache. But I want to be able to also sort my data by pull_requests since a date.
  belongs_to :creator, class_name: 'User'
  belongs_to :merger, class_name: 'User'

Is my user model.
Answer: Something like this should work:
User.select('users.id, count(pull_requests.id) AS pull_requests_count').joins(:pull_requests).where('pull_requests.created_at >= ?', your_date_here).group('users.id').order('pull_requests_count')

You can make it a scope, so u can have easier acces to it.
User.select('users.id, count(pull_requests.id) AS pull_requests_count').joins(:pull_requests_as_merger).where('pull_requests.created_at >= ?', your_date_here).group('users.id').order('pull_requests_count')

or
User.select('users.id, count(pull_requests.id) AS pull_requests_count').joins(:pull_requests_as_merger).where('pull_requests_as_merger.created_at >= ?', your_date_here).group('users.id').order('pull_requests_count')

Comment: My association is actually pull_requests_as_creator - (I have merger also) - and not just pull_requests. When I tried to update this to take that into account it didn't work .. any ideas?
Comment: And what exacly happens? It throws out an error, or returns a wrong result?
Comment: It errors on missing table - I've never used joins before so I think I changed too many things and somethings should be table name and some should be association?

To clarify:

My table is pull_requests - my associations are user has many pull_requests_as_creator and user has_many pull_requests_as_merger
Comment: I'm a little confused now. Can you provide me your models, what have you used, and full error you get?
Comment: Sorry - I've updated the post - I think what you're suggesting is going to work, I just cant seem to implement it :/
Comment: Sorry for long time. I've had to think about it. I think you should use your association name as an argument for joins, and the rest should be like I typed. If this won't work, try renaming it also in the where()

I've edited my answer with possible solutions.


How to know the tempo when it is not indicated

Question: I own a copy of Luis Milan's Six Pavanes for guitar but, contrary to what I expect to find on any music sheet, there is no tempo indication at the beginning of any of them.
According to Wikipedia a Pavane was a "fast dance that became slower over time" so that only adds to my confusion, should these then be played slow or fast? And what does that mean? If slow should they be played "Lento" or "Adagio"? If fast should they be played "Andante" or "Allegro"?
Thank you.
Comment: It depends on if the composer included tempo markings or not or if it's just the specific typesetter. Looking at other versions or listening to recordings should help if it's the latter.
Answer: Getting slower over time is what it did. Maybe a hundred years or so! It started off as a not-slow dance, and ended up as a majestic swing, slow in nature. Not actually what you thought!
If no tempo marks are shown, then the player has to resort to deciding how fast or slow he wants to play it. He can please himself, and choose a tempo he likes. Maybe play an early pavane faster, and a later written one slower?
Comment: Also you could look at the videos on YouTube which will give you an idea of the tempo that other guitarists think is appropriate


Newton's method for regression analysis without second derivative

Question: In regression analysis, instead of gradient descent, Newton's method can be used for minimizing the cost function.  However, in Newton's method, we need to calculate second derivative too.
For example, to minimize a cost function $F(x)$, we need to find $x_0$ such that $F'(x0) = 0$, which means that we need to find the zeroes of $F'(x)$.
And for that, we can use Newton's method:
$$
x_1 = x_0 - \frac{F'(x_0)}{F"(x_0)}
$$
In the case of linear regression, the cost function is:
$$
        J = [h(x) - y]^2
$$
In the case of logistic regression, the cost function is:
$$
        J = y \log(h(x)) + (1 - y)(1 - \log(h(x)))
$$
In both the cases, since the cost function's minimum value is $0$, why can't we directly find the zeroes of the function using Newton's method, thus avoiding the calculation of the second derivative?
Comment: It is not the case that the minimum value of the cost function will always be zero in linear or nonlinear regression.  Usually, it is not, but will be if all the "equations", i.e., data points, are entirely consistent - but this is not usually the case in regression analysis.
Comment: http://homes.soic.indiana.edu/classes/spring2012/csci/b553-hauserk/newtons_method.pdf
Comment: @MarkL.Stone How does Newton's method behave on a function which doesn't have any roots? Won't it just output the `x` where `F(x)` is nearest to the X-axis (i.e the minima of `F(x)`)?
Comment: Not necessarily. It depends on the function and the implementation of Newtons' method. You could end up far away with the algorithm reporting "failed".
Comment: @MarkL.Stone Could you give any example for such a case? (not doubting your opinion, just curious!)
Answer: As mentioned in the comments, the reason is that the cost functions mentioned might not have any zeroes at all, in which case Newton's method will fail to find the minima.
I have created a visualization to show this:

As you can see, the method is not converging at all for this particular case.
The code used to create this is stored here.
Adding the relevant portion of the code here itself for convenience:
newton.m:
<code>% Dummy statement to avoid writing function in the first line and making it a 'function file' instead of a 'script file'
1;

% The function to find zeroes of.
% The function is specifically chosen to not have any zeroes
% so as to show the weakness of Newton's method.
function y = f(x)
    y = (x - 5).^2 + 5;
endfunction

% The derivative of f(x)
function y = fd(x)
    y = 2 * (x - 5);
endfunction

% Initial guess
x0 = 1.5;

% Max number of iterations
itermax = 20;

% Epsilon value initialized to a very large value
eps = 1;

% A vector for storing the history of the approximate roots
xvals = x0;

% Number of iterations done
itercount = 0;

% Required for plotting f(x) vs x
x = linspace(0, 10, 100);

% Create a figure whose output is not rendered on the screen
% Not working currently; supposedly a bug in Octave
% A workaround is to use gnuplot instead of qt - `graphics_toolkit gnuplot`
% but this is very slow.
% Uncomment the following to activate the feature once the bug is fixed
% figure('Visible','off');

% The main loop
while eps >= 1e-5 && itercount <= itermax
    % x1 = New value of root
    % x0 = Current value of root
    x1 = x0 - f(x0) / fd(x0);

    % Plot f(x)
    % Plot a line passing through points [x0, f(x0)] and [x1, 0]
    % Plot a line passing through points [x1, 0] and [x1, f(x1)]
    % Plot a line passing through points [x0, 0] and [x0, f(x0)]
    plot(x, f(x), ";f(x);", [x0 x1], [f(x0) 0], "-r;f'(x);", [x1 x1], [0 f(x1)], ":r", [x0 x0], [0 f(x0)], ":r");
    title('f(x) = (x-5)^2 + 5');

    % Set limits for the axes shown in the plots
    xlim([0 10]);
    ylim([0 30]);

    % Label the two consecutive zeroes on the X-axis
    text(x0, -2, sprintf('x%d', itercount), 'color', 'red');
    text(x1, -2, sprintf('x%d', itercount+1), 'color', 'red');

    % Print the plot to a file
    filename = sprintf('output/%05d.jpg', itercount);
    print(filename)

    % Append the zero to the array of zeroes calculated so far
    xvals = [xvals; x1];

    % Calculate the epsilon value
    eps = abs(x1-x0);

    x0 = x1;
    itercount = itercount+1;
end

% Print the result of the iteration
xvals
f_zero = f(xvals(end))
eps
itercount
</code>
Comment: You appear to have confused a cost function with its derivative.  In practically all statistical applications, the cost function has a *minimum*: that is what is being sought, not a zero!
Comment: @whuber I know the difference between the cost function and its derivative. The problem is that this method would work only if there exists a hypothesis which perfectly fits the data (i.e. the zero of the cost function exists), as in that case finding the minimum and finding the zero of the cost function would have been the same thing (as cost functions are not designed to output negative values).
Comment: Your comment appears to continue the confusion between a cost function and its derivative.  The OP is applying Newton's method to $F^\prime$, not $F$ itself. It will therefore fail for nondifferentiable functions or when minima occur on a boundary, but those do not appear to be the possibilities you are investigating here.
Comment: @whuber I am the OP!
Comment: @whuber and I'm talking about applying Newton's method on the cost function itself rather than its derivative, as I earlier thought that Newton's method could find the (approximate) minima of a function even if it didn't have any zeroes. But, this is not the case as I've shown through the visualization.
Comment: But finding a zero of a cost function is pointless: as you have noted, it is usually not the case that a cost function has a zero.  It is difficult to see how your demonstration is related to the question that has been asked in this thread.
Comment: Actually, @AnmolSinghJaggi 's question seems reasonable to me. Often cost functions are of the forms he wrote down in his question and then, considering that the class of neural networks used for the task can often approximate a very wide range of functions if enough neurons and layers are used, one would expect that one can often find a function (member of the class / a weight configuration) that minimizes the objective almost perfectly. I wonder if one could show more rigorously how the size of the model class and the failing of the application of newton's method to the loss are related.


Descobrir se um site está ou não no ar

Question: Existe alguma função em PHP para descobrir se um endereço IP(entende-se por site) esta no ar ou não?
Encontrei essa função na WEB mas ela não me satisfez.... ela demora muito pra carregar.

function curl_info($url){
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_HEADER, 1);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );

    $content = curl_exec( $ch );
    $info = curl_getinfo( $ch );

    return $info;
}

$site = 'http://www.locaweb.com.br';
$info = curl_info( $site );
if( $info['http_code']==200 ) {
    echo ''.$site . ' - está no ar!!
';
} else {
    echo ''.$site . ' - está fora do ar
';
}

Comment: Como assim se um IP está online? Você quer verificar oque exatamente? Um serviço ou usuário?
Comment: Pelo que eu percebi quer verificar se um site está "online" certo? Se for esse o caso acho que essa é mesmo a melhor solução. Demora muito? Quanto tempo em segundos? Ah mais uma coisa o site pode estar online mas na página estar "em manutenção", não sei se é relevante, mas fica a ressalva.
Comment: pior que demora rs, por exemplo, testando 'https://www.google.com.br' essa função leva 21 segundos para terminar... não sei se eu estou fazendo alguma coisa errada, ou se isso está certo
Comment: A solução poderia ser em Javascript?
Comment: poderia ser sim, mas acho difícil criar uma solução desse tipo
Comment: Pergunta rápida: não seria mais fácil usar um serviço como o Pingdom? (a não ser que você queira, de fato, desenvolver um script para seu propósito)
Comment: não não, o proposito é outro....
Answer: 1) Usando fsockopen, atente-se para o formato da URL
if( fsockopen( 'www.locaweb.com.br' , 80 , $errno , $errstr , 30 ) ){
    echo 'site online!';
} else {
    echo 'site offline.';
}

2) Usando checkdnsrr: Verifica os registros de DNS que correspondem a um determinado nome de host ou o endereço IP Internet.
checkdnsrr( 'google.com' ) // TRUE
checkdnsrr( 'yaruuu.com' ) // FALSE

3) Usando curl
$ch = curl_init('http://www.locaweb.com.br');
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if( $httpcode >= 200 && $httpcode < 300 ){
    echo 'site online!';
} else {
    echo 'site offline.';
}

No caso de CURL, a URL http://www.locaweb.com.br retorna um status 301 de redirecionamento para a URL http://www.locaweb.com.br/default.html, podemos aceitar o site como ONLINE. No exemplo acima ele não considera status de redirecionamento como ONLINE, mas você pode alterar e aceitar estes casos:
status redirect:
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found', // 1.1
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
// 306 is deprecated but reserved
307 => 'Temporary Redirect',

Cabe a você definir o status que vai ser válido como ONLINE.
Answer: Tinha o mesmo problema e alterei o script.
A "responsabilidade" de obter dados da página passou para outra função.
Função para verificar apenas se o link informado retorna alguma resposta:
//verifica se o link informado retorna alguma resposta
function isUrl($_sUrl){
    $bRet = false;

    $cl = curl_init($_sUrl);
    curl_setopt($cl,CURLOPT_VERBOSE, true);
    curl_setopt($cl,CURLOPT_CONNECTTIMEOUT,1);
    curl_setopt($cl,CURLOPT_HEADER,true);
    curl_setopt($cl,CURLOPT_NOBODY,true);
    curl_setopt($cl,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($cl,CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($cl);
    curl_close($cl);
    if($response) $bRet = true;

    return $bRet;
}

No meu caso, verifico se existe algum vídeo na página:
function getVideo($_sUrl){
    $sVideo = '';
    //necessário a extensão php_openssl activa para ulr's com https
    $html = new DOMDocument();
    @$html->loadHTML(file_get_contents($_sUrl));
    $aMeta = $html->getElementsByTagName('meta');
    foreach($html->getElementsByTagName('meta') as $meta) {
        if($meta->getAttribute('property')=='og:video'){
            $sVideo = $meta->getAttribute('content');
            break;
        }
    }

    return $sVideo;
 }

Para utilizar o código acima:
$sUrl = 'https://www.youtube.com/watch?v=OZ5gVkSjC8k';
if(isUrl($sUrl))
    $sVideo = getVideo($sUrl);

Comment: funcionou não mano...
Usei assim:
$sUrl = 'https://www.google.com.br/';
isUrl($sUrl);

E não me da nenhum retorno =x
Comment: @MarceloBonifazio você tem que adaptar a sua necessidade, veja o exemplo que postei, verifica primeiro se existe alguma resposta do servidor (função isUrl) e depois procura pela meta tag 'og:video' (função getVideo), que no caso do google.com.br não existe, logo o retorno da função getVideo é vazio.
Comment: @MarceloBonifazio a função isUrl retorna true/false, logo você deve fazer um "if", por exemplo, echo isUrl('sua_url') ? "online" : "offline";
Answer: Não sou expert na parte de Web, mas acredito que se você executar um Get no endereço e retornar com sucesso, o endereço está "on line"

var urlValida = '/echo/html/';
var urlInvalida =  '/NaoExiste/html/';

$.ajax({
    type: 'GET',
    url: urlValida,
    success: function (data) {
        alert(urlValida + ' OnLine');
    }
}).error( function () {
        alert(urlValida + 'OffLine');
});

$.ajax({
    type: 'GET',
    url: urlInvalida,
    success: function (data) {
        alert(urlInvalida + ' OnLine');
    }
}).error( function () {
        alert(urlInvalida + 'OffLine');
});

O código pode ser testado neste exemplo no jsFiddle
Comment: @MarceloBonifazio Mas foi isso que eu fiz, estou desconsiderando os dados retornados. Apenas estou validando se houve ou não sucesso na chamada remota. Eu pensei em usar HEAD ou invés de GET mas não sei se todo servidor HTTP responde a HEAD. Veja o exemplo do JSFiddle, só não pude usar URLs reais pois existe bloqueio, mas se vc rodar o código na sua página, com as urls postadas o resultado será provavelmente o mesmo
Comment: Acho que voce não entendeu velho kk
Não quero procurar arquivos dentro do meu projeto e etc.... quero verificar sites externos, sites de outros servidores, tipo o comando ping do cmd
Comment: for example... ping www.google.com.br me retorna que os pacotes foram enviados e retornaram com sucesso, ou seja, o site está 'enxergavel', online
Comment: Bom, nesse seu exemplo, var urlValida = 'www.google.com.br';
Daria online correto?
Comment: Sim, mas fora do JSFiddle por ele não permitir chamadas externas. e `http://www.googlelalalalala.com.br` daria offline

Descobrir se um site está ou não no ar


Show the ideal $(x-2,x+3)\subset\mathbb{Z}[x]$ is prime but not principal

Question: Observe the isomorphism
$$
\mathbb{Z}[x]/(x-2,x+3)\cong\big(\mathbb{Z}[x]/(x-2)\big)/(x+3).
$$
Since $x+3$ is irreducible modulo $x-2$, the RHS of the above isomorphism is an integral domain (since irreducible polynomial generates prime ideal). Thus the LHS is an integral domain, so $(x-2,x+3)$ is a prime ideal. Is this right?
For the part about not being principal, assume $(x-2,x+3)=(p(x))$ for some $p(x)\in\mathbb{Z}[x]$. This means $p(x)$ is a common divisor of both $x-2$ and $x+3$. But $\gcd(x-2,x+3)=1$, so $p(x)=1$. However, this means $(p(x))=\mathbb{Z}[x]$, and since $1\not\in(x-2,x+3)$, we know $(x-2,x+3)\not=\mathbb{Z}[x]$. Thus the ideal cannot be generated by a single polynomial. Is this correct?
Comment: You need to justify that $1\not\in(x-2,x+3)$.
Answer: The quotient ring is indeed a field (it's isomorphic to $\mathbb{F}_{5}$). If you take the quotient with a principal ideal in this ring you can never obtain a field.
Comment: There's a lot of room for improvement in your Answer.  In its present form it provides only a couple of conclusory remarks without argument or other justification.  While it does not say anything wrong, it fails to prove the claims.


Transposing jazz standard 'Tune up' question

Question: I am a novice jazz pianist. My teacher had me learn tune up in its original key (D major) and memorize it with just melody on the right hand and shell voicings in the left. Now he wants me to play it in 2 other keys, Eb major and A major.
I'm trying to figure out the best approach to do this, because I know the next assignment will be to be fluent in playing this in all 12 major keys.
What are the recommended approaches here? Should I always be thinking of the melodies pitches in terms of the key I'm in, for example, the first few bars being:
P5, P4, m2,  M2, M3?
Or should I be thinking in terms of the phrase I'm in, given the the first 12 bars are all 2 5 1 patterns?
Or am I overthinking this entirely?
Answer: I would just comment this but I cannot do that yet because of my recent registration. My vote for rochard's answer also wasn't shown because of this.
But to just add something maybe valuable, I'd say that not only pay attention to the chord progression, but when you are also playing the melody in the RH you think in terms not only in what degree of your scale you are in, but also what degree is in relation to the chord being played in that bar. Is it the 9th of the chord? Is it the 3rd?
In terms of rithm, pay attention to strong or weak beat, as this will give you an idea of the main most important notes, and following the idea of Richard's answer on [not loosing the overall flow] of the main melodic construction. Is it a passing note?, Is an anticipation note? Is it a real chord note?
Comment: FYI I think this info is worthy of being an answer so I'm glad you were forced into not leaving it as a comment. Welcome!
Answer: You're not overthinking this at all, it's a great question!
I do not recommend thinking in terms of the intervals that you gave; that ruins the sense of large context and the overall flow in the music, and your performance will often come across as stilted and disconnected.
Instead, try to find larger patterns. The good news is that you already did: this chart is just a succession of three ii--V--I patterns, each one a whole step below the previous! This means that you have the following ii--V--I patterns for each transposition of the piece:

In D: D, C, Bb
In Eb: Eb, Db, Cb (=B)
In A: A, G, F

I recommend separating the hands first; make sure you can play the harmonies in the LH before adding in the melody in the RH (assuming that's how you have it orchestrated).
Then you're just transposing the melodies themselves. I recommend thinking in terms of scale degrees: the opening three measures is 5--4--b2--n2--3. You might think this is the same as your intervals from earlier, but it's different because this way shows how they all connect in a given key; the intervals from earlier could have changed keys every beat.
Of course, you'll use the same process for the final phrase.
You mentioned you'll probably eventually transpose it to all twelve keys---you're probably right! So get that ii--V--I progression in the LH fluent in all twelve major keys, and then get that opening 5--4--b2--n2--3 melodic line fluent in all twelve major keys, too, and before you know it you can play Tune Up in any key you want!
Comment: But keep in mind that it's just plain going to be a slow process at the start. But like with anything, your transposition skills will become more fluent the more you do it!
Comment: This makes sense when I am in the ii V I phrases, but what scale should I be thinking in when I'm beyond that?
Comment: My vote is to take a similar approach: know the chord changes (whether in Roman numerals or something else) and add the melody once you've transposed the chords.
Comment: I guess the more tactical follow up here is - with the E-7, F7, BbM7, A7 phrase - I'm not sure how to evaluate what roman numerals apply to that - do I Just make it up for myself, or should I be thinking of this relative to the key of the song (ii, III, bVI, V)?
Comment: I don't follow your  ii-V-I patterns . In D won't it be Em-A-D, etc.?
Comment: @tarun - those last 4 bars are a sort of turnaround, and meantime the key's modulated from (original) D, into Bb. There has to be a way to return to D for the repeat, so chromatically, the Em moves to F, then V-I to Bb, and chromatically down to A (the V of D). I'd think in those terms, the reason being, at that point the tune isn't actually in the original key, so when you get to that line in, say, Eb, it'll be Fm-F#7-B7-Bb7 for the turnaround. Thinking in the original key will probably mess you up, although your teacher may expect this, but it can't be that helpful, from my point of view.
Comment: @tarun - I've found several conflicting chord charts, and the last comment was based on a possibly simplified, spurious one. I'll dig out the real book, which is going to be the definitive version, and re-comment!
Comment: @tarun, you can think about the beginning of that turnaround in a similar way as Coltrane changes (e.g., Countdown)--you start with a ii-V-I in DΔ (Emin) but it quickly moves down a major 3rd to BbΔ (F7-BbΔ-Eb7). You can also think in terms of each step: start with the minor ii chord, move up a half step to a V7 chord, resolve to its relative I chord, and then move to the IV7 chord.


Text Classification Naive Bayes not working as expected

Question: I am trying to use Naive Bayes to perform text classification. I have two classes A and B. I am mainly interested in identifying class A.
Description about the dataset:

Some of the text contents that belong to class A can also be found in class B.
But some of the text contents are only found in class A.
The entire dataset is pretty small.

Training Set:
Number of Datapoints for class A: 275
Number of Datapoints for class B: 691
Testing Set:
Number of Datapoints for class A: 238
Number of Datapoints for class B: 403

I am using sci-kit learn's multinomialNB to perform the text classification.
The result that I got after running the Naive Bayes classifier on my test set:
Number of datapoints for class A (True Positive): 0
Number of datapoints for class B (True Negative): 401
Number of datapoints for class A (False Positive): 2
Number of datapoints for class B (False Negative): 238
EDIT:
I would like to know how can I improve the classification result of the aforementioned dataset?
Comment: What actualy is your question...?
Comment: @Unhandledexception edited my question?
Answer: You can try using a different classifier like logistic regression. Logistic regression is easier to regularize and that will help you avoid the problem of always predicting the same class.


how can I fix this..in select query

Question: this is a select query...
   $q = "SELECT
        tcs.tutor_id AS tid,
        tcs.category_id AS cid,
        tcs.subject_id AS sid,
        GROUP_CONCAT( DISTINCT s.subjects SEPARATOR ', ') AS subjects,
        t.tutor_name AS tname,
        t.tutor_code AS tcode,
        DATE_FORMAT(t.registration_date, '%b %D, %Y') AS date,
        t.qualification AS qualifi,
        GROUP_CONCAT( DISTINCT o.option_name SEPARATOR ', ') AS tutor_option,
        timg.image_name AS img,
        city_name AS city,
        d.district_name AS district
   FROM tutor_category_subject as tcs
        INNER JOIN subject AS s ON tcs.subject_id = s.subject_id
        INNER JOIN tutor_option AS toption ON toption.tutor_id = tcs.tutor_id
        INNER JOIN options AS o ON toption.option_id = o.option_id
        INNER JOIN tutors AS t ON tcs.tutor_id = t.tutor_id
        INNER JOIN address ON address.address_id = t.address_id
        INNER JOIN city ON city.city_id = address.city_id
        INNER JOIN district AS d ON d.district_id = city.district_id
        LEFT JOIN tutor_images AS timg ON timg.tutor_id = tcs.tutor_id AND timg.image_type = 'profile'
   WHERE s.subjects LIKE '%$subject%'
   GROUP BY tcs.tutor_id";

this query is working now.. now I found a problem. it is..... so many subject may have to one particular tutor. I need to select all the subject that pertaining to a tutor with searching keyword to display with search result. In this query searching keyword is '$subject'.
This query only selecting subjects to the tutor similar to the given keyword. For an example if a user give a keyword like 'business' query selecting subjects to that tutor like 'business studies, business accounting., etc only'. so I need to select other subjects too through this query.. can anybody help me?
thank you.
Comment: Not sure if I got it right but check out `distinct`. Otherwise if you only want subjects with the keyword of one tutor add `&& tutor = id` to get only results for this tutor.
Answer: Well I'm not MySQL guru, but I think you don't need to select
 tcs.category_id AS cid,
 tcs.subject_id AS sid,

and you also need to use distinct keyword
SELECT distinct
    tcs.tutor_id AS tid,
    GROUP_CONCAT( DISTINCT s.subjects SEPARATOR ', ') AS subjects,
    t.tutor_name AS tname,
    t.tutor_code AS tcode,
    DATE_FORMAT(t.registration_date, '%b %D, %Y') AS date,
    t.qualification AS qualifi,
    GROUP_CONCAT( DISTINCT o.option_name SEPARATOR ', ') AS tutor_option,
    timg.image_name AS img,
    city_name AS city,
    d.district_name AS district
FROM tutor_category_subject as tcs
    INNER JOIN subject AS s ON tcs.subject_id = s.subject_id
    INNER JOIN tutor_option AS toption ON toption.tutor_id = tcs.tutor_id
    INNER JOIN options AS o ON toption.option_id = o.option_id
    INNER JOIN tutors AS t ON tcs.tutor_id = t.tutor_id
    INNER JOIN address ON address.address_id = t.address_id
    INNER JOIN city ON city.city_id = address.city_id
    INNER JOIN district AS d ON d.district_id = city.district_id
    LEFT JOIN tutor_images AS timg ON timg.tutor_id = tcs.tutor_id AND timg.image_type = 'profile'
WHERE s.subjects LIKE '%$subject%'
GROUP BY tcs.tutor_id

how can I fix this..in select query


Rules- How can I copy the formatted text in one field to another?

Question: I need to move the values of a field (long text and summary) to another field (long text and  summary).  I am trying to do this with Rules and VBO.
I have fetched nodes A and B, and I want to set the value of the field in B to the value of the field in A.
The challenge is that I can't use the Set a data value action to simply set B to A.  I can use Rules to create a text variable and get the value from A that way, but I still can't set that text variable as the value (Rules requires a formatted text variable).  However, if I try to create a formatted text variable, I can't set the value of the Long text and summary field as the value.
I have the two nodes available in Rules and they both have fields of type Long text and summary.  I just want to set the value of B to the value of A.  How can I do this?
Answer: I figured it out-- I needed to add :value after the body field, since the field value contains the summary, text format, and text value.
So for example, instead of profile:field-myfield, use profile:field-myfield:value.


How to calculate expected value given its probability?

Question: I am weak in Math and was stuck on this problem:

A project has the following risks: 20% probability of a 14-day delay
  in the receipt of customer requirements; 10% probability of a 21-day
  delay in the procurement process; 50% probability the integration will
  take 14 days longer. What is the expected time value of these events?
A. 11.9 days
B. 35.8 days
C. 49 days
D. Seven days

Can someone please guide me on how I can solve it?
Comment: Hint: $E[X+Y+Z]=E[X]+E[Y]+E[Z]$
Answer: Conceptually, expected value is an average value, weighted by its various probabilities. Computationally, this ends up being* a sum of [values $\times$ probabilities of being those values]. So, if we call the receipt delay by $R$, then $R$ is either $14$ or $0$, and it is those things with probabilities $0.2$ and $0.8$, respectively; hence,
$$\mathbb E[R] = 14 \cdot 0.2 + 0 \cdot 0.8 = 2.8.$$
Similarly, you can compute the expected procurement delay ($P$) and integration delay ($I$). As @JMoravitz noted, the total delay is $\mathbb E[P + R + I] = \mathbb E[P] + \mathbb E[R] + \mathbb E[I]$. Can you take it from here?
*Note: this is true for discrete variables such as the type encountered here, but not true for all random variables. If you had something like a normally-distributed variable, then it doesn't assume particular values at all, and this formulation of its expected value doesn't make much sense. If that comment made no sense to you, don't worry about it; it may be a technicality that's beyond what you need to consider.
Comment: Thank you! I now understand from your explanation `E[R]=14⋅0.2+0⋅0.8=2.8.`. The answer is 11.9 days.


Is to possible to translate any time signature to any time signature?

Question: Is to possible to translate any time signature to any time signature without even slight change in music?
Sometimes it is so hard to translate some time signatures to each other but finally is it possible?
Answer: Probably.  But it can get a bit silly.  All these bars sound the same, but you wouldn't want to continue this sort of notation for too long!
Answer: No! it's possible to sort of translate 2/2 into 4/4, but even then there will be a subtle change in emphasis of certain notes, depending where they are in a bar. It's certainly not possible to tranlate 3/4 into 6/8, even though they both contain the equivalent of 3 crotchets/6 quavers. 12/8 is often written as 4/4, with a note at the top explaining the feel, but that's hardly translation.
By doubling the value of every note, it's possible to change the bottom number in a time sig. from, say, 8 to 4, if that's what you mean.
Answer: At the very least you could translate one three time into another type of three time. So for instance...

Into.

You can also change the nature of a certain type of time. Or in other change a passage from Simple Time to Compound Time.
So for Instance take the next simple duple time passage and change it into a compound duple time.
Comment: Your last examples can't sound the same - there's a different number of dots.


How to define a ring $R$ and two non-zero polynomials $a(x), b(x) \in R[x]$

Question: such that the degree of their product is NOT equal to the sum of their degrees?
Could someone please help with this question?
Thank you.
Answer: For two polynomials, the product is given by: $$(a_nx^n + ,\dots,+a_0)(b_mx^n + , \dots,+ b_0) = a_nb_mx^{m+n} + \Big( \text{lower degree terms} \Big) $$
So the only way for the product of these polynomials to have a degree different than their sum is for $a_nb_m$ to be $0$.
One way to do this is to choose a ring that has zero-divisors. Examples have been given in other answers. Another way to do this is to simply let one of the polynomials be the $0$-polynomial
Answer: In $\mathbb{Z}/4\mathbb{Z}[X]$, consider the polynomials $a=b=2X$. Each of them is of degree $1$ but their product is $4X^2=0X^2=0$.
Comment: Thank you Suzet for your help! I understand now the idea, but do I understand correctly that the ring is $Z_{4}\left[x\right]$? I'm not sure about the notation..
Comment: I guess it is $\mathbb{Z}_4$, actually I am not used to this latter notation. In France at least, it is very common to denote explicitly $\mathbb{Z}/4\mathbb{Z}$, which really is the quotient of $\mathbb{Z}$ by the subgroup $\mathbb{4Z}$. It is a cyclic abelian group with four elements $0,1,2,3$.


Can I stay on Drupal 7 forever?

Question: I've been using Drupal 8 for a while now and while it's not bad, it does slow down development a bit, as the whole framework is more strict. Which is a good thing to some, but I know of many people like me, who prefer having the freedom of easily creating modules, versus having to set up the new folder structure etc.
So my question is, can one survive without upgrading for the foreseeable future? And what is the longest time one can realistically go without upgrading?
Comment: [Backdrop CMS](https://backdropcms.org) is a fork of Drupal 7 and is very similar to Drupal 7. Most Drupal modules should work on Backdrop or be easier to port than porting to Drupal 8. It's not Drupal but maybe worth checking out. :)
Comment: Drupal has always maintained 2 branches, so 7 will likely be halted once Drupal 9 arrives. Hoewever the New 3 number version model of Drupal 8 should slow the need for Drupal 9 as API breaking changes can be introduced as part of the second version number. So you should be able to use 7 for quite some time to come. Perhaps even for longer if people step up to offer long term support.
Comment: Sure you can ***survive*** without upgrading Drupal ... think of all those people who have never ***heard*** about Drupal at all ... Maybe you should reword that part of your question ...
Comment: Uh, you can always switch to Backdrop CMS - a fork of Drupal 7 with a solid track record: https://backdropcms.org
Comment: Wasn't _exactly_ the question, or this answer needs to be expanded on.
Answer: IF the current version of Drupal is working out for you and you don't need more features added than you can stick around on 7 for a long time.
The problem is that D7 will not receive any feature updates and most modules will not be updated for D7 aswell.
It is hard to say the exact date of when D7 will not be supported anymore but most likely in 3-4 years.
but the bug/security fixes will continue till the end of this year most likely.
source: https://www.ostraining.com/blog/drupal/drupal-7-end-of-life/

Can I stay on Drupal 7 forever?


Showing lockscreen widget to control application only when the application needs it

Question: I would like to add lockscreen controls for my app similar to what netflix or youtube does when casting to a chromecast device.
Do I do this with a lockscreen widget that I add and remove on demand or is there a different method?
Thank you.
Answer: The proper way to add a lock screen controller is to use the RemoteControlClient. There are limitations to what you can do there, both in terms of the functionality and availability based on the Android version. If you are running Android version 4.1+, then the required functionality is there (check out the Google Play Music to see how it can look like). Give that a try and if run into issues, come back here and post your issue(s).
Comment: Thanks for the info. I have noticed Netflix will sometimes show full screen controls and sometimes above the unlock wheels. Is that all done with the RemoteControlClient?
Comment: RemoteControlClient implementation has changed between JB and KitKat: in JB, it is a small area and in KitKat it is a full screen background image. Netflix, on the other hand, uses a different mechanism which I would call a "hack"; we encourage folks to stay away from any hacks and just rely on the RCC for lock screen implementations.
Comment: @AliNaddaf How do we show the lockscreen image using the new MediaSessionCompat class? http://stackoverflow.com/questions/38752191/chromecast-sender-v2-7-0-lockscreen-image


Get list of times from a start time by 5 minutes

Question: Let's say I have an "end time" which is now - 20 minutes
Sys.time()-20
"2015-09-17 13:06:45 CST"

and I would like to generate a vector that is time buckets from a "starttime" = "2015-09-17 10:00:00 CST"  to the end time in 5-minute bucket so the result I am looking for is:
10:05:00
10:10:00
10:15:00
....
....
11:00:00
11:05:00
11:10:00
....
....
13:00:00
13:05:00

do you know how to do that?
Comment: `seq(start, end, by = "5 mins")` ? Or `format(seq(start, end, by = "5 mins"), "%X")` if just need the time. (assuming `start` and `end` are of class `POSIXct` of course)
Answer: To close this up, seq is a generic function which has a seq.POSIXct method and thus can understand time terminology in its by statement.
Lets say those are your starttime and endtime
(endtime <- Sys.time())
# [1] "2015-09-18 12:38:34 IDT"
(starttime <- endtime - 20*60)
# [1] "2015-09-18 12:18:34 IDT"

You can simply specify by = "5 mins" directly in seq
seq(starttime, endtime, by = "5 mins")
# [1] "2015-09-18 12:18:34 IDT" "2015-09-18 12:23:34 IDT" "2015-09-18 12:28:34 IDT" "2015-09-18 12:33:34 IDT"
# [5] "2015-09-18 12:38:34 IDT"

Or for exact output, you can modify the output using the format function
format(seq(starttime, endtime, by = "5 mins"), "%X")
# [1] "12:18:34" "12:23:34" "12:28:34" "12:33:34" "12:38:34"

JFI, R doesn't have a time class and those this is just a character string. You can check out the chron package if you want to use such class.