Mensagem JavaScript não esta aparecendo no input

Question: Bom dia. Quero fazer com que o resultado da variavel cpf seja exibido no input 'recebe'.
praticando.php

    <meta charset="UTF-8"/>

    <fieldset style="width:50%; margin: 0px auto; ">
        <legend>Colocando PONTO no CPF</legend>
        <form id="form">
            CPF
            <input type="number" name="cpf" placeholder="Sem pontos e traço" required />
            <input type="submit" value="ENVIAR" name="button"/>

            <input name='recebe' id="recebe" readonly style='width:100%;'/>
        </form>
    </fieldset>

validaPraticando.php
$cpf = $_POST['cpf'];

if(strlen($cpf) == 11){
    $pegaCpf = substr($cpf,0,3).'.'.substr($cpf,3,3).'.'.substr($cpf,6,3).'-'.substr($cpf,9,2);
    echo json_encode($pegaCpf);
}else{
    echo json_encode("CPF Invalido");
}

pratica.js
$(documento.ready(function(){
$("#form").on("submit",function(e){

    e.preventDefault();
    var data = $("#form").serialize();
    $.ajax({
        url: "validaPraticando.php",
        data: data,
        method: "POST",
        dataType: "json",
        success: function(data){
            $("#retorno").val(data);
        },
        error: function(){
            alert("erro na requisição");
        }
    });
  });
});

Comment: Só complementando o que o @CaiqueRomero falou, no lugar do alert(data) coloque console.log(data) e aperte f12 para ver o resultado no console, porque se for um objeto ou um array não vai mostrar os valores usando o alert.
Comment: altere $("#retorno").val(data);     por   $("#recebe").val(data);
Comment: Verifica no navegador o que acontece quando chama a página validaPraticando.php, no success da um alert(data); só para verificar se está retornando corretamente.
Comment: Não há nenhum elemento com o id "retorno" no seu html.
Comment: O navegador esta alertando esse erro "Uncaught SyntaxError: missing ) after argument list". Referente a linha 23 do arquivo JavaScript. Essa linha é a ultima que contem "});".
Answer: Atualizando aqui a resposta, se você quer usar máscara de cpf, use esse exemplo, junto com minha dica debaixo e ao digitar, já fará tudo automaticamente:
Máscaras com jQuery: Telefone, CPF e CNPJ
Mas se você só quer validar a quantidade de caracteres, basta usar um
minlength="11" e maxlength='14' dentro do seu input ficando:
<input type="number" name="cpf" minlength="11" `maxlength='14' placeholder="Sem pontos e traço" required />

Por último, se você quiser ver se o cpf é válido de verdade, pode usar uma função já pronta, fácil de achar em varios sites como esse:
Como validar CPF no lado do cliente com script?
ou
http://www.devmedia.com.br/validar-cpf-com-javascript/23916
Answer: Você está atribuindo o valor a um elemento que não existe retorno.
Verifique se a página retorna a informação desejada e corrija o campo onde ela será atribuída.
Mude de
success: function(data){
   $("#retorno").val(data);
},

Para:
success: function(data){
       //console.log() ou alert() apenas para verificar o que retornou.
       console.log(data);
       $("#recebe").val(data);
    },

Comment: Fiz isso Caique Romero. Apertando F12 informa um erro no arquivo JavaScript, mostra a mensagem, "Uncaught SyntaxError: missing ) after argument list". Referente a linha 23 do arquivo JavaScript. Essa linha é a ultima que contem "});"


Expose the user form into a page

Question: I've been thinking for a user-friendly navigation into my website.
I wanted to exposed the user form into a page where they can just easily update their information. I've installed the module profile 2 and added 3 types of profile (Personal Data, Withdrawal Form and Drawing Records), these 3 types of form I want to expose in one page.
Can it be just embedded into a views or do I need to use hook_form_alter? Please help... Thank you...
Answer: Not exactly sure what you want here. But i think i understood that you have 3 profile types defined in profile2 and want to expose these to anonymous users, so that they can sign up?
If this is indeed the case, then i would reccomend you to take a look at the profile2 registration path module
https://www.drupal.org/project/profile2_regpath
This module allows you to setup a direct menu path to a user registration form that shows the profile types you select
Answer: Do you really need 3 different profiles? For me it looks like you can have one profile with fields divided to 3 set of different field Groups using field group module
With your current approach of having 3 different profiles form on one page might be multiple forms module will be of some help to you.

Expose the user form into a page


Angular and PouchDBFind plugin

Question: I have an angular application in which I want to use PouchDB with the PouchDBFind plugin.
I've already gotten PouchDB to work. But I can't figure out how I use the PouchDB Plugin.
Example database setup:
constructor() {
    this.db = new PouchDB('exampleDb');
    this.db.createIndex({
        index: {fields: ['number', 'name']}
    }).catch(error => {
        console.log(error);
    });
}

I always get this error:
ERROR Error: Uncaught (in promise): TypeError: this.db.createIndex is not a function
TypeError: this.db.createIndex is not a function

This is how my import statements are:
import * as PouchDB from 'pouchdb';
import * as PouchFind from 'pouchdb-find';
PouchDB.plugin(PouchFind);

I don't get any errors here.
I've already read about another import alternative, but this does not work:
import PouchDB from 'pouchdb';
import PouchFind from 'pouchdb-find';

I get this error:
"pouchdb-find" has no default export

I have installed the typings.
So here are my package.json dependencies:
"dependencies": {
    "@types/pouchdb": "6.1.1",
    "@types/pouchdb-find": "^0.10.1",
    "pouchdb": "^6.2.0",
    "pouchdb-find": "^6.3.4"
},

So how do I get the PouchDBFind plugin to work?
If any more information are required, please notice me.
Thanks in advance!
Edit:
After locking the versions to...
"pouchdb": "6.3.4",
"pouchdb-find": "6.3.4",

... I get the following warning after the webpack compilation:
WARNING in ./src/app/services/example-db/example-db.service.ts
17:8-22 "export 'plugin' (imported as 'PouchDB') was not found in 'pouchdb'

And in the browser console:
ERROR Error: Uncaught (in promise): TypeError: __WEBPACK_IMPORTED_MODULE_2_pouchdb__.plugin is not a function
TypeError: __WEBPACK_IMPORTED_MODULE_2_pouchdb__.plugin is not a function

When I comment the PouchDB.plugin(PouchFind) line, the warning is gone but the error in the console remains. It just says that it doesn't have a constructor.
Edit: It is an angular-cli project.
Answer: Can you lock your versions to ...
"pouchdb": "6.3.4",
"pouchdb-find": "6.3.4"

... and try again with the following?
import PouchFind from 'pouchdb-find';
import PouchDB from 'pouchdb-browser';

PouchDB.plugin(PouchFind);

Comment: I tried those imports and im getting a compiler warning which stops the app from starting: **"export 'plugin' (imported as 'PouchDB') was not found in 'pouchdb-browser'**
Comment: Thanks for your answer! I have updated my questions. And i still have to import like the following:
import * as PouchDB from 'pouchdb'. import PouchDB from 'pouchdb' says that there is no default export
Comment: After uninstall the typings and reinstall pouchdb and pouchdb-find, I could import it as you suggested and everythings working. Thanks!
Comment: thanks you very much! this issue has already been bothering me for days 2 weeks ago - now I finally got my app running again :)

Angular and PouchDBFind plugin


Drupal View 3 / CiviCRM integration - block update depends on user authorization

Question: All,
In my CiviCRM installation, I support both Individual Contacts and Organization Contacts. For the Drupal site, there is a block based on a view that exposes some information about Organization Contacts. This view is configured with a Global: Random sort criteria in order to expose three different Organization on each page visit.
When I am logged into the site (as an Authenticated User or Administrator), the block works properly. When I am not logged into the site, the block does not update. Just to be clear: When logged in, reloading the same page results in three different Organization Contacts being displayed. When not logged in, the same three Organization Contacts are displayed each time.
The issue seems to be tied to the cache. When I cleared the Drupal caches, the Organization Contacts for the non-logged in user changed (but then remained the same as described above).
Would you please suggest a fix for this problem. Thank you!
Comment: Obviously one could just "turn caching off", but that's not necessarily a good idea. How do you know that your servers can handle the increased load? How much extra loading time are you willing to accept, etc. There are a number of things that must be considered to "suggest a fix for this problem".
Answer: I'm not sure if there's a way around this. Drupal will cache the output of Views to anonymous users, as it does for most pages. Drupal rarely caches content for authenticated users. On top of that, your host may be using a reverse-cache such as Varnish, since it greatly improves performance of Drupal sites for anonymous users.
A workaround could be to reduce the cache time of content. First try by changing the cache settings on the specific View, and if not, try the global setting in /admin/config/development/performance.
However, assuming that the list of contacts you are displaying is a sort of "randomly featured members" type of block, if your cache expires every 15 or 30 minutes, it's still usually pretty sufficient for that type of requirement, unless you have a really high traffic site and you must rotate faster.
If you do have a very high traffic site, I would probably load the block dynamically with Ajax to avoid killing the cache (and cache that block in a more efficient cache such as memcached, which a short expiration time of perhaps 5 minutes).
Answer:
The issue seems to be tied to the cache.

You are perfectly right, it is. It may be block cache, but more probably it is page cache or even Boost. Instead of various workarounds like short cache or DRUPAL_NO_CACHE that can be ignored by Boost, Varnish etc, I prefer different way:

I create an empty place for data that is supposed to be random. This means that page may be cached, no problem.
Using AJAX, I fill it with random data. Page is already rendered, user sees no delay. I use some nice effect for first portion of data to appear.
Additional bonus: Using timer, I can shuffle data even if user is not reloading my page.
Answer: In hook_block_info I would try using https://api.drupal.org/api/drupal/includes%21common.inc/constant/DRUPAL_NO_CACHE/7


Difference between time signatures

Question: What is the difference between 4/4 and 8/8 time? 4/4 means 4 crotchets in a bar and 8/8 means 8 quavers in a bar, but 4 crotchets mean 8 quavers.
Is it just a question of notation? If so, why isn't all music X/2, since we can divide the semibreve up to sixteen times (up to the semiquaver)?
Comment: Does this answer your question? https://music.stackexchange.com/questions/568/is-there-any-real-world-difference-between-time-signatures-such-as-4-4-and-8-8/571
Answer: 8/8 is sometimes used for music where the 8th-note groupings are consistently not 2+2+2+2 - i.e. NOT a traditional 'four in the bar'.
There's also 2/2, for when the half-note is the main beat. In marches and show tunes notating this as 'Cut Time' is more usual.
Even, very occasionally, 1/1.

Difference between time signatures


Alternative to DBs for storing audit logs?

Question: I'm currently developing a system that is used for generating verification codes. The system authenticates a user, sends them a code, stores it locally, then at some later point receives the code from the user, after which point the code is spent and deleted from the system
The original proposal was to create this system using an SQL database, however this use case just screams Kafka, and since these codes have a very short duration (they expire in 30 seconds, which means that they must be spent almost immediately) it only makes sense to have producers and consumers that create and consume events that hold these codes.
However, the issue is that all events must be logged, i.e. upon code consumption/expiration something must be written in the audit log. Also, any attempt to use an invalid code must be logged as well. It seems like a waste to have a fully fledged database and then use it to have one AUDIT_LOG table in it.
Since we're using Spring boot we'd like to use some plug-and-play solution that can be easily interfaced with. I've seen suggestions of using Kafka itself to store audit logs, but we need long term persistence and Kafka doesn't seem ideal for that. Using a no-SQL DBs was also suggested, and I've seen some promising append-only solutions.
Do you folks have anything to recommend here?
Comment: so you can just compress them and store it in some local storage as well but question is who is going to review/use these audit logs and whether they will need any interface/UI or some tool to view it ? based on these questions your storage requirement will changes and also it depends where your server is sitting ?  on cloud or some on-prim/dedicated cluster and if it can connect to any local storage seamlessly ...
Comment: the db choice totally depends on for how long you need to store these logs and size of audit log record. if its very simple structure then you can go with sql , if its complex json like structure go with no-sql obviously but choice of DB is again depends on cost that you want to spend and how important these audit logs are.

you can also dump these audit logs to some file system , compress it at end of day and upload it to some cold storage like S3 or Azur Blob
Comment: @prasannajoshi

The thing is that I'm looking for a way to sidestep the need for a database entirely. S3 and Azur Blob sound nice, I would however prefer an offline solution that is stored locally.
Comment: @prasannajoshi The service will be running on our machines, this is what I mean by "local". So ideally it is some small DB-like system that doesn't offer the full functionality of SQL and no-SQL databases but is good enough for storing simple audit logs, and doesn't come with overhead and maintenance costs of traditional databases.

Due to relative simplicity of this data I would assume that querying it and getting data back in say json format would be readable enough. I also assume that it is possible to export it to txt/xls.
Comment: not sure if its local then are you even care much , just dump to any file format and use editor or ms office
Answer: According to it's home page kafka is for

data pipelines, streaming analytics, data integration, and mission-critical applications

But you stated that an important functionality of your application is persistent storage of structured data. So it's highly doubtable whether kafka is a good long term fit for this purpose if that purpose isn't advocated by kafka itself.
Also keep in mind that there is probably more to your application than just the use cases. Maybe at some point reporting functionality is required. Than you are probably way better of leveraging a reporting product that probably a lot of people already know or have worked with than reinventing all of that on top of kafka (even though streaming analytics is a use case for kafka, but it probably is way lesser known than for example an sql reporting tool).
Comment: @MrLinjak You can write Kafka logs to S3/Azure/HDFS. Kafka was originally created with this exact use case (for Hadoop, specifically)
Comment: Maybe I wasn't clear, audit logs must be persisted, data that is required for the application to run has a lifetime measured in seconds. I did point out that Kafka isn't a perfect solution for storing audit logs in a persistent way.

It is highly unlikely that any additional functionality will be added on top.
Answer:
original proposal was to create this system using an SQL database

Use both? Kafka Connect can write to JDBC databases from Kafka topics. This way, you don't need to write JDBC Clients within your Java code, and non-Java clients can also send data to the same Kafka topic since the protocol is generic TCP, not specific to your database.
If that SQL database doesn't work, you can still consume the same Kafka topic to a different system (Elasticsearch works great for log analysis, as does HDFS or S3 for larger datasets). Since you mention "offline" systems, then MinIO is a self-hosted, S3 compatible option.
Comment: Using both is also an option.

Elasticsearch sounds like it might be the perfect solution here actually, funny that I didn't think of it before. Thanks!


Proving formulas for $\cos(nx)$ and $\sin(nx)$

Question: How do I prove the following formulas?

Let $n \in \mathbb{N}, x \in \mathbb{R}$. Prove that:
$$\cos(nx)=\sum_{j=0}^{[n/2]} (-1)^j {n \choose 2j} (\cos x)^{n-2j} (\sin x)^{2j}$$
$$\sin(nx)=\sum_{j=0}^{[(n-1)/2]} (-1)^j {n \choose 2j+1} (\cos x)^{n-2j-1} (\sin x)^{2j+1}$$
Comment: Can you use $\cos\theta +i\sin\theta=e^{i\theta}$? If so, expanding $(\cos x+i\sin x)^n$ using the Binomial Theorem will do the job.
Comment: Otherwise, induction on $n$ and addition formulas.
Comment: Explicit hint: $$(\cos n x+ \sin n x) = e^{n i x} = \left( e^{i x} \right)^n = (\cos x+ i \sin x)^n .$$ Now apply the binomial theorem, and then separate out the real and imaginary parts.
Comment: @Kevin: If you want to give an inductive proof (i.e. the hard way), you need two items. The first is the Addition Laws for sine and cosine. The other is (essentially) the Binomial Theorem. The key observation there is that $\binom{n+1}{k}=\binom{n}{k-1}+\binom{n}{k}$.
Comment: Thanks, I'm trying induction. But now I come to the point $\cos(kx)\cos(x)-\sin(kx)\sin(x)$ and I need to prove that that formula equals $\sum_{j=0}^{[(k+1)/2]} (-1)^j {k+1 \choose 2j} cos(x)^{k+1-2j} sin(x)^2j$, but how? That $\sin(kx)$ won't fit in here, will it?
Comment: Let me suggest you try @André's hint.
Comment: But how? Then you have to write $cos(nx)$ in terms of $cos(\alpha)$ and $i sin(\alpha)$ in order to apply the Binomial Theorem?
Comment: Where did your $\alpha$ come from? In any event, $\cos\,nx=\Re\exp(inx)$; you can apply that after expanding out $(\cos\,x+i\sin\,x)^n$.
Comment: Ah :), thanks! That will do the job I guess ;)!
Comment: I gave that suggestion in case you did not know about the Euler formula that André suggested.
Answer: Since $n\in\mathbb{N}$ and $x\in\mathbb{R}$, the we can start a derivation for both at once using DeMoivre's formula and Binomial Theorem as @André Nicolas says:
$$
\cos(nx)+i\sin(nx)
=e^{inx}
=(\cos x+i\sin x)^n
=\sum_{k=0}^{n}i^k\binom{n}{k}\cos^{n-k}x\sin^{k}x
$$
Next we must observe that even and odd $k\in\{0,1,\dots,n\}$ give rise to the real and imaginary part, respectively, and can be parametrized by $k=2j$ for $0 \leq j \leq [\frac{n}{2}]$ and by $k=2j+1$ for $0 \leq j \leq [\frac{n-1}{2}]$.
Comment: Thanks, but the only thing I don't get is $j \le [\frac{n-1}{2}]$. $j$ must loop through all odd parts, so I thought it must loop untill $[\frac{n+1}{2}]$?
Comment: For odd $k=2j+1\leq n$ (with $j\in\mathbb{Z}$), the inequality implies (requires) that $j\leq\frac{n-1}{2}$. However the highest such $k$ occurs for $j=[\frac{n-1}{2}]$ (rounding the fraction down when $n$ is even).
Comment: is $[\cdot]$ the nearest integer function or the ceiling function?
Comment: clathratus: the square bracket $\left[\cdot\right]$ notation refers to the "floor" or "greatest integer" function (less than or equal to its argument), which truncates any fractional part and moves non-integers to the left on the number line (and is thus asymmetric, not an odd function).


Don't know where 404 error is coming from

Question: Don't know where this 404 error "sites/all/modules/lightbox2/images/blank.gif" is coming from. It's on everypage on www.lostinthesmoke.com. Can't find the reference to it in the page source. I don't know if its Drupal or CloudFlare. CloudFlare says its Drupal or my server. I cleared caches everywhere. I had lightbox2 installed a couple months ago but not on this fresh install. I use this domain to learn and test on. It started showing last night.
Comment: Did you clone the site from a previous one?
Comment: no, I just started a new ec2 and downloaded drupal through drush about a week ago. i starting to think its cloudflare when i access my site through my ec2 ip, http://188.8.131.52/ i don't get the errors.
Answer: If you go into inspector, you can see:
<code><object data="http://www.lostinthesmoke.com/sites/all/modules/lightbox2/images/blank.gif" width="0" style="position: absolute; left: -9999px; "></object>
</code>
is being added at the very bottom of your page.  Why?  I dunno, but it's there :)  The fact that it doesn't show up in "view source" suggests it's being added via javascript on page load.
Why isn't it finding blank.gif?  Again, I dunno.  It's here in my lightbox2 directory, so, perhaps your installation has been corrupted and thinks it is still installed.
Comment: Jimajamma, Thanks for the advice it helped. Justin from CloudFlare found the issue, it had something to do with their preloader feature.
Comment: quite welcome, glad I could poke around and help out.
Comment: Sometimes ftp corrupts images


Proving convergence of a linear combination of sequences

Question: Suppose $(a_n)$ and $(b_n)$ are converging sequences. I want to show that the sequence $(c_n)$ defined by $c_n = 3a_n - 7b_n$ also converges.
My attempt:
Suppose $a_n \rightarrow a$ and $b_n\rightarrow b$. Let $\epsilon_1$, $\epsilon_2 > 0$ be arbitrary but fixed. Then there exists integers $N_1$, $N_2\in \mathbb N$ such that
if $n\geq N_1$, then $|a_n - a| < \epsilon_1$ and if $n\geq N_2$, then $|b_n - b| < \epsilon_2$.
Now let $\epsilon > 0$ be arbitrary but fixed. I want to find some $\delta > 0$ and some $N\in\mathbb N$ such that $n\geq N$ implies $|3a_n - 7b_n| < \delta$.
So
\begin{align}
|3a_n - 7b_n| &= |3a_n - 7b_n - 3a + 3a - 7b + 7b| \\ &\leq |3a_n - 3a| + |7b_n - 7b| + |3a + 7b| \\ &= 3|a_n - a| + 7|b_n - b| + |3a+ 7b| \\ &< 3\epsilon_1 + 7\epsilon_2 + |3a+7b|\end{align}
And this is where I'm stuck.
Comment: If you are talking about sequences, you don't want $\delta$, only $N$. So you want to show for any $\epsilon > 0$ there is a $N(\epsilon)$ such that if $n > N(\epsilon)$ then $|(3a_n-7b_n)-(3a-7b)| < \epsilon$. Write this as $|(3(a_n-a)-7(b_n-b)| < \epsilon$ and you are close to being done.
Answer: You have some correct ideas but you do not want to show that $|3a_{n}-7b_{n}|<\delta$. This would effectively mean that the limit of $c_{n}$ is zero. Instead what you might guess is that $\lim_{n\to \infty}c_{n} = 3a-7b$. This would be shown if for every $\epsilon >0$ you can find a $N\in \mathbb{N}$ such that for all $n\geq N$
$$|c_{n}-(3a-7b)| = |(3a_{n}-7b_{n}) - (3a-7b)|<\epsilon.$$
Can you take it from here?
PS. It is equally difficult but more useuful prove linearity of limit whenever they exist.


How to stylize a form to make it REALLY FREAKING BIG

Question: I want to make the default size of the input fields and button on my form 3X larger than normal as well as the text that appears inside the input fields be 3X larger than the default.
I've seen this done before but I'll be damned if I can even find any code to get me started.
Comment: http://getthiscrazyoffer.com/hiringnational/ the form appears toward the bottom of this page. I want it to be nice and BIG so people notice it.
Comment: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Styling_HTML_forms
Comment: yeah I saw that page already, not much help
Answer: To make the input fields and buttons bigger, you will need to use CSS Selectors to carry this out, I'll give you a quick example on a basic form:
HTML:
<form ID="Form" action="Contact.php" method="post">

     <input type="Text" name="FirstName" placeholder="First Name">
     <input type="Text" name="Surname" placeholder="Surname">

     <input type="submit" value="Submit" name="Submit">
</form>

CSS:
input[name=FirstName] {
    font-family: Arial;
    font-size: 16px;
    width: 300px;
    height: 150px;
    font-weight: bold;
}

input[name=Surname] {
    font-family: Arial;
    font-size: 16px;
    width: 300px;
    height: 150px;
    font-weight: bold;
}

input[type=submit] {
    width: 300px;
    height: 300px;
    font-family: Arial;
    font-size: 16px;
    background: #DF0101; /* red */
    box-shadow: #6E7849 1px 1px 10px;
    color: white;
}

Here is a jsfiddle.net example of what I have just done, all the widths and heights etc can then be modified to suit your preference in the CSS stylesheet.
http://jsfiddle.net/tduagdnt/


Trying to use eval to check for a perl module

Question:
Possible Duplicate:
How can I check if I have a Perl module before using it?

I'd like to eval a use statement similar to this: eval {use $foo;} but am having trouble with the correct syntax. I've tried various combinations of string interpolation, but the eval always succeeds even for a module that does not exist. Can someone give me hand with this one?
Comment: I'm not sure how `eval` is succeeding; I get a syntax error when using a variable with `use`. From `perldoc -f use`: "[use Module LIST] is exactly equivalent to BEGIN { require Module; import Module LIST; } except that Module *must* be a bare word."
Comment: Define "eval always succeeds".
Answer: The idiom you are looking for is:
eval "use $module; 1" or ... ;

eval "use $module; 1" or warn "$module is not available: $@";
eval "use $module; 1" or die "This script requires $module";
eval "use $module; 1" or $module_available = 0;

eval "always succeeds" in the sense that program execution will continue no matter what code is evaluated -- that's really the whole point of an eval statement. If the evaluated string contained errors -- run time or compile time -- the return value of the eval call is undef and the special variable $@ will be set with an appropriate error message.
The use statement, even when successful, does not return a value. That's why this idiom includes the "; 1" at the end.
Comment: Thanks, I just worked my way to this before checking if someone had submitted an answer.
Answer: use is a keyword that is processed during compilation, as is mentioned in the comments, it does require you to use bareword arguments. That is, no variables.
Now, I can't get an eval { use $foo } to even compile, because it causes a syntax error, so the script is never run. I'm not sure what you mean exactly by "always succeeds", unless you mean the opposite: "always fails".


Proof of: $f_{n}^{2} = f_{n-1}f_{n+1}+(-1)^{n+1}$

Question: So I'm going over some examples  of recursion and Fibonacci Sequences for my quiz tomorrow and I'm a bit lost after a certain point.
Prove $f_{n}^{2} = f_{n-1}f_{n+1}+(-1)^{n+1}$ $n\geq 2$
Basis Step: P(2)
$f_{2}^{2} = f_{2-1}f_{2+1}+(-1)^{n+1}$
$(1)^{2} = f_{1}f_{3}+(-1)^{3}$
$(1)^{2} = (1)(2)+(-1)$
$1 = 1$
Induction Step: Assume P(n) is true, Prove P(n+1), that is, show: $f_{n+1}^{2} = f_{n}(f_{n}+f_{n+1})+(-1)^{(n+2)}$
$$\begin{align}
f_{n}f_{n+2}+(-1)^{n+2} & = f_{n}(f_{n+1}+f_{n})+(-1)^{n+2} \\
 & = f_{n}f_{n+1}+f_{n}^{2}+(-1)^{n+2} \\
 & = f_{n}f_{n+1}+[f_{n-1}f_{n+1}+(-1)^{n+1}]+(-1)^{n+2} \\
\end{align}$$
What do I do after this step? I'm a bit lost...
Comment: It seems like you started with A=B and ended up showing that A=B. Try assuming the hypothesis P(n), and start developing the left hand side of P(n+1). $f_{n+1}^{2} = f_{n+1}(f_n+f_{n-1})= f_{n+1}f_n + f_{n+1}f_{n-1}$ and now use the hypothesis to replace the second term. A little algebra and you are done!
Comment: @Nocturne When you say "hypothesis" I presume you're referring to the given equation (the one used in the basis step) but how can you replace the second term when you don't have $(-1)^{n+1}$ to complete it?
Answer: In your inductive step you started out by assuming
$$f_{n+1}^2=f_nf_{n+2}+(-1)^{n+2}\ .$$
But this is what you are trying to prove, so your argument, even if "successful", will be circular and therefore wrong.
A better way would be to start with the RHS only of this equation and prove it equals the LHS.  You could begin
$$f_nf_{n+2}+(-1)^{n+2}=f_n(f_{n+1}+f_n)+(-1)^{n+2}\ .$$
See if you can take it from here.  Remember that at some stage you will have to use the assumed formula for $f_n^2$.
Comment: @ChantryCargill what's funny is that I knew that equaled zero but had NO idea what that meant. I think it's time I took a break.  Thank you and David both! Really appreciate it.
Comment: So I've reached $f_{n}f_{n+2}+(-1)^{n+2} = f_{n}f_{n+1}+f_{n-1}f_{n+1}+(-1)^{n+1}+(-1)^{n+2}$ and have no idea what to do again
Comment: @TaiM. $(-1)^{n + 1} + (-1)^{n + 2} = ?$. Now what happens if you factor out $f_{n+1}$?


Programmatically pass parameters to Apache Solr integrated with Search API

Question: I'm currently trying to enable spellcheck results with the search api. If I visit my apache solr server directly with http://myserver:8983/solr/d8/select?q=goood+worksd&spellcheck=true and provide the keywords and set spellcheck to true in the url parameters
I receive expected results

{   "response":{"numFound":0,"start":0,"docs":[]   },   "spellcheck":{
      "suggestions":[
        "goood",{
          "numFound":1,
          "startOffset":0,
          "endOffset":5,
          "suggestion":["good"]},
        "worksd",{
          "numFound":1,
          "startOffset":6,
          "endOffset":12,
          "suggestion":["worked"]}]}}

In the response I can see the spellcheck information I need in the spellcheck section.
However when I set the options programmatically before doing the query with the search api I don't receive any of this information.
<code>    $index_id = 'default_solr_index';
    $index = \Drupal\search_api\Entity\Index::load($index_id);
    $query = $index->query();
    $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
        ->createInstance('terms');
    $parse_mode->setConjunction('AND');
    $query->setParseMode($parse_mode);
    $query->keys($search_terms);
    $query->setFulltextFields(['title', 'body_field_parse', 'type','field_description','name','body','field_title','field_summary']);
    $query->addCondition('status', 1);
    $query->sort('search_api_relevance', 'DESC');
    $query->setOption('spellcheck','true');
    $executed_query = $query->execute();
    var_dump($executed_query->getAllExtraData());
</code>
When I var_dump($executed_query->getAllExtraData()) all I get is

{ ["search_api_solr_response"]=> array(1) { ["response"]=> array(4) {
  ["numFound"]=> int(0) ["start"]=> int(0) ["maxScore"]=> float(0)
  ["docs"]=> array(0) { } } } }

I've done all kinds of variations giving true instead of 'true' and adding other options like
<code>$query->setOption('spellcheck','true');
$query->setOption('spellcheck.build','true');
$query->setOption('search_api_spellcheck','true');
$query->setOption('spellcheck.extendedResults','true');
</code>
But nothing seems to work. I saw a spellcheck search api module someone posted but I couldn't get it to work and it seemed to do things very similar to how I'm doing it now. Is there a way to pass these parameters to my query to my apache solr? Or is my method correct and getAllExtraData not the proper way to get this information back?
Answer: After digging deep into the search_api_solr module I found a spot where it's applying options to the solr parameters inside the search method of the SearchApiSolrBackend class here
<code>  foreach ($options as $option => $value) {
    if (strpos($option, 'solr_param_') === 0) {
      $solarium_query->addParam(substr($option, 11), $value);
    }
  }
</code>
I noticed that it only applies the parameter if it's preceded by 'solr_param_' and if it is it strips out the 'solr_param_' before applying it to the actual parameter.
All I had to do was add 'solr_param_' to the beginning of my option like so.
<code>$query->setOption('solr_param_spellcheck','true');
</code>
Once I did that, getAllExtraData() returned what I needed.

array(1) { ["search_api_solr_response"]=> array(2) { ["response"]=>
  array(4) { ["numFound"]=> int(0) ["start"]=> int(0) ["maxScore"]=>
  float(0) ["docs"]=> array(0) { } } ["spellcheck"]=> array(1) {
  ["suggestions"]=> array(16) { [0]=> string(5) "goood" [1]=> array(4) {
  ["numFound"]=> int(1) ["startOffset"]=> int(11) ["endOffset"]=>
  int(16) ["suggestion"]=> array(1) { [0]=> string(4) "good" } } [2]=>
  string(5) "goood" [3]=> array(4) { ["numFound"]=> int(1)
  ["startOffset"]=> int(42) ["endOffset"]=> int(47) ["suggestion"]=>
  array(1) { [0]=> string(4) "good" } } [4]=> string(5) "goood" [5]=>
  array(4) { ["numFound"]=> int(1) ["startOffset"]=> int(60)
  ["endOffset"]=> int(65) ["suggestion"]=> array(1) { [0]=> string(4)
  "good" } } [6]=> string(5) "goood" [7]=> array(4) { ["numFound"]=>
  int(1) ["startOffset"]=> int(93) ["endOffset"]=> int(98)
  ["suggestion"]=> array(1) { [0]=> string(4) "good" } } [8]=> string(5)
  "goood" [9]=> array(4) { ["numFound"]=> int(1) ["startOffset"]=>
  int(111) ["endOffset"]=> int(116) ["suggestion"]=> array(1) { [0]=>
  string(4) "good" } } [10]=> string(5) "goood" [11]=> array(4) {
  ["numFound"]=> int(1) ["startOffset"]=> int(129) ["endOffset"]=>
  int(134) ["suggestion"]=> array(1) { [0]=> string(4) "good" } } [12]=>
  string(5) "goood" [13]=> array(4) { ["numFound"]=> int(1)
  ["startOffset"]=> int(154) ["endOffset"]=> int(159) ["suggestion"]=>
  array(1) { [0]=> string(4) "good" } } [14]=> string(5) "goood" [15]=>
  array(4) { ["numFound"]=> int(1) ["startOffset"]=> int(182)
  ["endOffset"]=> int(187) ["suggestion"]=> array(1) { [0]=> string(4)
  "good" } } } } } }

Not entirely sure why I have so many duplicate results here so if anyone has input on that that would be helpful. Otherwise I do have the data I need.


Have a note stand out in a pianissimo chord (piano)

Question: This is the last chord of Francis Poulenc's Mélancolie for piano. It occurs while a piano D♭ major chord is still resonating in the bass.

How would you have the B♭♭ be perceptible, surprising, and yet still pianissimo? Any technique?
I tend to think that any single performer would judge himself negatively if this note did not sound properly, and I feel that I miss it approx. 30% of the time.
Comment: I'm not sure this is a real question ... if you want it to stand out in terms of volume, you need to play it louder.  You'd have to do something bizarre like replace its string with a different type for it to stand out otherwise, or something "wrong" like play it staccato.
Comment: I have to agree with Matthew here. Perhaps you could clarify...this is a very subtle question, in any case.
Comment: @Matthew Read: the problem as you can see it is: how to play it louder, but not too much.
Comment: There was a Bartók piece I once played, which I had to change the last chord to make it as expressive as I wanted.
This is what I did: Take the Bbb and make it a grace note, play it first, then press the left pedal and play the rest of the chord.
Attention: I don't know the piece, nor if you have room to make such big changes in the piece.
Answer: The general way to emphasize a single note in a chord is to shift the weight of your hand over the finger playing the note you want to emphasize. This can be achieved by a slight rotation of your wrist. I don't see why it wouldn't work in your situation.
Answer: Place your fingers on the chord but raise your finger over the B flat flat.  As you bring your hands down to play the other notes, play the high note simultaneously.  Because of the extra finger motion, you will play that note a little louder.
Answer: All you really need to do is make sure you PLAY it!  Don't obsess on the 'pppp'.   Play the note sufficiently decisively.  Particularly on a piano with a less than perfect action.  Take the weight off by lifting your arm.
Answer: I have never heard of anyone using Mark Lutton's suggestion. It seems silly to me, as it requires extra pinky work. It seems like it would be very tiring in passages with extended chordal voicing.
You can practice it by playing the whole chord an extremely light staccato and only holding the top note. After you master this, try playing the top note at different volumes while you continue to play the other voices in a very light staccato.
Horowitz suggested that when doing voicing it's helpful to think of the voiced note as "striking first" even if it strikes simultaneously.
Answer: Try playing the B♭♭ a few moments later than the rest of the chord. Similar to Lagerbaer's suggestion, you can rotate your wrist towards the top note, then play the pinky note a bit later to create emphasis—but not too late, or else it won't sound like a proper chord (≈ 0.1 seconds).


NGINX if condition have and condition

Question: i want to make a condition if it fulfills
abc.com/abc.m3u8?token=abcd
if conditions are met then allow
otherwise return 403
I'm a little confused because I can't use nested if in nginx
`
     if ($uri !~* "^(.*)/(abc.m3u8)(.*)" && $arg_token !~* "abcd"){
        return 403;
}

`
Comment: after request abc.m3u8
then the browser will request again
abc.com/1.ts
abc.com/2.ts
where 1.ts must allow, the if condition above will block abc.com/1.ts
how to handle 1.ts requests too?
Answer: You can use request_uri to check if the URL matches abc.com/abc.m3u8?token=abcd :
if ($request_uri !~* "^/abc\.m3u8\?token=abcd$") {
  # Return a 403 Forbidden status if the URL does not match the pattern
  return 403;
}

Comment: sorry, there is a need for additional
because the m3u8 live video will have more requests asking
abc.com/1.ts
abc.com/2.ts
where if set if statement above, request 1.ts will get response 403

NGINX if condition have and condition


Does the variable order matter in linear regression

Question: I'm investigating interplay between two variables ($x_1$ and $x_2$). There is a great deal of linear correlation between these variables with $r>0.9$. From the nature of the problem I cannot say anything about the causation (whether $x_1$ causes $x_2$ or the other way around). I would like to study deviations from the regression line, in order to detect outliers. In order to do this I can either build a linear regression of $x_1$ as a function of $x_2$, or the other way around. Can my choice of variable order influence my results?
Comment: In the search for outliers, you should first regress your dependent variable against both $x_{1}$ and $x_{2}$ and look for outliers.
Comment: Is finding outliers the pupose of your investigation? If so, then you should first regress your dependent variable against both $x_{1}$ and $x_{2}$ and then perform outlier tests. If finding possible causation, then you should consider performing a designed experiment. If the purpose of your experiment is to find a relationship between your two independent variables, looking at a happenstance of collected data will not do the trick.
Comment: It isn't clear to me what you mean by outliers. If there are outliers in your data then they will affect the calculation of the regression line.  Why are you looking for outliers in both $x_1$ and $x_2$ simultaneously?
Comment: See https://stats.stackexchange.com/questions/22718/what-is-the-difference-between-linear-regression-on-y-with-x-and-x-with-y
Comment: Please clarify the roles of these "variables": are they both predictors of a third variable?  If not, then the links suggested in earlier comments identify a duplicate thread.
Answer: It surely can (actually, it even matters with regard to the assumptions on your data - you only make assumptions about the distribution of the outcome given the covariate). In this light, you might look up a term like "inverse prediction variance". Either way, linear regression says nothing about causation! At best, you can say something about causation through careful design.
Answer: To make the case symmetrical, one may regress the difference between the two variables ($\Delta x$) vs their average value.
Answer: Standard regression minimizes the vertical distance between the points and the line, so switching the 2 variables will now minimize the horizontal distance (given the same scatterplot).  Another option (which goes by several names) is to minimize the perpendicular distance, this can be done using principle components.
Here is some R code that shows the differences:
<code>library(MASS)

tmp <- mvrnorm(100, c(0,0), rbind( c(1,.9),c(.9,1)) )

plot(tmp, asp=1)

fit1 <- lm(tmp[,1] ~ tmp[,2])  # horizontal residuals
segments( tmp[,1], tmp[,2], fitted(fit1),tmp[,2], col='blue' )
o <- order(tmp[,2])
lines( fitted(fit1)[o], tmp[o,2], col='blue' )

fit2 <- lm(tmp[,2] ~ tmp[,1])  # vertical residuals
segments( tmp[,1], tmp[,2], tmp[,1], fitted(fit2), col='green' )
o <- order(tmp[,1])
lines( tmp[o,1], fitted(fit2)[o], col='green' )

fit3 <- prcomp(tmp)
b <- -fit3$rotation[1,2]/fit3$rotation[2,2]
a <- fit3$center[2] - b*fit3$center[1]
abline(a,b, col='red')
segments(tmp[,1], tmp[,2], tmp[,1]-fit3$x[,2]*fit3$rotation[1,2], tmp[,2]-fit3$x[,2]*fit3$rotation[2,2], col='red')

legend('bottomright', legend=c('Horizontal','Vertical','Perpendicular'), lty=1, col=c('blue','green','red'))
</code>
To look for outliers you can just plot the results of the principle components analysis.
You may also want to look at:

Bland and Altman (1986), Statistical
  Methods for Assessing Agreement
  Between Two Methods of CLinical
  Measurement. Lancet, pp 307-310
Answer: Your x1 and x2 variables are collinear. In the presence of multicollinearity, your parameter estimates are still unbiased, but their variance is large, i.e., your inference on the significance of the parameter estimates is not valid, and your prediction will have large confidence intervals.
Interpretation of the parameter estimates is also difficult. In the linear regression framework, the parameter estimate on x1 is the change in Y for a unit change in x1 given every other exogeneous variable in the model is held constant. In your case, x1 and x2 are highly correlated, and you cannot hold x2 constant when x1 is changing.


Streams Why Use Seek(0L, SeekOrigin.Begin) instead of Position = 0 or vice versa

Question: Could anyone please explain to me the differences, if any?
I tried to Google it but couldn't find much information.  Maybe I didn't use correct keywords.
Any insight would be greatly appreciated.
Answer: stream.Seek(x, SeekOrigin.Begin); and stream.Position = x; both result in the stream position being set to x. The difference is that the Position setter unconditionally discards any read buffer, while the Seek method attempts to retain the part of the buffer that is still relevant to the new position.
You'll have to test, which one is faster for your scenario, but there's definitely a performance difference and neither is faster in all cases. I really wonder why this difference isn't documented.
Comment: Thanks, this was an important important difference that I wasn't aware of.  Helped me fix a bug doing small backwards seeks yielded wrong data.  Changed to Position instead and the data was read through.
Answer: In your example there is no difference.
The actual difference between Stream.Position and Stream.Seek is that Position uses an absolute offset whereas Seek uses an offset relative to the origin specified by the second argument.
Answer: As far as I can tell, at least for this specific case, nothing.
Both method Seek() and property Position require CanSeek to be true so from what I see it's up to the implementer.
Seek is really there to allow searching from specified locations (SeekOrigins) to an offset (the examples given on MSDN are somewhat convoluted but representative of the purpose: http://msdn.microsoft.com/en-us/library/system.io.filestream.seek.aspx).
Position is absolute and is obviously not meant for searching.
The case you mentioned just happens to be equivalent.
Personally, I'd use .Position = 0 to move to the beginning of the stream as that reads cleaner to me than "Seek using the beginning of the file as an origin and move this 0 offset of bytes."


What is the intuitive explanation of the expectation of a mean and variance value in Bishop's PRML book?

Question: In Bishop's Pattern Recognition and Machine Learning book, there are two equations stated as follows.
Equation 1.57:
$\mathbf{E}[\mu_{ML}] = \mu $
and
Equation 1.58:
$\mathbf{E}[\sigma^2_{ML}] = (\frac{N-1}{N})\sigma^2$
where $\mu_{ML}$ and $\sigma^2_{ML}$ is the maximum likelihood solution for the mean, and variance.
My question is that since $\mu_{ML}$ and $\sigma^2_{ML}$ are already functions of the $N$ dataset, what does it mean when we take the expectation of $\mu_{ML}$ and $\sigma^2_{ML}$ with respect to the dataset again as in the equations 1.57 and 1.58 above? I understand how to prove the equations, but I don't understand what do they mean?
Thank you in advance.
Answer: It means, if you take several datasets of size $N$, calculate mean and variance estimates for each of them and then take the average, you'd obtain $\mu$ and $\frac{N-1}{N}\sigma^2$


How small can a subsample in bagging be before performance degrades severely?

Question: If I want to perform bagging, would subsamples with sizes of 0.1% of the actual data be appropriate?
The reason I want to do so is because my actual data set is very large in the tens of millions.
Answer: This depends entirely on the data. It's impossible to give a general answer. The optimal subsample size can't be expressed in terms of $x\%$ of the full data set. What determines the size of a real data set anyway? It's in no way optimal.
To give you some examples, I've had surprisingly good results with bagging on tiny subsamples in text mining (e.g. 40 data points in $~20,000$ dimensions, ~$60\%$ base model accuracy, over $90\%$ ensemble accuracy), but for other data sets you typically need more. There is no rule of thumb, definitely not in the form of "$x\%$ of the full data set".
The simplest approach is to try: e.g. use a couple of small subsamples and bag them, if the ensemble accuracy is much higher than the base models, it's working; if not, use larger subsamples.
Note that using larger subsamples is not guaranteed to improve your results. In bagging you make a tradeoff between base model accuracy and the gain you get through bagging. If you have unstable base models (typically trained on smaller subsamples with lower accuracy), the aggregation may improve the ensemble greatly. When your base models become more stable (typically trained on larger subsamples with higher accuracy), the improvement through aggregation diminishes.


What is the probability that the angle is a right angle?

Question: Let's say you have a square, say $ABCD$, with side length 1. A point $P$ is randomly chosen from inside the square, with any point being equally probable of being chosen. What is the probability that the angle $\angle APB$ is a right angle?
This looks simple, and I do this problem for the case of $\angle APB$ being acute or obtuse, and that the set of all points satisfying the condition above is a semicircle inside the square centered at the midpoint of $AB$. How do you do this, or is it impossible?
Comment: My guess:  probability of being a right angle (or any partticular angle) is $0$.
Answer: This question doesn't really make any sense, but the way I would interpret 'probability' of being chosen in this case is in terms of area. Since the area of the region which would fulfil the required criterion is zero (a line), the associated probability is zero.
As for the angle being obtuse, the associated area is a semi-circle centred at the midpoint of the line $AB$ with radius $0.5$ hence its total area is
$$\frac12\pi(0.5)^2=\frac18\pi$$
as the total area of the shape is $1\times1=1$ we have
$$\text{probability }\angle APB\text{ obtuse}=\frac18\pi$$
$$\text{probability }\angle APB\text{ acute}=1-\frac18\pi$$
Comment: @Jithinash - in probability (especially with continuous distributions), a probability of $0$ does not mean *impossible* or *never*, and a probability of $1$ does not mean *sure* but instead *[almost sure](https://en.wikipedia.org/wiki/Almost_surely)*
Comment: I can see your reasoning, but because there is equal probability of every point being chosen, the probability should, intuitively, be nonzero, because zero probability shows impossibility.
Comment: Yes. It is also 'impossible' to choose any single real number randomly from the interval $[0,1]$. You should look into measure theory.
Comment: So 0 can mean, so infinitely small that it is basically impossible?
Answer: The probability is zero. You've correctly identified the set of all points satisfying the desired condition -- the locus is a semicircle. In the acute or obtuse case, you were able to find the locus, and it turned out to have positive two-dimensional area. You were able to use this to calculate a probability. For the right angle case, the locus isn't "two dimensional" -- it's one dimensional. Thus its two-dimensional area is $0$, so the probability is $0$. Intuitively, it is impossible to randomly pick a point exactly on that locus.
To make these ideas more rigorous, you must take a course on measure theory.


cannot be null - PhP PDO Function

Question: I have a problem with one function, function should be sent a text to base (phpmyadmin), or menu displays error..
Error code:

Error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column
  'Code' cannot be null

My function:
public function UploadInvoice($CONN)
{
  $SubmitOK = '1';
  $Core = new Core();
  $Core->CheckForEmpty(array('Code'), 'finances.php');

  if($SubmitOK == '1') {
    try {
      $SQL = 'INSERT INTO Invoices (UserID, Code) VALUES (:UserID, :Code)';
      $SQL = $CONN->prepare($SQL);
      $SQL->execute(array('UserID' => $_SESSION['UserLogin']['ID'], 'Code' => $Code));
      $_SESSION['Success'] = 'Successfully submitted your code, Wait for checking multiple payments, your money will be soon on the bill';
      header('location: finances');
      exit();
    } catch(PDOException $e) {
       echo "Error: " . $e->getMessage();
    }
  } else {
      $_SESSION['Error'] = 'An error has occurred. Try again!';
      header('location: finances');
      exit();
  }
}

My form code:
<form action="" method="POST">
    <input type="text" class="form-control" required="true" minlength="4" name="Code" placeholder="Your ID">
    <button type="submit">SEND</button>
</form>

Comment: The error clearly states that `$Code` have no value
Comment: HI @CyberFX: You Didn't Respond To The Answer Given Below.
Answer: You Missed ":" in $SQL->execute.... Append it with UserID & Code.
Change
$SQL->execute(array('UserID' => $_SESSION['UserLogin']['ID'], 'Code' => $Code));

To
$SQL->execute(array(':UserID' => $_SESSION['UserLogin']['ID'], ':Code' => $Code));

For More info, Please click PDO Statement Execute

cannot be null - PhP PDO Function


How to show an ideal isn't radical

Question: The ideal in question is $(wy-x^2,w^2z-x^3)$ in the ring $k[w,x,y,z]$ for algebraically closed $k$.
Comment: In fact, the radical of the given ideal is $(x^2-yw, xy-zw)$.
Answer: First, you need to find a simple polynomial that is zero in the zero-set $V(I)$ of the ideal $I$. If $(a,b,c,d)$ is in $V(I)$, then
$abd=a^3=d^2c$, so either $d=0$ or $ab=cd$. But if $d=0$, then $a^2=0$, so $ab=cd$ again. Hence the polynomial $xy-zw$ is zero in all $V(I)$. Therefore $xy-zw$ is in the radical of $I$. (One can show also that $(xy-zw)^3$ is in $I$, but you don't need this.)
Now you only need to show that $xy-zw$ is not in $I$.

How to show an ideal isn't radical


Can you determine how a neural network produces its results?

Question: I read an article about neural networks that stated you really can't determine how the network produced a given result.
What I mean is that there might be several thousands of factors behind the result and that you can't really isolate them. Could anyone shed some light on this?
Comment: Could you provide a link to the article?
Answer: Artificial Neural Networks are 100% deterministic. The only operations used are multiplication, addition, and some sort of nonlinear function. In fact, the methods used to train them (usually always back propagation) only work because the network can be reversed, and you can see where each contribution to the end result came from.
Comment: Can you extend your points to explain how someone can identify the role of an individual factor on the result? Does your argument imply that that role will always be the same irrespective of the status of the other factors in the NN?
Comment: The Eric Wan diagrammatic Jacobian, with a technically insignificant perturbation of the output, when the input is specified, and the NN has been trained allow the determination of contribution by every deterministic factor in the NN, even with some pretty elaborate topologies.  The graph determination is amazingly simpler than chain rule and lots of symbolic manipulation.  Before Wan there were folks who earned their credentials by proving how to train a particular style.  After Wan, it was not such an issue.
Comment: Using calculus you can put an exact numeric value on how much any one factor affects any other factor. For example, to find out how much the weight "w" affects an activation "a" downstream, you just calculate the derivative of w with respect to a. The role of each factor will always be the same once training is done, because none of the factors that produce an output change except the input into the network (much unlike a biological neural network where the factors are always changing, an artificial network is fixed in place)


Holomorphic functions in $D(0,1)$

Question:
Let $f$ be a holomorphic function in the disk $D(0,r)$ of center $0$ and radii $r>1$ s.t. for all $z$ of module $1$ we have $|f(z)|<1$.
Show that there is an $a\in D(0,1)$ s.t. $f(a)=a$ and $f'(a) \neq 1$.

Well, so far I've shown that there is a unique $a\in D(0,1)$ s.t. $f(a)=a$.
Indeed, since $|z-(f(z)-z)|=|f(z)| < 1 = |z|$ for all $z\in \partial D(0,1)$ Rouche's theorem says that $f(z)-z$ has the same number of zeros as $z$ in $D(0,1)$, that is one.
Now, a hint on how to prove that $f'(a) \neq 1$?
I was thinking that Schwarz's lemma has similar hypothesis and a pertinent conclusion, but I don't see how to transform $f$ in a holomorphic function with a zero in $0$ still contained in the unit disk and with the same derivative as $f$.
Comment: If you want to use the Schwarz lemma, look at $T_a \circ f \circ T_a^{-1}$, where $T_a(z) = \dfrac{z-a}{1 - \overline{a}z}$.
Answer: If a=0, then you can use the Schwarz lemma. If $a\neq0$, you can use the Blaschke factor $$b_a=\frac{z-a}{1-\bar{a}z}$$ defined on $D(0,1)$. $b_a(0)=a$ and $b_a(a)=0$. Now consider $g=b_a ∘ f ∘ b_a^{-1}$ defined on $D(0,1)$. Then $g(0)=0$. Apply Schwarz Lemma to $g$. Then $|g'(0)|\leqslant 1$, and $$g'(0)=\frac{f'(a)}{\left(1-|a|^2\right)^2},$$ which gives the result as $a\neq0$.
Comment: Due to chain rule, $$g'(0) =b_a'(0)\cdot f{'}\circ b_a(0) \cdot b_a^{-1}{'}\circ f\circ b_a (0) = b_a{'}(0) \cdot f{'}(a) \cdot b_a^{-1}{'}(a) = \frac{b_a'(0)}{b_a{'}(0)}\cdot f{'}(a)=f'(a)$$, amirite?
Comment: I am sorry, will just make the correction.
Answer: A solution without using Schwarz's lemma:
We already knew that $f(z)-z$ had a single zero in $D(0,1)$. Now, that implies that $(f(z)-z)'_{z=a}=f'(a)-1 \neq 0$, or otherwise the zero would have multiplicity of at least two.
Thus $f'(a)\neq 0$.

Holomorphic functions in $D(0,1)$


Persistent ip rule on Linux (Redhat)

Question: How can I configure a persistent ip rule on Linux (specifically Redhat based distros)? Is there no built in method? Is my only option adding to /etc/rc.d/rc.local or creating my own rc.d script?
Edit: For clarification I am not referring to iptables but the ip tool (which I don't think a lot of people are familiar with). In any case, the rule I am trying to persist is added with the following command:
# ip rule add fwmark 1 lookup 100
# ip rule
...
32765: from all fwmark 0x1 lookup 100
...

The only reference I've found to doing this is from Novell: http://www.novell.com/support/viewContent.do?externalId=7008874&sliceId=1 which recommends creating an rc.d script
Comment: Can you share the IP rule you'd like to persist?
Comment: Rule is `ip rule add fwmark 1 lookup 100`
Answer: As is customary I stumble upon the answer to my own problem shortly after asking :) Found an answer at http://grokbase.com/t/centos/centos/099bmc07mq/persisting-iproute2-routes-and-rules
On Redhat 5+ the /etc/sysconfig/network-scripts/ifup-routes script handles rule-* files. Relevant code below:
# Routing rules
FILES="/etc/sysconfig/network-scripts/rule-$1"
if [ -n "$2" -a "$2" != "$1" ]; then
    FILES="$FILES /etc/sysconfig/network-scripts/rule-$2"
fi

for file in $FILES; do
   if [ -f "$file" ]; then
       { cat "$file" ; echo ; } | while read line; do
           if [[ ! "$line" =~ $MATCH ]]; then
           /sbin/ip rule add $line
       fi
       done
   fi
done

Script for RHEL 6.5 (possibly older 6+):
# Routing rules
FILES="/etc/sysconfig/network-scripts/rule-$1 /etc/sysconfig/network-scripts/rule6-$1"
if [ -n "$2" -a "$2" != "$1" ]; then
FILES="$FILES /etc/sysconfig/network-scripts/rule-$2 /etc/sysconfig/network-scripts/rule6-$2"
fi

for file in $FILES; do
   if [ -f "$file" ]; then
       handle_ip_file $file
   fi
done

handle_ip_file() {
    local f t type= file=$1 proto="-4"
    f=${file##*/}
    t=${f%%-*}
    type=${t%%6}
    if [ "$type" != "$t" ]; then
        proto="-6"
    fi
    { cat "$file" ; echo ; } | while read line; do
        if [[ ! "$line" =~ $MATCH ]]; then
            /sbin/ip $proto $type add $line
        fi
    done
}

Answer: The above is about 3/4 of the answer - the missing piece is how to format the /etc/sysconf/network-scripts/rule-ethX file.  You also need to add the routing tables to /etc/iproute2/rt_tables:
# add a line with a table identifier and name:
100    ISPname

And add the rule file /etc/sysconfig/network-scripts/rule-eth0:
# rule-eth0
from 126.96.36.199/24 table {table name from /etc/iproute2/rt_tables}
to 18.104.22.168/24 table {table name from /etc/iproute2/rt_tables}

Note that the table names must match, and are case sensitive.
Answer: note if you use priorities in these rule files for any of the rules, you have to use priorities for all the rules. Otherwise, the ones that don't have any priorities all get added to the priority 0 chain.

Persistent ip rule on Linux (Redhat)


What is lettuce library for?

Question: I have found code within an open source project which uses lettuce library extensively.
It seems  that lettuce is a tool to support "Behaviour Driven Development".
I'm wondering whether code based on lettuce is only for testing purposes, or is it actually used as a "production code"?
I would appreciate if someone could explain in plain English what is the purpose of lettuce library and how is it used?
Answer: The Lettuce library is used to test code before it is released to production systems.
Lettuce is meant to describe Behavior Driven Development.
The idea behind lettuce is that before coding up any functionality, you first describe your what you want your functions to do with written descriptions. Then following your descriptions, you write out the core steps of what you expect from the function. After doing so, you implement the functionality you originally described and test the results.
You can repeat the cycle above, each time adding additional descriptions. After each iteration, you develop more confidence in the correctness of your code.
Reference:
http://lettuce.it/tutorial/simple.html

What is lettuce library for?


Python PySimpleGUI abrindo a tela errada

Question: Tenho um crawler utilizando PySimpleGUI para definir os dados a serem coletados e Selenium para a coleta de dados. Após a definição dos dados através de uma window criada pelo sg.Window(), eu crio uma sg.PopupAnimated indicando o status do Crawler, porém ao executar na IDE PyCharm funciona corretamente, após gerar o EXE através do PyInstaller, Auto-py-to-exe ou CX_Freeze no lugar de gerar o Popup ele exibe novamente a tela, segue o código abaixo:
from selenium import webdriver
import PySimpleGUI as sg
import multiprocessing
import time
import sys
import re
import os

def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)

def getDados():
    global nome
    global email
    global user

    sg.SetOptions(text_justification='right')
    layout =[[sg.Text('Nome',size=(23,1)), sg.Input()],
            [sg.Text('E-mail',size=(23,1)), sg.Input()],
            [sg.Text('Nome e Sobrenome',size=(23,1)), sg.Input()],
            [sg.Submit('OK', pad=((420, 5), 5)), sg.Exit('Cancelar', pad=((5, 0), 5))]]
    window = sg.Window('Gera', layout, finalize=True)
    while True:
        event, values = window.read()
        if event == sg.WIN_CLOSED or event == 'Exit' or event == 'Cancelar':
            sys.exit(0)
        elif event == 'OK':
            #Valida se todos estão preenchidos
            if(values[0] =='' or values[1] =='' or values[2] ==''):
                sg.popup('Preencha todos os campos')
                continue
            # Valida formato do email
            elif (re.search("[a-z0-9.]+@[a-z0-9]+\.[a-z]", values[1]) == None or ' 'in values[1]):
                sg.popup('É Necessário Informar um e-mail Válido')
                continue
            # Valida se existe nome e sobrenome
            elif(re.search(". .", values[2]) == None):
                sg.popup('É Necessário Informar Nome e Sobrenome')
                continue
             else:
                 nome = values[0].upper()
                 email = values[1]
                 user = values[2]
                 window.close()
                 del window
                 return

def alerta(msg):
    while(True):
        sg.PopupAnimated('loading.gif', time_between_frames=100, message = msg, font ='Courier 12', keep_on_top=True)

def thread(desc,pare):
    if(pare == None and desc == None):
        pare.terminate()
        return
    if(pare!= None):
        pare.terminate()
    if(desc == None):
        pare.terminate()
        return
    th = multiprocessing.Process(target=alerta,args=(desc,))
    th.start()
    return th

if __name__ == '__main__':
    sg.SetGlobalIcon('logo.ico')
    getDados()
    th = thread('Aguarde', None)

    driver = webdriver.Chrome(executable_path=resource_path('chromedriver.exe'))
    driver.set_window_size(1920, 1080)

    try:
        try:
            th = thread('Logando', th)
        except NoSuchElementException:
            th = thread(None, th)
            sg.popup_error('Erro ao Efetuar o Login')

        time.sleep(60)
        try:
            th = thread('Acesando Perfil', th)
        except NoSuchElementException:
            th = thread(None, th)
            sg.popup_error('Erro ao Acesar Perfil')
    except NoSuchElementException:
        driver.get_screenshot_as_file('erro.png')

Sempre que executado o comando sg.PopupAnimated() o software abre a tela da função getDados(). Porém isso somente ocorre após a geração do EXE, enquanto eu rodo o código .py pela IDE ele funcionar normal, exibindo o PopUp.
Answer: Boa tarde, descobri a solução do problema, ele estava exibindo a mesma janela pois eu estava utilizando o multiprocessing.Process(), devido ele criar uma nova instância para execução, ele acabava executando novamente a função getDados(). Para corrigir o problema precisei efetuar algumas alterações, uma delas foi alterar multiprocessing por Thread(), que corrigiu o problema da abertura das janelas. Porém como eu não conseguia finalizar a Thread, eu utilizei apenas uma Thread para executar o Crawler, e no main mantive a janela onde era exibido os status. Desta forma criei uma variável para indicar o status e apenas verificava ela em um While dentro do Main.


Downloading Embedded Videos

Question: Youtube and other similar video sharing websites shares embedded flash videos. Many applications like Youtube Downloader realises this . I am developing a downloader using java. Can i realize this in java.
Answer: try to look to the java YouTube video Downloader
Answer: definitely you can do this with java
connect url through urlconnection
and save read data in appropriate form for example your_Video.mkv etc..

Downloading Embedded Videos


How to create incremented view filters for numeric fields in Drupal?

Question: In my Drupal 7 I'm building a view of homes/properties with exposed filters of "Minimum Rent" and "Maximum Rent" - so that people can find homes according to their budget.
Rent (per month) is basically an integer number field and can be whichever number (£475 or £677 or whatever an end user enters when creating the node). But in my exposed filters for "Min Rent" and "Max Rent" I want it to be a dropdown list of £100, £200, £300, £400, £500 etc -in other words, automatically incremented. Exactly as we see on websites like www.rightmove.co.uk or www.zoopla.com or any other property listing website.
How can I achieve this?
Answer: If you create a field an select a type of text list using a list widget, you can create the any list you wish for the field.  Then when you expose the field in your view  the drop down list of values will be included in the exposed filter.
Comment: That's not what I'm after because my field type is numeric (price) and can be anything, thus the selection list for the field is out of the question - you can't ask people to rent out their house for specifically £200 when they want to receive £245 for example.

I have created a custom module here http://groups.drupal.org/node/25941#comment-746878  but it doesn't seem to work in D7.  Perhaps you can help in improving its code?  Thanks.
Answer: I'd use hybrid exposed filters as a starting point. It is a work in progress patch but very mature. See:

http://drupal.org/node/731662
http://vimeo.com/14533078


Java collection with most performance for lookup table with multiple values per key?

Question: I am looking to implement a transformation process, based on receiving some value, i want to return one or many instances of a class.
I need to do this at the highest speed possible as it is used as part of a realtime process.
I have a collection of 30,000 classes, each of which with a corresponding key, matching a signal to be received, some classes can be linked to the same key
Which option is the most efficient, or is there another to consider?

Multimap
Map<String, ArrayList<Class>>
ArrayList<Class> and search using predicate?
Comment: HashMap> I would suggest
Comment: Or `Map` and `ArrayList`, to parallelize some of that indirection and remove overheads.
Answer: Your choice should be based on the most frequent operation, in this case search.
Lists give you best complexity for insert O(1) and O(n) for search
A MultiMap associates a key of type A with a value of type Collection
A Map associates a key of type A with a value of type B.
So, a MultiMap<Integer, Set<String>> can be viewed as a
Map<Integer, Collection<Set<String>>.
Both give O(1) insert and worst case O(k) k is the longest collection in the values. k is heavily dependent on the quality of the hash function, with good hash function the lookup time can be O(1).
So I would go with either Map or MultiMap. If you are initializing the structure once and then never inserting new elements then definitely go with Map.


Como carregar uma view dentro de um layout?

Question: Estou tentando carregar uma view dentro de um layout, segue meu controller abaixo:
class IndexController extends BaseController {
    protected $layout = 'admin.layouts.default';

    public function index()
    {
        $this->layout->$this->layoutcontent =  View::make('admin.index');
    }
}

Porém está retornando o seguinte erro:

Attempt to assign property of non-object
Answer: O Erro está neste trecho:
$this->layout->$this->layoutcontent =  View::make('admin.index');

A propriedade é content mas tu tens $this->layoutcontent, deverás alterar para :
$this->layout->content = View::make('admin.index');

Ver também a documentação em: Laravel - Controller Layouts (Inglês)
Answer: Para incluir sub-views dentro do layout, pode ser desta forma:
@include('view.name')

Passando valores:
@include('view.name', array('some'=>'data'))


Should you ever use non-bootstrapped propensity scores?

Question: I am trying to measure the difference in continuous $y$ given a binary treatment $B$ and I am using the propensity score matching method. As I built the propensity score model I noticed that small changes in some of the variables lead to a really big difference in estimates of the effect of $B$ downstream.
In order to measure this variance I built a bootstrap. Sample $n$ rows with replacement from the data, fit the the propensity score model on the sample, match, and estimate the effect of $B$. Repeat.
This begs the question - is there ever a reason NOT to do this? It seems like this incorporates an extra level of uncertainty that otherwise wouldn't be captured.
Answer: It's true that there are several sources of uncertainty in propensity score matching. One is sampling from the superpopulation (which is true of most statistical analyses and is the usual justification for sampling distributions and confidence intervals), but two others are the uncertainty in estimating the propensity score and the uncertainty due to matching. I would not say the solutions to addressing these uncertainties are well understood, but we do have lots of evidence from simulation studies and some analytic derivations to guide us.
Regarding bootstrapping. Bootstrapping the whole process of estimating the propensity score, performing the matching, and estimating the effect is often a good idea. Although Abadie & Imbens (2008) argued analytically that the bootstrap is not valid when performing matching with replacement, simulation studies including Bodory et al. (2020) and Hill & Reiter (2006) have found the bootstrap to be adequate, if not conservative. For matching without replacement, simulations by Austin & Small (2014) examining the performance of bootstrapping have found that the full bootstrap as you described is conservative. From this evidence, we can feel confident in using the bootstrap for propensity score matching.
Austin & Small (2014) and Abadie & Spiess (2019) both observed that a block bootstrap actually approximates the sampling variability of a propensity score matching estimator better than a traditional bootstrap. In the block bootstrap, you perform the propensity score estimation and matching in your original sample and then bootstrap pairs from that sample to estimate the treatment effect. This seems to ignore the uncertainty due to estimating the propensity score, but it turns out this isn't so problematic. Abadie & Imbens (2016) found analytically that treating the propensity score as fixed actually increases the variability of the effect estimate, which was further confirmed by Austin & Small (2014) who compared bootstrapping with the true and estimated propensity score. This same type of relationship has been found with propensity score weighting, which is why failing to account for the estimation of the propensity score actually yields conservative standard error estimates (Lunceford & Davidian, 2004).
So, to answer your question, you can bootstrap the whole process, but you don't have to, and you can validly estimate the variance of the effect estimate by ignoring the variability due to the estimation of the propensity score and instead performing a block bootstrap on the matched pairs. It might be the case that your dataset is weird and the block bootstrap doesn't correctly address the true uncertainty in the effect estimate, in which case it might be beneficial to use an estimation for which uncertainty estimation is well understood, like propensity score weighting.

Abadie, A., & Imbens, G. W. (2008). On the Failure of the Bootstrap for Matching Estimators. Econometrica, 76(6), 1537–1557. JSTOR.
Abadie, A., & Imbens, G. W. (2016). Matching on the Estimated Propensity Score. Econometrica, 84(2), 781–807. https://doi.org/10.3982/ECTA11293
Abadie, A., & Spiess, J. (2019). Robust Post-Matching Inference. 34.
Austin, P. C., & Small, D. S. (2014). The use of bootstrapping when using propensity-score matching without replacement: A simulation study. Statistics in Medicine, 33(24), 4306–4319. https://doi.org/10.1002/sim.6276
Bodory, H., Camponovo, L., Huber, M., & Lechner, M. (2020). The Finite Sample Performance of Inference Methods for Propensity Score Matching and Weighting Estimators. Journal of Business & Economic Statistics, 38(1), 183–200. https://doi.org/10.1080/07350015.2018.1476247
Hill, J., & Reiter, J. P. (2006). Interval estimation for treatment effects using propensity score matching. Statistics in Medicine, 25(13), 2230–2256. https://doi.org/10.1002/sim.2277
Lunceford, J. K., & Davidian, M. (2004). Stratification and weighting via the propensity score in estimation of causal treatment effects: A comparative study. Statistics in Medicine, 23(19), 2937–2960.


Any conditions that makes eigen values of a real square matrix real and distinct

Question: With respect to a matrix $A\in\mathbb{R}^{n\times n}$, is there any if and only if conditions that make sure the eigen values of $A$ remain real and distinct? $A$ here is not symmetric but is stable and also there exists a $P$ such that $PAP^{-1}$ is symmetric.
For having real eigen values, $A$ needs to symmetric or symetrizable right. But I have no clue to show that $A$ has distinct eigen values. The theory of interlacing inequalities for symmetric/hermitian matrices cannot help as I cannot say about a submatrix of $A$ having distinct eigen values or not.
The $A$ matrix is of the form
$\left(
  \begin{array}{cccc}
     -(a+b+c+d)&e  &f  & g \\
     b&  -e& 0 & 0 \\
     c& 0 & -f &0  \\
     d&  0& 0 & -g \\
  \end{array}
\right)$, i.e. $A$ is a Metzler Matrix. For certain values of $a~,b~,c~,d~,e~,f~,g \ge 0$ the matrix $A$ has real and distinct eigen values. I want to know whether any matrix $A$ which is Metzler, diagonally dominant, and with $a~,b~,c~,d~,e~,f~,g \ge 0$ the eigen values will be real and distinct.
Comment: @Blazej Probably the first, otherwise we could say : The eigenvalues are real and distinct if and only if the characteristic polynomial has real and distinct roots. I do not think that this is the intent of the question.
Comment: @Peter I have edited the question, $A$ has a peculiar form, is essentially nonnegative. Also $\sum_{i=1}^{n}A_{ij}\le 0$. I think assuming that characteristic polynomial known makes the result for a particular system right? Or am I missing something? Thanks
Comment: Are you interested in easily calculable condition or abstract characterization?
Comment: A necessary condition is that the matrix can be diagonalized.
Comment: @Peter Yes I am looking for a condition that is necessary for $A$ to have real and distinct eigen values.
Comment: @Peter please elaborate or help me to show that if the characteristic polynomial of $A$ has n
distinct roots, then $A$ is diagonalizable? As A is stable we can diagonalize $A$ right, such as the one with eigen values as diagonal entries can be obtained. Thank you for your time
Comment: Can we assume that the characteristic polynomial is known ? In this case, there might be easier criterions. To check, whether a matrix is diagonalizable is probably more difficult than checking the characteristic polynomial.
Comment: There is a following abstract characterization not using the characteristic polynomial: Hermitian matrix $A$ has a degenerate eigenvalue if and only if the $*$-algebra of all matrices commuting with $A$ contains a $*$-subalgebra isomorphic to $M_2(\mathbb C)$. However, I doubt this condition is computionally tractable for nontrivial matrices $A$.
Comment: @Blazej I am quite unfamiliar with these terms..not a mathematician....Thank you for your comment. So this is still an open problem...I mean there does not exist a theorem that states necessary conditions for the matrix roots to be real and distinct right?
Answer: You already got a sufficient condition for realness (matrix being hermetian) but a condition for distint-ness is not that easy.
You could use Gerschgorin-circles for a start.
This theorem gives you circles in the complex plane with midpoints on the diagonal entries. It states, that each eigenvalue lies in it's overlapping circles. If two (or more) overlap, the eigenvalues lie in the union of both circles (not necessarly in the intersection!)
So if every circle is distinct, all eigenvalues are unique.
If the circles overlap, the still can be unique!
Answer: As pointed out by Peter, it is sufficient that the characteristic polynomial $\mathrm{det}(A-t I)$ has no double zeros. While this condition might be difficult to check in general, you have rather special form of $A$. You can compute the characteristic polynomial (by hand or using some software like mathematica to make it faster and less painful) and try to verify this property. This might be possible to do even without finding all roots explicitly. For example you can find all roots of the derivative of characteristic polynomial (this is third order rather than fourth so much easier) and then verify whether any of these is a root of the characteristic polynomial of $A$. Another method (probably more useful for larger matrices) is to extract some partial information (using tools such as polynomial discriminant, Descartes rule of signs or Vieta formulas - look up e.g. wikipedia for these). The approach with Greschgorin circles pointed out in one of the answers also looks promising.
Answer: For the eigenvalues to be real matrix has to be Hermitian $v^{\dagger}Aw=w^{\dagger}A^{\dagger}v$
For any $v, w\in\mathbb{C}$. And here $F^{\dagger}=\bar{F}^{T}$. Don't know what to say about them being distinct.
Comment: This is not right. $\pmatrix{1&1\\ 0&1}$ is not Hermitian, but its eigenvalues are real.


Getting an instance of the subclass extending a superclass when a method is called

Question: So, I want to be able to get an instance of a subclass that is being run when it calls a method from the super class. For example, if I had this class:
public class A {
public void aMethod() {
    //Here is where I want to see if class B is calling the code
}
}

public class B extends A {
}

public class C {
B b = new B();
b.aMethod();
}

And, like the comment says, I want to check, in aMethod, if class B, the subclass of class A, is calling the code.
Comment: If you want to "see if class B is calling the code", you can say `this instanceof B` (which is also `true` if it's a subclass of `B`), or `this.getClass().equals(B.class)` (which is `true` only for `B`, not its subclasses).  But: **don't do this.**  99.9967% of the time you just need to rethink your design and use polymorphism properly.
Comment: The fact that `B` extends `A` here is basically irrelevant; you haven't created an instance of `B` here...
Comment: The code doesn't even compile.
Answer: As has been pointed out to you, there is almost never a good reason to do this and I agree that you should be using polymorphism instead. However, if you "need" to do this or just want to know how to go about doing something like this, you can use instanceof on this inside of the method:
class A {
    public void aMethod() {
        if (this instanceof B) {
            System.out.println("I'm a B!");
        }
    }
}

public class B extends A {

    public static void main(String[] args) {
        B b = new B();
        b.aMethod();
    }
}

Comment: That's the correct way to answer the question, but I want to reemphasize what I said in my comment: **don't do it**.  Polymorphism was invented so that programmers wouldn't have to write stuff like this.
Comment: I agree. Updated the answer to re-iterate that.
Answer: public class A {

    public void aMethod() {
        if(this.getClass() == B.class){
            System.out.println("huhuhuuuuuuuuuuuuuuuuu");
        }
    }
}

public class B extends A {

}

public class C {

    public static void main(String[] args) {
        B b = new B();
        b.aMethod();
    }
}

Answer: Note that this finds a call at any depth:
for(final StackTraceElement element : Thread.currentThread().getStackTrace()) {
  if (element.getClassName().equals(B.class.getName())) {
    System.out.println("BINGO");
  }
}

If you want to check only a limited depth, don't iterate through all of the array.
This can be useful e.g. if some framework forces you to have a special method or a no-arg constructor to be present, but you don't want any developer to call this method directly. (Yes, it is a hack, but sometimes odd frameworks force you to do odd things). Then you can have an assertion in the unwanted method that just throws an exception if it is called by the wrong corner of your code.
Anyway you should try do avoid things like this if possible.
Answer: Check here: How to get the caller class in Java
The 2nd part of the answer from @dystroy is probably a start.


(Piano) Fast "alternating" octaves on the left hand - technique or just muscle power?

Question: So, I'm trying to learn Hiromi's "The Tom and Jerry Show", but I'm stumped at a certain point, 1:58 in this video.
She seems to be playing octaves on the left hand, but first the lower note, then the higher, in quick succession. When I try to do that, not only can I not even come close to that speed, but after just a few seconds, my arm is burning and I can't keep going.
I came here to ask if there's any "technique" involved in this specific part (a name for these "alternating octaves" would be nice, if there is one!), or if it's just a matter of practicing it over and over and building the muscular strength to do it.
Thanks!
Answer: I'll talk about broken octaves generally rather than respond specifically about the video link, since it may not stay up.
Broken octaves are a standard part of piano technique from Mozart onward.
Forearm rotation is the major source of power in playing them. I suggest the following simple exercises to get used to it, if it's new to you.
Firstly, try playing a slow, mezzo forte tremolo on C in the left hand, that is, C with the little finger, then C with the thumb, then C with the little finger, and so on. Exaggerate the rotational movement: rotate the forearm far to the left to put 5 on the lower note, then rotate far to the right to put 1 on the upper note, and so on. Gradually increase the rotational movement up through forte to fortissimo. If done well, you should manage fortissimo with absolutely minimal effort.
Secondly, you can move on to broken octaves proper, playing up and down C D E F G F E D C. Here a little more practice is needed due to the changing position of the hand. Continue to exaggerate the rotational element until you're quite sure you've "got it" and are achieving an effortless forte.
Later, when you need speed, you can look at minimizing the rotation - as speed is all about minimizing unnecessary movement - but it will always be present.
Finger action is involved in broken octaves too, but for now look upon it as fine adjustment to make sure that the right key is played, not as the source of power.
With practice, you'll find this forearm rotation can be done very fast and effortlessly. It can be used for trills, tremolos, broken octaves, and for power in non-repeating patterns too.
Specific advice about the pains you have suffered shouldn't be given without observation. Generally speaking though, don't open the hand wider than necessary, and don't tilt it toward the thumb or little finger. That is sometimes necessary, but not for broken octaves unless they reach extreme positions on the keyboard.
Comment: Thank you very much! This was very clear, and exactly what I needed. :)


Why does ca.jo has a minimum lag order of 2?

Question: I am trying to use urca library to do cointegration test, and its function ca.jo, which conducts the Johansen procedure on a given data set.
I think a lag order of 1 is possible for a cointegrated VECM, which means it does not have short term error correction. For example, we have VAR(1)
$$
X_t=\Pi_1X_{t-1} + \epsilon_t
$$
and its VECM is
$$
\Delta X_t = \Pi X_{t-1} + \epsilon_t
$$
where $\Pi=\Pi_1-I_2$
Why does ca.jo specify the minimum lag order to be 2? Is there a reason behind it?
Comment: Maybe [this](https://stat.ethz.ch/pipermail/r-sig-finance/2008q4/003255.html) can help. You can find the detailed explanation in the link.
Answer: I updated the package tsDyn (version 0.9-40 submitted to CRAN), so that its VECM() function can handle your case of lag=1. Note that:

With function VECM(), use lag=0 for the case you described as lag=1
A warning will be printed, as fevd(), irf(), predict() et al are not guaranteed to work
If you want no intercept, use: include="none"

Example:
<code>library(tsDyn)
data(barry)
summary(VECM(barry, lag=0, estim="ML"))

#############
###Model VECM
#############
Full sample size: 324   End sample size: 323
Number of variables: 3  Number of estimated slope parameters 6
AIC -4871.5     BIC -4848.83    SSR 29.3275
Cointegrating vector (estimated by ML):
   dolcan    cpiUSA    cpiCAN
r1      1 -0.021234 0.0402079

            ECT                 Intercept
Equation dolcan -0.0004(0.0011)     0.0024(0.0030)
Equation cpiUSA -0.0436(0.0155)**   0.3685(0.0413)***
Equation cpiCAN -0.0824(0.0214)***  0.4649(0.0572)***
</code>
Comment: @Michael hope this answer is useful to you?
Comment: Thanks @Matifou, really appreciate your help! I missed your comment. My deepest apologies for replying 7 years later!
Comment: haha no worries, you are good!
Answer: Well I guess the reason is simply code simplicity and time... You are right that such a VECM can be estimated, but allowing it would have required to add several exceptions in the code, eventually skipping the "short term parameters concentration" step in the case lag=1, which maybe the author was not keen to do.
But with the code at hand, you can easily adapt it for your case ;-)


Why can't these generic type be inferred?

Question: I'm writing a Vuex store for Vue 3, and the following issue has been bother me recently.
Please consider following minimal reproducible example:
interface Options<State, G extends Getters<State>> {
  state: State
  getters: G,
  mutations: {
    [P: string]: (state: State, getters: G) => void
  }
}

interface Getters<State> {
  [P: string]: (state: State) => any
}

function createStore<State>(options: Options<State, Getters<State>>) {
  return options
}

createStore({
  state: {
    count: 0
  },
  getters: {
    isOdd: (state) => state.count % 2 === 1
  },
  mutations: {
    incrementIfOdd (state, getters) {
      if (getters.isOdd) {
               // ^ a this cannot be inferred to Boolean here.
        ++state.count
               // ^ ok, it is number.[enter image description here][1]
      }
    }
  }
})

Codesandbox
IDE snapshot
Further code info can be found here: https://github.com/js-cosmos/vuex-light/issues/11
Thanks for your help :D.

Update:
I try to remove wrapped option and it works!
To simplify the example code:
// This works
function spreadOptionsFn<
  State extends Record<any, any>,
  Getters extends Record<any, ({ state }: { state: State }) => any>,
  Mutations extends Record<any, ({ state, getters }: { state: State; getters: Getters }) => any>
>(state: State, getters: Getters, mutations: Mutations) {}

spreadOptionsFn(
  { stateKey: 'state' },
  { getterKey: ({ state }) => state.stateKey },
  { mutationKey: ({ state, getters }) => [state.stateKey, getters.getterKey] },
)

// But not this
function wrappedOptionsFn<
  State extends Record<any, any>,
  Getters extends Record<any, ({ state }: { state: State }) => any>,
  Mutations extends Record<any, ({ state, getters }: { state: State; getters: Getters }) => any>
>({ state, getters, mutations }: { state: State; getters: Getters; mutations: Mutations }) {}

wrappedOptionsFn({
  state: { stateKey: 'state' },
  getters: { getterKey: ({ state }) => state.stateKey },
  mutations: { mutationKey: ({ state, getters }) => [state.stateKey, getters.getterKey] },
})

CodeSandbox
screenshot for type inference

Update 2:
I missing something again, It finally be fixed with the following code:

interface Options<
  State extends Record<any, any>,
  GetterKeys extends string,
  MutationKeys extends string,
> {
  state: State,
  getters: {
    [P in GetterKeys]: ({ state }: { state: State }) => any
  },
  mutations: {
    [P in MutationKeys]: ({ state, getters }: { state: State; getters: {
      [P in GetterKeys]: ({ state }: { state: State }) => any
    } }) => any
  },
}

function wrappedOptionsFn<
  State extends Record<any, any>,
  GetterKeys extends string,
  MutationKeys extends string,
>(options: Options<State, GetterKeys, MutationKeys>) {
}

wrappedOptionsFn({
  state: { stateKey: 'state' },
  getters: { getterKey: ({ state }) => state.stateKey },
  mutations: { mutationKey: ({ state, getters }) => [state.stateKey, getters.getterKey] },
})

Answer: This is because you're using P: string for your mutations and getters, so we don't know what the specific keys are, and therefore their types can be inferred.
You should use extra generic parameters for P here - for the MutationKeys and GetterKeys, which can then be inferred correctly:
interface Options<
  State,
  MutationKeys extends string,
  G extends Getters<State, string>
> {
  state: State;
  getters: G;
  mutations: {
    [P in MutationKeys]: (state: State, getters: G) => void;
  };
}

type Getters<State, Keys extends string> = {
  [key in Keys]: (state: State) => any;
};

function createStore<
  State,
  MutationKeys extends string,
  GetterKeys extends string
>(options: Options<State, MutationKeys, Getters<State, GetterKeys>>) {
  return options;
}

createStore({
  state: {
    count: 0
  },
  getters: {
    isOdd: (state) => state.count % 2 === 1
  },
  mutations: {
    incrementIfOdd(state, getters) {
      if (getters.isOdd(state)) {
        ++state.count;
      }
    }
  }
});

Comment: Thanks for answer: I tried this solution recently, but it still not works correctly.
Comment: Update: Thanks again, it works now. Because I still not provide it to know what is the specified keys.
Comment: awesome! feel free to accept the answer if it solved your question :)


$a_n$ be a sequence in [0,1]. what about f($a_n$)?

Question: consider a strictly increasing function f. let $a_n$ be a sequence in [0,1]. which of following is true about f($a_n$)?

f($a_n$)  is bounded
f($a_n$)  is convergent
f($a_n$)  is bounded but not convergent
f($a_n$)  is unbounded

my attempt:
let f=x, so f($a_n$)=$a_n$. since nothing can be surely said about an except that it is bounded. so f($a_n$) is bounded. plz give your suggestion
Comment: What do *you* think?
Comment: If you really try I'm sure you will be able to prove that it is bounded by using the two pieces of information that you are given: 1) $f$ is stricktly increasing 2) $a_n$ is contained in a bounded interval ($[0,1]$).
Comment: so answer is option 1?
Comment: Does it say something about the domain of $f$?
Comment: no, only that it is strictly increasing.
Answer: Assuming that we are dealing with a strictly increasing function $f:[0,1]\rightarrow\mathbb R$ we conclude that $f(0)\leq f(a_n)\leq f(1)$ for each $n$.
This tells us that the sequence $(f(a_n))_n$ is a bounded sequence.
The sequence can be convergent, but that is not necessary. E.g. let $f$ be prescribed by $x\mapsto x$. Then $f(a_n)=a_n$ and the sequence $(f(a_n))_n$ iff sequence $(a_n)_n$ is convergent.


How to programmatically display an image field in Drupal 7 + default value when needed

Question: I've used field_view_field to display an image field for a specific entity in Drupal. The problem is when that entity doesn't have any value for field. I expect field_view_field to display the default image for field but it doesn't load default value of the field.
How can I do this?
Comment: can you post the code you have that isn't working properly?
Comment: I would start debugging from image_field_prepare_view() where it handles default images.
Comment: My code was:      $user_pic = drupal_render(
        field_view_field('user', $user_loaded, 'field_profile_photo',
          array(
            'label' => 'hidden',
            'settings' => array(
              'image_style' => '170_170'
            )
          )));
Comment: Can you post it in your question instead of the comment? It's easier to read.
Answer: field_view_field is a correct function to use if you want to display node image (if provided) or default (attached to field settings) if not.
$node = node_load($nid);
print render(field_view_field('node', $node, 'field_image')));

Comment: I know and I'm surprised. Even checked if it works on local copy of D7 and everything seems to be ok. @Sebto - are you sure that default image is correctly loaded into field settings form and correctly configured in Manage Display -> Default? Try to dpm field_view_field for random node **with** image and other one **without** image (with default image uploaded).
Comment: According to the question they are already doing this but it isn't showing the default image when it should be.
Answer: In our case we have two set of images

Default image
another is node specific image

i created two block in views in the first view get the default image it will always have the default image
and in the second block render the image if the image field is empty render the whole default block there, below is the sample code
in views block 2 select the image field in the view and exclude it from display
in views global php add the code below
<?php
    $banner = isset($data->field_field_banner)? $data->field_field_banner : '';
    if(!empty($banner)){
      print drupal_render($banner);
    }else{
          print render_view_block_for_noresult('view_name','block_name');
    }
?>

/* function to render default view blocks if no banner is present */
function render_view_block_for_noresult($view_name='',$block_name=''){
        $view = views_get_view($view_name);
        if(isset($view) && !empty($view))
            return $view->preview($block_name);
}

this will help you to print the image and get the default image printed in the view.
Comment: 2 views to display one image seems like overkill. Also you should be able to do this without custom code by putting one view in the empty text setting of the first view so that if the first view returns no results the view in the empty text displays.
Answer: By the way, I find a solution for my problem. If there aren't any value for field, it retrieves field instance information then load default image of field and display it.
       $user_loaded = user_load($uid);
if ($user_loaded->field_profile_photo[LANGUAGE_NONE][0]) {
  $user_pic = drupal_render(
    field_view_field('user', $user_loaded, 'field_profile_photo',
      array(
        'label' => 'hidden',
        'settings' => array(
          'image_style' => '170_170'
        )
      )));
}
else {
  $instance = field_info_instance('user', 'field_profile_photo','user');
  $user_loaded->field_profile_photo[LANGUAGE_NONE][0] = (array)file_load($instance['settings']['default_image']);
  $user_pic = drupal_render(
    field_view_field('user', $user_loaded, 'field_profile_photo',
      array(
        'label' => 'hidden',
        'settings' => array(
          'image_style' => '170_170'
        )
      )));
}

Answer: Here's an example of how to use a field instance's default image as a fallback when the individual image field itself is empty.
To briefly explain the concept, use field_get_items() to attempt to get the image attached to the entity (e.g. node, user, taxonomy_term, ...), then fallback to field_info_instance() if an image has not been uploaded.
Once an image is available to work with, set the $file variable to the image reference, which will get rendered after calling field_view_value().
$field_image = field_get_items('node', $node, 'field_image');

if (!empty($field_image)) {
  $file = $field_image[0];
}
else {
  $info = field_info_instance('node', 'field_image', 'blog');

  if (!empty($info) && $info['settings']['default_image'] > 0) {
    $default_image_fid = $info['settings']['default_image'];

    $file = (array) file_load($default_image_fid);
  }
}

if ($file) {
  $image = field_view_value('node', $node, 'field_image', $file, array(
    'type' => 'image',
    'settings' => array(
      'image_style' => NULL,
    ),
  ));

  print render($image);
}

All of this logic could be wrapped up into a helper function or simply used wherever needed.


Substituir números que estão dentro de uma palavra

Question: Desejo remover números em meio à letras, porém não desejo remover todos os números do texto, exemplo:
Vini12cius

Quero transformar em Vinicius, mas sem alterar um possível CPF que virá após, criei o seguinte regex:
r = re.sub(r'([0-9])','',"")

Porém, ele elimina todos os números do texto, mesmo os que não estejam entre caracteres, também tentei:
r = re.sub(r'([a-z]*[0-9]*[a-z])','',"")

Mas também não obtive sucesso.
Comment: Mantendo os `[a-z]` dentro dos parenteses, você os captura junto, fazendo que sejam, também, substituídos. Reveja o seu grupo de captura. Aproveitando, e se foram coisas como "123foo" ou "foo123"? Deve substituir ou não?
Comment: sim, nestes casos podem ser removidos, o meu problema está nos números que estão sozinhos, pois não desejo que sejam removidos
Answer: Eu prefiro fazer isso com uma função de substituição:
>>> def f(m):
...     text = m.group()
...     if text.isdigit(): # se for tudo digito
...         return text
...     else:
...         return re.sub(r'\d', '', text)
...
>>> re.sub(r'\w+', f, '4lfr3do rodr1g0 marc05 12345')
'lfrdo rodrg marc 12345'

Comment: Muito Obrigado, deu certo!!
Comment: Sabe como eu poderia fazer agora se quisesse realizar o contrário? Ex: 1234678ab910 e transformar em : 12345678910
Comment: Seria só trocar `r'\d'` por `r'\D'` @HVLopes
Comment: Perfeito, agradeço amigo
Answer: Você pode utilizar esta Expressão Regular: \d+(?=[a-zA-Z]+)|(?<=[a-zA-Z])\d+
Em que a demo do Regex101 pode ser vista.
Código
import re

testes = ("Vini12cius 000.000.000-00",
            "Vini12cius 00000000000",
            "Vinicius12 00000000000",
            "12Vinicius 00000000000",
            "000.000.000-00 Vini12cius",
            "00000000000 Vini12cius",
            "00000000000 Vinicius12",
            "00000000000 12Vinicius")

padrao_regex = re.compile(r"\d+(?=[a-zA-Z]+)|(?<=[a-zA-Z])\d+")
substituicoes = [re.sub(padrao_regex, "", elemento_teste) for elemento_teste in testes]
if substituicoes:
    for substituicao in substituicoes:
        print(substituicao)

Ideone
Comment: Obrigado!! também funcionou , agradeço !!