Postfix forwarding issue

Question: I've followed flurdy's postfix set up, however I seem to have a problem when it comes to forwarding emails.  For example, in my maildb database - I have a table Alias which maps mail to a destination. For example: mail=firstname.lastname@example.com to destination=firstname.lastname@example.com.
When tailing the mail.logs I see>

postfix/smtpd[10912]: connect from mail-wi0-f170.google.com[22.214.171.124]
postfix/smtpd[10912]: Anonymous TLS connection established from mail-wi0-f170.google.com[220.127.116.11]: TLSv1 with cipher ECDHE-RSA-RC4-SHA (128/128 bits)
postgrey[29500]: action=pass, reason=client whitelist, client_name=mail-wi0-f170.google.com, client_address=22.214.171.124, email@example.com, firstname.lastname@example.com
postgrey[29500]: cleaning up old logs...
postfix/smtpd[10912]: D5B6D6025: client=mail-wi0-f170.google.com[22.214.171.124]
postfix/cleanup[10927]: D5B6D6025: email@example.com
postfix/qmgr[10881]: D5B6D6025: email@example.com, size=1913, nrcpt=1 (queue active)
postfix/smtpd[10912]: disconnect from mail-wi0-f170.google.com[188.8.131.52]
postfix/smtp[10929]: D5B6D6025: firstname.lastname@example.com, firstname.lastname@example.com, relay=ASPMX.L.GOOGLE.com[22.214.171.124]:25, delay=0.62, delays=0.21/0.02/0.17/0.22, dsn=2.0.0, status=sent (250 2.0.0 OK 1359385356 f5si212603wja.5 - gsmtp)
postfix/qmgr[10881]: D5B6D6025: removed

However, firstname.lastname@example.com doesn't receive anything. I have the following postfix set up.

alias_database = hash:/etc/postfix/aliases
alias_maps = hash:/etc/postfix/aliases
append_dot_mydomain = no
biff = no
broken_sasl_auth_clients = no
config_directory = /etc/postfix
delay_warning_time = 4h
disable_vrfy_command = yes
inet_interfaces = all
inet_protocols = ipv4
local_recipient_maps =
mailbox_size_limit = 10737418240
maximal_backoff_time = 8000s
maximal_queue_lifetime = 7d
minimal_backoff_time = 1000s
mydestination = mail.mymail.com, localhost, localhost.mymail.com
mynetworks = 127.0.0.0/8, 192.168.1.0/24
mynetworks_style = host
myorigin = mymail.com
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_helo_timeout = 60s
smtp_sasl_type = cyrus
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_tls_note_starttls_offer = yes
smtp_tls_security_level = may
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
smtpd_client_restrictions = reject_rbl_client sbl.spamhaus.org, reject_rbl_client blackholes.easynet.nl, reject_rbl_client dnsbl.njabl.org
smtpd_data_restrictions = reject_unauth_pipelining
smtpd_delay_reject = yes
smtpd_hard_error_limit = 12
smtpd_helo_required = yes
smtpd_helo_restrictions = permit_mynetworks, warn_if_reject reject_non_fqdn_hostname, reject_invalid_hostname, permit
smtpd_recipient_limit = 16
smtpd_recipient_restrictions = reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service inet:127.0.0.1:10023, permit
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain =
smtpd_sasl_security_options = noanonymous
smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, warn_if_reject reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unauth_pipelining, permit
smtpd_soft_error_limit = 3
smtpd_tls_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file = /etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_security_level = may
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
unknown_local_recipient_reject_code = 450
virtual_alias_maps = mysql:/etc/postfix/mysql_alias.cf
virtual_gid_maps = static:5000
virtual_mailbox_base = /var/spool/mail/virtual
virtual_mailbox_domains = mysql:/etc/postfix/mysql_domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql_mailbox.cf
virtual_transport = virtual
virtual_uid_maps = static:5000

Can someone help point me in the right direction? Totally lost.
Cheers
Comment: check this link  http://superuser.com/questions/332389/postfix-forwarding-e-mail-to-gmail-not-working
Comment: Your log shows that the message was delivered successfully to google and google mail server accepted it. It appears to me firstname.lastname@example.com might have some filters, forward rules etc. Did you check the spam folder?
Comment: It's strange - there's no filters set up and nothing in Spam. Not sure how else to check... {edit} - just set forwarded to another gmail account, and appears to have worked. Strange why the first didn't.
Comment: Spot on! Cheers
Answer:
postfix/smtp[10929]: D5B6D6025: firstname.lastname@example.com,
  firstname.lastname@example.com, relay=ASPMX.L.GOOGLE.com[188.8.131.52]:25,
  delay=0.62, delays=0.21/0.02/0.17/0.22, dsn=2.0.0, status=sent (250
  2.0.0 OK 1359385356 f5si212603wja.5 - gsmtp)

This message was accepted by gmail; it is out of postfix's hands.
You'll have to ask Gmail, or possibly look in your spam folder.

Postfix forwarding issue


Object Oriented Design / Design Pattern scenario

Question: I have 3 different type of shape diagrams say Rectangle, Cube, Circle, I want to define classes for them such that

All classes would have Title & Color property/method,
Circle & Rectangle would have additional method Area,
Similarly Cube would have Volume method rather than Area method.

There is a method in which I get the reference of of 'object', following is sample method
public void ShapeClicked(object obj)
{
// Check the type of obj & type cast it accordingly & call the method on that object
    object obj = new Circle();

    if (obj is Circle)
    {
        Circle circleObj  = (Circle)obj;
        circleObj.GetArea();
    }
    else if (obj is Rectangle)
    {
        Rectangle rectangleObj = (Rectangle)obj;
        rectangleObj.GetArea();
    }
    else if (obj is Cube)
    {
        Cube cubeObj = (Cube)obj;
        cubeObj.GetVolume();
    }
}

How can I design my classes such that in 'ShapeClicked(object obj)' method

a) I need not to check the type every time (should happen at run time), (This is important for me because I have many methods like 'ShapeClicked' which requires me checking the type)
b) if object is of Circle then it would get only Area method, similarly for Cube object it would get only Volume method.

I can think of two approaches

Put all the methods & properties in base class & only override required methods in derive class. Create a Factory method/class which would return the reference of Base class. With this approach my 'b' requirement does not meet
Put only common methods/property (like color) in base class & add additional methods in derive class. This does not solve #a :(

Can anybody suggest me some solution which solves both #a & #b
Comment: Is this real code or just an arbitrary sample?  Right now your sample is fetching a numeric from the shape, but you don't show what you do with it.
Answer: Introduce a new interface.
public interface IMeasurable
{
    someReturnType GetMeasure();
}

public class Circle : IMeasurable
{
    //some other methods

    public someReturnType GetMeasure() { return GetArea(); }
}

public class Cube : IMeasurable
{
    //some other methods

    public someReturnType GetMeasure() { return GetVolume(); }
}

Update
Your method would look like:
public void ShapeClicked(object obj)
{
    var measurable = obj as IMeasurable;
    if (measurable == null)
        throw new InvalidOperationException(string.Format("We can only work with measurable types, which {0} is not.", obj.GetType());

    var measure = measurable.GetMeasure();
}

Comment: Thanks for your response, You added'GetMeasure' method to both cicle & cube, & from there calling their respective methods.          I have lots of methods like GetVolume/GetArea some are common to both circle,cube & rest are specific to that class. how would it solve both #a & #b which I mentioned in my question?
Comment: Implement IMeasurable in the baseclasses.
Comment: Could you please answer http://stackoverflow.com/questions/9511137/is-the-solution-design-optimal-c-sharp-3-tier ?
Answer: Yes.
You should have a base class for all shapes and have a method ShapeClicked() in the base class.
class Shape
{
-tile
-color
ShapeClicked()
}

class PlanarShape extends Shape
{
-area
Area()
}

class SpatialShape extends Shape
{
-volume
Volume()
}

class Circle extends PlanarShape
{
ShapeClicked()
}

class Rectangle extends PlanarShape
{
ShapeClicked()
}

class Cube extends SpatialShape
{
ShapeClicked()
}

Then you modify the function as:
public void ShapeClicked(Shape obj)
{
    obj.ShapeClicked();
}

Via polymorphism, your call will be directed to the right class.
Comment: -1 No. It would violate the "is-a" relationship. An interface (composition) is preferred.
Comment: @jgauffin how does it vialote the is-a relationship?
Comment: @LuchianGrigore Atul is working C#. You have given java code :)
Comment: I think the inheritence is appropriate, interfaces are not required.  It doesn't hurt to use them both though (Shape base class implementing the IShape interface).
Comment: if I understood correctly you put 'ShapeClicked' into the base class? 'ShapeClicked' is the consumer & there can be many function like this. Tomorrow there can be new consumers, does that mean I have to modify my base class?
Comment: @AtulSureka nu you don't. That's the point. You override the even in your derived classes without touching the base class.
Comment: Could you please answer http://stackoverflow.com/questions/9511137/is-the-solution-design-optimal-c-sharp-3-tier ?
Answer: Using base types is good when you have common behaviour you want to inherit. In your case, you really have a common way to interact with your types, but how those types behave is quite different.
In this case what you're really trying to do is define a common interface so you can treat your types similarly.
I would define the following:
public interface IShape
{
    string Title { get; }

    string Color { get; }
}

public interface I2DShape : IShape
{
    int GetArea();
}

public interface I3DShape : IShape
{
    int GetVolume();
}

You can then implement I2DShape on Circle and Rectangle, and I3DShape on Cube. Your method then can be implemented as such:
public void ShapeClicked(IShape shape)
{
    var shape2d = shape as I2DShape;

    if(shape2d != null)
    {
        shape2d.GetArea();
        return;
    }

    var shape3d = shape as I3DShape;

    if(shape3d != null)
    {
        shape3d.GetVolume();
    }
}

You still need to check whether a shape is 2D or 3D, but that's just because we've defined Area and Volume as separate things. If you wanted to define them as a singular thing, you could put that on the base interface and have all your types implement that interface.
Comment: The problem with writing conditional code based on type is extensibility.  If later on we need another type of shape we have a lot of work to do.
Comment: It depends on what other methods you are adding aside from Area and Volume.  1D (Length), 2D (Area), and 3D (Volume) seem to cover all the known diagramming dimmensions :)  I like the suggestion if it fits the broader problem you have, but you'd have to give a few more examples.
Comment: As stated, you only need to do the type check if you consider Area and Volume different things (like a sane person). If you want to treat them as the same information, you can create a method `GetAreaOrVolume` that expresses both things on the base `IShape` interface.
Comment: Thanks for your response, As I said there are lots of method like 'ShapeClicked' where I am getting 'object' as a paramter & I don't want type checking at every place. That's why I was thinking of using factory pattern. But the problem with factory pattern is that I have to put every thing in base class (override some in derive class), more importantly one can call wrong method, for e.g Shape.GetVolume() what if Shape is of type Rectangle?
Comment: `ShapeClicked` violates Open/Closed principle & Liskovs Substitution principle.
Comment: As does anything to do with `System.Linq.Expressions`, most XML tree-walking algorithms and 90% of the uses of `as` in .NET. It's not a desirable quality, but then neither is trying to force commonality where there is none.


Whats the difference between a port forwarder and a socks proxy?

Question: Question title describes itself clearly
Comment: Have they anything in common? :p
Answer: The simplest answer is that port-forwarding (as in NAT) is generally transparent to the client, while a SOCKS (or HTTP) proxy requires the client to explicitly use the proxy protocol.
Answer: I agree with the above definitions, though I'd add that NAT and Proxies have a very different purpose. NAT is simply routing: there is no caching, and there is no real "oversight" for lack of a better word. Proxies are put in place for caching, monitoring, traffic shaping. They are very much about control.
So NAT has very little overhead, but doesn't offer many options, while proxies have a much higher overhead (sometimes massively higher), but allow a lot of control.
Answer: A NAT device performs "address translation" (tuple [TCP/UDP port:IP address] to another tuple) whereas a proxy terminates (in networking terms) a protocol layer, performs adaptation (again in networking terms) and rebuilds another a connection towards the destination.
In other words, a NAT tries to be as "transparent" to the client protocol as can be whereas a PROXY is really "two connections back-to-back" (same or different protocols on each side).


Statistical analysis flowchart implementation in R

Question: I have seen lots of flowcharts describing the different questions you should ask yourself when doing statistical analysis and the corresponding tests you should run based on your answer. For instance, you can find some here: Flowcharts to help selecting the proper analysis technique and test
Unfortunately I could not find implementations of such flowcharts. By implementation of the flowchart I mean the program could ask you some questions, and based on your answers would run some test. Do you know if such programs exist? (it would be better in R but implementations in other programming languages are also welcome)
Thanks a lot!
Comment: There is no implementations because the flowcharts describe simple heuristics, while real life cases are much more complicated than this. I would say that the flowcharts are most useful for passing your "applied statistics" course, but not much beyond that.
Comment: I agree with @Tim. I just found one (reference suppressed to protect the guilty as well as the innocent) which said "Normal mean, Non-normal median". I suppose the advice is better than the exact opposite, but you don't have to be a statistician to see that statistical life is too complicated to be reduced to such dichotomies. If I have a Poisson or an exponential, I really want to work with the mean!
Comment: Understood ! I guess the fun of doing stats comes from the fact that it cannot be reduced to a flow chart ;) @Tim you can post an answer and I will validate it ! And also, thank you !
Answer: There is no implementations because the flowcharts describe simple heuristics, while real life cases are much more complicated than this. The flowcharts described by you are connected to, often criticized, "cookbook" approach to statistics. Flowcharts are helpful for passing your applied statistics exams, but in real life may not be that helpful given the complicated nature or real-life statistical problems and datasets. Below you can find few quotes dealing with this approach.
Rasmus Bååth:

In Bayesian statistics you can quickly escape the cookbook solutions,
  once you get a hang of the basics you are free to tinker with
  distributional assumptions and functional relationships. In some way,
  classical statistics (as it is usually presented) is a bit like
  Playmobile, everything is ready out of the box but if the box
  contained a house there is no way you're going to turn that into a
  pirate ship. Bayesian statistics is more like Lego, once you learn how
  to stick the blocks together the sky is the limit. (http://www.sumsar.net/blog/2014/01/bayesian-first-aid/)

Herbert Spirer and Louise Spirer:

Most textbooks offer "cookbook" approach of analysis of data without
  advising the reader what will happen to the recipe if one of the
  ingredients is left out... (Misused Statistics, p. 6)

Michael R. Hulsizer and Linda M. Woolf:

A cookbook approach to teaching of statistics may make the material
  more accessible to students. (...) Students need to decide what to
  bake (what to study), collect the ingredients (data collection),
  prepare the dish (data analysis), finish preparing the dish (data
  analysis), finish preparing the dish (interpretation of results), and
  present the food to one's guests (publication/preparation). (...)
  However, this strategy believes that fact in statistics, data are not
  always neat or precise and researchers can use more than one procedure
  to explore a problem. (A Guide to Teaching Statistics., p. 71)

The quotes are quite random, but should give you some overview of the critique.
The same with flowcharts, they may be helpful with simple, "textbook" problems, but may easily fail in more complicated situations. Furthermore, real-life usage of such flowcharts needs its user to make number of subjective decision, e.g. on critical value of $p$-value, or assessing if sample is "normal" enough etc. so they cannot be applied automatically.


Problems with sizing a custom view in Android

Question: I don't know how to size a custom view the right way. I am new in Android programming, so please be calm!
I have definied chessboard in an own xml file board.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/BoardLayout"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_gravity="center">
    <TableRow>
        <de.xyz.ChessField android:id="@+id/A8" />
        <de.xyz.ChessField android:id="@+id/B8" />
....

Then I definied a layout, where the board is pasted in as a fragment:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteY="81dp">

    <fragment
        android:id="@+id/fragmentBoard"
        android:name="de.xyz.BoardFragment"
        android:layout_width="300dp"
        android:layout_height="00dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Now, I want to implement the onMeasure(int widthMeasureSpec, int heightMeasureSpec) method of the de.xyz.ChessField to set the size of each Field programmaticaly.
I've tried something like that:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Log.i("widthMeasureSpec, heightMeasureSpec", String.valueOf(widthMeasureSpec) + ", " + String.valueOf(heightMeasureSpec));
    setMeasuredDimension(widthMeasureSpec / 8, heightMeasureSpec / 8);
}

But the MeasureSpec values are very strange:
I/widthMeasureSpec, heightMeasureSpec: 788, 788

or
I/widthMeasureSpec, heightMeasureSpec: 1073742218, -2147482860

Can you help me get on the wright way??
An other possiblity is to set the LayoutParam of each ChessField from outside the class, or? What is the best way??
Thank you for your help!!
P.S.: Update, using MeasureSpec. Why isn't there an exact height? How can I calculate it?
Answer: Use MeasureSpec.getSize(int measureSpec) to extract the hight and width from the supplied measure specification.
Then calculate height and width on the those values and use  [View.setMeasuredDimension()](https://developer.android.com/reference/android/view/View.html#setMeasuredDimension(int, int)) to set the height and width
Comment: Thanks for your help! You can take a look on my update


Voltando informações gravadas no banco

Question: Tenho um sistema que está instalado em uma rede instável, minha dúvida é o seguinte, se em algum momento na minha gravação eu perder a conexão com o banco de dados, como eu faço para desfazer  o que foi feito no banco de dados? Se eu colocar:
try
 ....
 query1.post;
 query2.post;
 commit;
except
 rollback;

Isso funcionaria? Acho que não, pois se no segundo Post, eu perder a conexão com o banco o rollback também não vai funcionar?
Answer: Sim vai, você tem que estar em uma transação para isso, é claro. Mesmo que não consiga executar o rollback, o commit também não será executado e é somente no commit que as informações são salvas. Como a conexão foi interrompida sem informar ao banco, ele provavelmente irá segurar a conexão e a transação, até estourar o timeout, então ele mesmo irá descartar tudo.
Esse é o principio da Atomicidade que deve existir nos mecanismos de banco de dados: https://technet.microsoft.com/pt-br/library/ms190612%28v=sql.105%29.aspx?f=255&MSPPError=-2147217396
Answer: Você deve iniciar uma transação
Considerando
dbConexao - o nome do componente de conexão ao banco
query1 e query 2 - query com instruções em sql.
dbConexao.starttransaction;
Try
  Query1.execsql;
  Query2.execsql;

  dbConexao.commit;
except
  dbconexao.rollback;
end;

Pode haver variação dos comandos se for dbexpress, firedac ou outro. Mas esta é a sequencia correta dos comandos.
Answer: Faz um tempo que não programo em Delhi, mas acho que seria mais ou menos assim:
qry1.post
qry2.post
...
qryN.post

try:
   commit
except
   Implmentação

Voltando informações gravadas no banco


mask não é uma função

Question: estou com erro em uma função mask do jQuery.
Eis meu código:
//############## MASK INPUT
$(".formDate").mask("99/99/9999");
$(".formTime").mask("99/99/9999 99:99");
$(".formCep").mask("99999-999");
$(".formCpf").mask("999.999.999-99");

$('.formPhone').focusout(function () {
    var phone, element;
    element = $(this);
    element.unmask();
    phone = element.val().replace(/\D/g, '');
    if (phone.length > 10) {
        element.mask("(99) 99999-999?9");
    } else {
        element.mask("(99) 9999-9999?9");
    }
}).trigger('focusout');

O erro retornado pelo console é:
TypeError: $(...).mask is not a function

A documentação do erro:
documentação do erro
o include do js:

o conteúdo do maskinput.js
  /*
    Masked Input plugin for jQuery
    Copyright (c) 2007-2013 Josh Bush (digitalbush.com)
    Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
    Version: 1.3.1
*/
(function(e){function t(){var e=document.createElement("input"),t="onpaste";return e.setAttribute(t,""),"function"==typeof e[t]?"paste":"input"}var n,a=t()+".mask",r=navigator.userAgent,i=/iphone/i.test(r),o=/android/i.test(r);e.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},dataName:"rawMaskFn",placeholder:"_"},e.fn.extend({caret:function(e,t){var n;if(0!==this.length&&!this.is(":hidden"))return"number"==typeof e?(t="number"==typeof t?t:e,this.each(function(){this.setSelectionRange?this.setSelectionRange(e,t):this.createTextRange&&(n=this.createTextRange(),n.collapse(!0),n.moveEnd("character",t),n.moveStart("character",e),n.select())})):(this[0].setSelectionRange?(e=this[0].selectionStart,t=this[0].selectionEnd):document.selection&&document.selection.createRange&&(n=document.selection.createRange(),e=0-n.duplicate().moveStart("character",-1e5),t=e+n.text.length),{begin:e,end:t})},unmask:function(){return this.trigger("unmask")},mask:function(t,r){var c,l,s,u,f,h;return!t&&this.length>0?(c=e(this[0]),c.data(e.mask.dataName)()):(r=e.extend({placeholder:e.mask.placeholder,completed:null},r),l=e.mask.definitions,s=[],u=h=t.length,f=null,e.each(t.split(""),function(e,t){"?"==t?(h--,u=e):l[t]?(s.push(RegExp(l[t])),null===f&&(f=s.length-1)):s.push(null)}),this.trigger("unmask").each(function(){function c(e){for(;h>++e&&!s[e];);return e}function d(e){for(;--e>=0&&!s[e];);return e}function m(e,t){var n,a;if(!(0>e)){for(n=e,a=c(t);h>n;n++)if(s[n]){if(!(h>a&&s[n].test(R[a])))break;R[n]=R[a],R[a]=r.placeholder,a=c(a)}b(),x.caret(Math.max(f,e))}}function p(e){var t,n,a,i;for(t=e,n=r.placeholder;h>t;t++)if(s[t]){if(a=c(t),i=R[t],R[t]=n,!(h>a&&s[a].test(i)))break;n=i}}function g(e){var t,n,a,r=e.which;8===r||46===r||i&&127===r?(t=x.caret(),n=t.begin,a=t.end,0===a-n&&(n=46!==r?d(n):a=c(n-1),a=46===r?c(a):a),k(n,a),m(n,a-1),e.preventDefault()):27==r&&(x.val(S),x.caret(0,y()),e.preventDefault())}function v(t){var n,a,i,l=t.which,u=x.caret();t.ctrlKey||t.altKey||t.metaKey||32>l||l&&(0!==u.end-u.begin&&(k(u.begin,u.end),m(u.begin,u.end-1)),n=c(u.begin-1),h>n&&(a=String.fromCharCode(l),s[n].test(a)&&(p(n),R[n]=a,b(),i=c(n),o?setTimeout(e.proxy(e.fn.caret,x,i),0):x.caret(i),r.completed&&i>=h&&r.completed.call(x))),t.preventDefault())}function k(e,t){var n;for(n=e;t>n&&h>n;n++)s[n]&&(R[n]=r.placeholder)}function b(){x.val(R.join(""))}function y(e){var t,n,a=x.val(),i=-1;for(t=0,pos=0;h>t;t++)if(s[t]){for(R[t]=r.placeholder;pos++a.length)break}else R[t]===a.charAt(pos)&&t!==u&&(pos++,i=t);return e?b():u>i+1?(x.val(""),k(0,h)):(b(),x.val(x.val().substring(0,i+1))),u?t:f}var x=e(this),R=e.map(t.split(""),function(e){return"?"!=e?l[e]?r.placeholder:e:void 0}),S=x.val();x.data(e.mask.dataName,function(){return e.map(R,function(e,t){return s[t]&&e!=r.placeholder?e:null}).join("")}),x.attr("readonly")||x.one("unmask",function(){x.unbind(".mask").removeData(e.mask.dataName)}).bind("focus.mask",function(){clearTimeout(n);var e;S=x.val(),e=y(),n=setTimeout(function(){b(),e==t.length?x.caret(0,e):x.caret(e)},10)}).bind("blur.mask",function(){y(),x.val()!=S&&x.change()}).bind("keydown.mask",g).bind("keypress.mask",v).bind(a,function(){setTimeout(function(){var e=y(!0);x.caret(e),r.completed&&e==x.val().length&&r.completed.call(x)},0)}),y()}))}})})(jQuery);

Comment: Verificou se o plugin é compativel com essa versão? edite a pergunte e adicione os 'imports' dos arquivos javascript.
Comment: Importou o jquery?
Comment: Adicionou o Javascript da máscara no seu projeto?
Comment: acabei de ver no site do plugin, ele é compatível somente com a versão jQuery 1.9

Alguém conhece algum plugin de máscara que seja compatível do jQuery 3?
Comment: sim, estou usando o jQuery mais atual, versão 3
Comment: editei e adicionei o conteúdo do arquivo
Comment: não consigo encontrar essa documentação no jquery, pelo menos no deprecated não encontrei nada
Comment: Ja tentou esse aqui https://github.com/igorescobar/jQuery-Mask-Plugin
Comment: estava tentando ele, mas estou achando muito difícil... mas valeu pela dica
Comment: @Jardel, na verdade é muito simples. Veja esses exemplos que criei pra você (com jQuery 3): https://jsfiddle.net/lbclucascosta/u8v1aLeb/
Comment: Dá uma olhada no repositório da jquery: https://plugins.jquery.com/?s=mask
Answer: Fiz algo parecido estes dias. Criei um input para o telefone e criei esse código para o id:
    $(function(){
        $("#txtTelefone").mask("(99) 9999-9999?9");
        $("#txtTelefone").blur(function(event) {
            if($(this).val().length == 15){
                $('#txtTelefone').mask('(99) 99999-999?9');
            } else {
                $('#txtTelefone').mask('(99) 9999-9999?9');
            }
        });
    });

O plugin utilizado foi o https://plugins.jquery.com/maskedinput/
Testei no meu projeto e funcionou com https://code.jquery.com/jquery-3.1.1.min.js

mask não é uma função


Test whether the function $\frac{x}{2}+\frac{1}{x}$ is contraction or NOT

Question:
Let , $X=\{x\in \Bbb R: x\ge 1\}$. Define a map $f:X\to X$ by $\displaystyle f(x)=\frac{x}{2}+\frac{1}{x}$ for all $x\in X$. Examine if $f$ is contraction map or not w.r.t. usual metric on $\Bbb R$. Find the smallest $\lambda$, as contraction constant.

We have $|f(x)-f(y)|=\left |\left(\frac{1}{2}-\frac{1}{xy}\right)(x-y)\right |\le |x-y|.\left(\frac{1}{2}+\frac{1}{|xy|}\right)\le \frac{3}{2}|x-y|$
From here how I can say that $f$ is a contraction map ?
As, $x,y\ge 1$ so , $1/xy \le 1$. If we take $x,y\in X$ such that $1/xy=1/4$ then the constant $\lambda=1/2+1/4=3/4<1$. But $f$ to be contraction we have to show for all $x,y\in X$ , $|f(x)-f(y)|\le \lambda|x-y|$. So why I will take $x,y$ such that $1/xy=1/4$ ?
Answer: You gave up too much when you used the triangle inequality to get
$$\left|\frac12 -\frac{1}{xy}\right| \le \left(\frac12 + \frac{1}{xy}\right).$$
Since $x,y\ge 1, 0 < \displaystyle \frac{1}{xy}\le 1$, as you said. So the greatest distance $\displaystyle \frac{1}{xy}$ can have from $\displaystyle \frac12$ is $\displaystyle \frac12$.
Now you have a contraction. Before, with Lipschitz constant $\displaystyle \frac32$, you did not have a contraction.
Comment: Okay. Here's what I'm saying. You've shown that $|f(x) - f(y)| \le \displaystyle\frac12 |x-y|$ for all $x,y$ in your domain. Now I want you to show that you $\textit{cannot}$ improve that constant out front. Show that for some $x,y$, you have equality $|f(x) - f(y)| = \displaystyle \frac{1}{2}|x-y|$. If you do, you will be done. Because that means you can't say $|f(x)-f(y)|\le \alpha |x-y|$ for all $x,y$ for any $\alpha < \displaystyle \frac12$. This last bit should be easy. There are some easy guesses for where equality should hold.
Comment: I got it. In that case the smallest value of $\lambda$ is $0$. Am I right?
Comment: If $\lambda=0$ held, $f$ would be constant. Is $f$ constant?
Comment: Ok..But $1/xy$ may be $1/2$. Then $\lambda=0$.
How I can calculate the smallest value of $\lambda$ ?
Comment: The point is you want a contraction constant that holds for $\textit{all}$ $x,y$. Not just for those that satisfy $xy=2$. You know that $\displaystyle \frac12$ works. Try to show that it is the $\textit{best}$ constant you can get by showing that there are $x,y$ such that $|f(x)-f(y)| = \displaystyle \frac12 |x-y|$.
Comment: Yeah. Then I've to show only $|f(x)-f(y)|\ge \frac{1}{2}|x-y|$. But I'm unable to show it. In that case I'm trying to show $|1/2-1/xy|\ge 1/2$. But I am not getting any logic for it !
Comment: Oh you know what, the points I had in mind for equality were actually things like $x=2, y= 1/2$. I forgot that that wouldn't be allowed. Still, $1/2$ should be the best you can do. Hold $x=1$ fixed and send $y \to \infty$ and it should be clear.
Answer: Hint: The estimate
$$\Big|\frac12 - \frac1{xy}\Big| \le \frac12 + \frac1{xy}$$
is too bad. Try to find a better estimate. (What are the possible values for $xy$?)
Comment: Well. $1/xy \le 1$  always. Then , $|1/2-1/xy|\le 1/2$. Is it ?
Comment: (And $1/xy \ge 0$). Yes, I think $1/2$ is the best possible constant.
Answer: $f(x)
=\frac{x}{2}+\frac{1}{x}
$
so
$f'(x)
=\frac{1}{2}-\frac{1}{x^2}
\le \frac12
$
for
$x \ge 1$/
Therefor,
by the mean value theorem,
$f(x)-f(y)
=(x-y)f'(z)
$
where
$x \le z \le y$
so that
$|f(x)-f(y)|
\le\frac12|x-y|
$.
If
$M
\lt x < y$,
then,
if
$x \le z \le y$,
$f'(z)
\gt \frac12-\frac1{M^2}
$
so that
$|f(x)-f(y)|
=|x-y||f'(z)|
\gt (\frac12-\frac1{M^2})|x-y|
$
so that
$\frac12$
is the best possible value.
Comment: It says that, for any $c > 0$, there is an $M$ such that $M < x < y$ implies that $|f(x)-f(x)| > (\frac12-c)|x-y|$, so that no constant smaller than $1/2$ will work for all $x$ and $y$.
Comment: From the last line of your answer how I can say that $|f(x)-f(y)|\ge \frac{1}{2}|x-y|$ ? I'm not getting the logic behind it.


How to Play any Major Scale on Guitar

Question: I am new to guitar and started learning Major Scales, so to go by the definition,
<code>A major scale is a diatonic scale. The sequence of intervals between the notes of a major scale is:

whole, whole, half, whole, whole, whole, half
</code>
Now, I am playing G major or A major on an open E string, so the above formula makes sense to me.
But how can I decode Major scales which are played on more than one string, for example the C major scale? How did they come up with the shape?
I want to have an idea of how I can play any Major scale anywhere on the fretboard?
Comment: Could you clarify a little? The definition you found is correct. You just start with any note and go up two whole steps, one half step, three more whole steps, and one more half step.
Comment: related: https://music.stackexchange.com/questions/46190/what-are-guitar-scale-patterns/62239#62239
Answer: So you already know how to construct a scale from semitone jumps, and you know that frets are spaced at semitone (i.e. half step) intervals, and so you were able to put these two things together to form major scales on one string. Now you only have to see the string-to-string intervals in terms of semitones, and you'll be able to utilize more than one string.
The interval between the low E string and the A string is 5 semitones, i.e. 5 frets. And the same with all other neighboring strings, except between G and B it's 4 semitones. So:

Low E -> A : +5
A -> D : +5
D -> G : +5
G -> B : +4
B -> high E : +5

In total, the interval between the open low E and high E strings is 5+5+5+4+5 = 24 semitones = 2 octaves.
With this extra knowledge, can you use more than one string? For example, G is on the 3rd fret of the low E string. Construct the G major scale from there. First, a whole step, +2 : where can you go? You can either stay on the same string and move to the 5th fret, or you can move to the A string. Yes, the open A string is an A, which is the second scale degree in G major.
Some people choose to memorize ready-made scale fingering patterns and diagrams, and that's OK, but I think it's good if you can construct the scales yourself.
Answer: There are many different patterns for playing a major scale on the guitar. All will use the same formula of TTSTTTS (or WWhWWWh) - gaps between successive notes. The simplest one will start on one string, somewhere, and go progressively up that same string in the increments shown. It works, but is hardly practical.
Probably the most common uses all of the strings, and works across them. The way the guitar is tuned, it isn't too difficult. In fact, your hand doesn't have to move up or down the fretboard - it can stay in one position, while the fingers do the work.
Using one finger for each fret, and moving to the next string when needed: for A major - start on bottom string,on the 5th fret, using middle finger. Next note is 2 frets higher, so play it with pinky. Then play 5th string with index, then middle, then pinky.Next string (4) uses index, ring, then pinky. That's one octave.
On to 3rd string. Index, ring, pinky. Then 2nd string, only two notes here - middle, pinky. At the end, on top string, it's index then middle, for the final top A note.
All you've done is translate the TTSTTTS spacings across the strings. The beauty of it is that there are two octaves, and the hand hasn't needed to slide up down or anywhere. By placing that middle finger just about anywhere on the bottom string, and using exactly that pattern, you have all the major scales (yes, all 12) at hand, so to speak!

How to Play any Major Scale on Guitar


Incidence density

Question: Suppose there are $6$ people in a population. During $2$ weeks $3$ people get the flu. Cases of the flu last $2$ days. Also people will get the flu only once during this period. What is the incidence density of the flu?
Would it be $\frac{3}{84 \text{person days}}$ since each person is observed for $14$ days?
Comment: Do you know when each people get the flu?
Comment: @Thierry: Assume that they get the flu on Monday, Tuesday, and Wednesday of the first week.
Comment: Please only use the "Your Answer" field to provide an answer to the question. Do not use it to comment or reply to comments. Since you're new here, it may help you to read our [about page](http://stats.stackexchange.com/about) & our [FAQ](http://stats.stackexchange.com/faq).
Comment: larry, can you confirm that these two accounts, [20010](http://stats.stackexchange.com/users/20010/larry) and [20032](http://stats.stackexchange.com/users/20032/larry), are yours? A moderator will merge them but you'll still need to register your account once and for all.
Answer: The study population is at risk, that is to say that its members should be able to contract the disease in the study.
In general, we look at the first occurrence of a disease in a person. In your example, the 3 cases diagnosed during the study are not at risk from the moment they are diagnosed. The total duration of follow-up for this study was 3*14person-days for those who do not have the disease (3 people times 2 weeks) and say that the study begin the first week on Monday. And the 3 peoples get sick on Monday, Tuesday and Wednesday of the week after, we have 7+8+9 person-days for those who have it.
The true incidence is $\frac{3}{(3*14)+(7+8+9)} = \frac{3}{66 person-days}$.

Incidence density


If someone wanted to do a meta analysis would they be able to use a publication that does not have p-values listed in the publication?

Question: If someone wanted to do a meta analysis would they be able to use a publication that does not have p-values listed in the publication?
Does a meta analysis really need a publication to have a p-value?
Comment: Can you edit to clarify what the exact situation is? Are you trying to use a method for combining p-values but some primary studies do not present them?
Comment: The objective was to assess if an article is worthy for inclusion dependent on them mentioning p values or not. It clearly depends on the value/variable of interest as one user pointed out. Thanks.
Answer: Welcome to CrossValidated!
For every study you want to put into a meta-analysis, you (usually) need two things:

An estimate of the effect (often standardized)
An estimate of the standard error of the effect

That's all.
If the paper has the information that allows you to calculate those two things, you're good to go. That information might be: Means and standard deviations, or standard errors, or p-values, or t-statistics, or confidence intervals (possibly of a difference), etc.
(If you point us to the paper, we might be able to help.)


Meaning of the words "Recitativo" and "tutte le corde" in music?

Question: I am trying to understand Romantic music. I came across this extract from Beethoven's Piano Sonata op.110 from the Allegro man non troppo part.

I want to understand what the words "Recitativo" and "tutte le corde" mean? The internet explained "recitativo" as recitative, and I couldn't find the meaning for "tutte le corde". Examples to understand these terms would help.
Answer: Tutte Le Corde tells you to release the left pedal. The earlier marking Una Corda tells you to press down the left pedal. The left pedal is sometimes called the "soft" pedal. It makes the sound softer by shifting the piano hammers so they only strike one string at a time (hence Una Corda, which is Italian for "one string"). Tutta Le Corde is Italian for "all the strings", which you achieve by lifting the left pedal.
Comment: The mechanism of the left pedal on upright pianos is apparently that it puts a screen between the hammers and the strings instead of shifting the hammers.
Comment: @Dekkadeci in my experience, the more common mechanism on uprights is a bar behind the hammers, on which they rest, which is moved closer to the strings when the left pedal is used, so the hammers have less room to accelerate and therefore strike the strings with a lower velocity.
Answer: From the ever-reliable Dolmetsch page, which really ought to be where every question submitted here should redirect :-=) ,

recitative can be: recitativo secco or recativo parlante  literally
  'dry' (seco) or 'spoken' (parlante    with only a very simple chordal
  accompaniment
  this is a rapid dialogue which carries forward the plot,
  particularly in comic operas
recitativo accompagnato recitativo stromentato
    literally 'accompanied' with the active involvement of the
  orchestra used to accompany more emphatic phrases such as the
  declamatory introduction to an aria


Array not returning correct value

Question: I'm currently trying to apply text to whether the events inside my event group have spaces available or are sold out.
My loop looks at each event in the event group and returns whether they are sold out or available for each specific event. My issue is that it's just returning the same value for both events rather than looking at each specific event so it is returning the wrong value.
It adds these to an array and implodes each one out, but the second value is always wrong. Any ideas?
Even if the second event has hit it's capacity value, it still shows as available
public function getAreEventsAvailableStringMultiple() {
    $availability = null;
    foreach ($this->events as $event) {
        $availability[] = $this->getAreEventsAvailable() ? 'Spaces still available' : 'Sold Out';
    }
    return implode('
 ', $availability);
}

Other function
 public function getAreEventsAvailable() {
        foreach ($this->events as $event) {
            if ($event->getRemainingCapacity() > 0) {
                return true;
            }
        }
        return false;
    }

Comment: calling same function on each iteration `$this->getAreEventsAvailable()` ? I think you are missing param `$this->getAreEventsAvailable($event)`
Answer: You are iterating over $this->events (which is probably an array of event objects), but checking availability for $this, meaning the current object.
If $this->events is array of objects, then you should do this:
   foreach ($this->events as $event) {
       $availability[] = $event->getAreEventsAvailable() ? 'Spaces still available' : 'Sold Out';
   }

Assuming that your Event object has getAreEventsAvailable() method.
If $this->getAreEventsAvailable() returns availability for all the events, there is no need for the foreach loop, just assign the result to $availability:
$availability = $this->getAreEventsAvailable();

EDIT:
Your getAreEventsAvailable() should look like this:
public function getAreEventsAvailable() {
    $availability = [];

    foreach ($this->events as $event) {
        if ($event->getRemainingCapacity() > 0) {
            $availability[] = true;
        } else {
            $availability[] = false;
        }
    }

    return $availability;
}

and then in your getAreEventsAvailableStringMultiple() function:
public function getAreEventsAvailableStringMultiple() {
    $availability = [];

    foreach ($this->getAreEventsAvailable() as $eventAvailable) {
        $availability[] = $eventAvailable ? 'Spaces still available' : 'Sold Out';
    }
    return implode('
 ', $availability);
}

It is not the most ellegant solution, but it should work.
Comment: I have updated my question with the other function. Only returns one result with your suggestion.
Comment: `return` means "exit the function and return this value". So after the first execution of your loop it returns a value and quits the function. I updated my answer.

Array not returning correct value


ckeditor figure caption can't delete without new paragraph

Question: I have a problem with my ckeditor, if I add a image with caption without use before enter or other character I can't use backspace for delete character on image caption, but if I press other character from a to z I see this is put on caption. This is happened only on mozila firefox, and I see a br with _moz_editor_bogus_node="TRUE". After press enter and add a new paragraph this br is removed and never see it, and more then that I can edit image caption (I can delete character from caption) after first paragraph insertion.
Answer: This issue (broken editability of captions) is causes by a regression in Firefox 39. See this bug. The change that caused it will be reverted in Firefox 40, so the feature should work again.
Comment: Thank you, but for moment i will use that hack,  after new version will come will need some time to upgrade all persons her browser but is good to know to fix it if Firefox will solve it. Thank you !
Answer: The reason for what happened that is because on mozila firefox if editoru have no paragrah or div with contenteditable="true" he put a br start at body and you can't modify the text.
My solution was to modify plugin image2 to add this row:
this.wrapper.$.setAttribute("contenteditable","true");

on init element, line 425.
If have problem on mozila with a br who have attribute _moz_editor_bogus_code="TRUE" remeber you need to have 1 div or paragraph with content_editable="true"
Comment: This is an interesting hack. Firefox has now at least two serious bugs related to usage of `contenteditable=false`. https://bugzilla.mozilla.org/show_bug.cgi?id=1181130 and https://bugzilla.mozilla.org/show_bug.cgi?id=911201. CKEditor uses this attribute to make sure that content inside a widget cannot be edited, but it also implements dozen other fixes and improvements for native behaviour of this attribute. So those fixes themselves can give you a feeling that the attribute isn't needed any more. On the other hand, some of them requires presence of this attribute (check keyboard navigation).
Comment: So your hack will fix the issue that you mentioned, but unfortunately will introduce different issues like broken backspace/arrow keys around images. This may lead to crashes, so I would not recommend this hack. PS. Make sure to ping Firefox guys about the issues – this should help.


Remove all places that starts with known part till some known end part

Question: I have some text (JSON) where I need to remove all parts that starts with known text and ends with some known text. Please help me build a regex to remove all that.
String input, part from JSON:
"oge": "GOF",
"original": {
  "report": true,
  "tier": "IA"
},
"pertinentNegative": false,
"populationFrequency": {
  "externalLinks": {
    "7-2-A-T": "https://x.d.org/s/7-d-A-T?dataset=s"
  },
  "maxPop": "South Asian",
  "maxPopAC": 1,
  "maxPopAN": 30,
  "maxPopFreq": 3.276,
  "overallPopAC": 1,
  "overallPopAN": 23,
  "overallPopFreq": 4.22,
  "source": "gnomAD"
}

Known start part : "externalLinks"
Known end part : "maxPop"
I need to remove all that starts with "externalLinks" till "maxPop".
Output after regex work:
"oge": "GOF",
"original": {
  "report": true,
  "tier": "IA"
},
"pertinentNegative": false,
"populationFrequency": {
  "maxPop": "South Asian",
  "maxPopAC": 1,
  "maxPopAN": 30,
  "maxPopFreq": 3.276,
  "overallPopAC": 1,
  "overallPopAN": 23,
  "overallPopFreq": 4.22,
  "source": "gnomAD"
}

Comment: What programming language are you using?
Comment: I am using JAVA
Answer: Use the "replaceAll" method with the following pattern:
\"externalLinks\"[\s\S]+?(?=\"maxPop\")

This will match you every occurrence of "externalLinks" followed by any character, till next occurrence of ""maxPop"" (not included in the match). The lazy operator (?) will allow you to match the least amount possible of characters. Replace every match with the empty string.
Check the demo here.


How to understand SARIMAX intuitively?

Question: I'm trying to understand a paper about electric load forecasting but I'm struggling with the concepts inside, specially the SARIMAX model. This model is used to the predict the load and uses many statistical concepts that I do not understand (I'm an undergrad computer science student -- you can consider me a layperson in statistics). It is not necessary for me to understand completely how it works, but I'd like to at least understand intuitively what is happening.
I've been trying to split SARIMAX into smaller pieces and trying to understand each of these pieces separately and then putting them together. Can you guys help me? Here's what I have so far.
I started with AR and MA.
AR: Autoregressive. I have learned what a regression is, and from my understanding, it simply answers the question: given a set of values / points, how can I find a model that explains these values? So we have, for example, the linear regression, which tries to find a line that can explain all these points. An autoregression is a regression that tries to explain the values using their previous values.
MA: Moving Average. I'm actually quite lost here. I know what a moving average is, but the moving average model doesn't seem to have anything to do with the "normal" moving average. The formula for the model seems awkwardly similar to AR and I can't seem to understand any of the concepts I find in the internet. What is the purpose of MA? What's the difference between MA and AR?
So now we have ARMA. The I then comes from Integrated, which as far as I have understood, simply serves the purpose of allowing the ARMA model to have a tendency, either increasing or decreasing. (Is this equivalent to saying ARIMA allows it to be non-stationary?)
Now comes the S from seasonal, which adds periodicity to ARIMA, which basically says, for example in the case of load forecasting, that the load looks very similar everyday at 6 PM.
Finally the X, from exogenous variables, which basically allows external variables to be considered in the model, such as weather forecasts.
So we finally have SARIMAX! Are my explanations OK? Recognize that these explanations aren't required to be rigorously correct. Can someone explain me what MA does intuitively?
Comment: Your intuition that _the Moving Average Model doesn't seem to have anything to do with the "normal" Moving Average_ is sound. See for example: [Why are MA(q) time series models called "moving averages"?](http://stats.stackexchange.com/questions/58242/why-are-maq-time-series-models-called-moving-averages)
Answer: As you noted, (1) an AR model relates the value of an observation $x$ at time $t$ to the previous values, with some error:
$$
 x_t = \phi x_{t-1} + \varepsilon_t
$$
Let's substitute in $ x_{t-1} $, and then $ x_{t-2} $:
$$\begin{aligned}
x_t &= \phi (\phi x_{t-2} + \varepsilon_{t-1}) + \varepsilon_t  \\
&= \phi^2x_{t-2} + \phi\varepsilon_{t-1} + \varepsilon_t  \\
&= \phi^3x_{t-3} + \phi^2\varepsilon_{t-2} + \phi\varepsilon_{t-1} + \varepsilon_t
\end{aligned}
$$
Taking that out to infinity:
$$
 x_t = \phi^nx_{t-n} + \phi^{n-1}\varepsilon_{t-n+1} + ... + \phi\varepsilon_{t-1}+ \varepsilon_t
$$
You can write any (stationary) AR($p$) as an MA($\infty$), though of course you run into a giant pile-up of terms on top of one another with $p>1$.
Having seen that, let's rephrase our definition (1) now. An AR process relates the value of an observation $x$ at time $t$ to an infinite sequence of decaying error shocks $\varepsilon$ from prior time periods (that we don't directly observe).
So what an MA process is might be clearer now. (2) An MA($q$) process relates the value of an observation $x$ at time $t$ to just $q$ error shocks from prior periods (that we don't directly observe), of which coefficients are allowed to vary more than the exponential decay implicit in an AR model. As you note, it has nothing to do with the usual "moving average" concept.
With some conditions on the coefficients $\theta_1...\theta_q$ of an MA($q$) process, we can actually do something very similar to what I showed for an AR process above, that is, write the MA($q$) as an AR($\infty$). So it's just as valid to restate (2) to say an MA process relates the value of an observation $x$ at time $t$ to a decaying sequence of all prior values of $x$.
So an ARMA model just combines those two ideas, relating $x_t$ to both an infinite decaying sequence and a defined sequence. ARIMA just adds in differencing to the mix, that is, you run ARMA on $x_t - x_{t-1}$ (or further differences as it may be), to remove trend, as you noted.
Comment: Hi Affine, thanks for the fast reply! Can I say MA is like an AR for the error?
Comment: Sort of. The key idea is that AR can be transformed into a decaying MA of infinite length, and vice versa. So any intuitive meaning you assign to one - AR = relate current observation to $p$ previous observations - can be assigned to the other - MA = relate current observation to all previous observations. Or as I approached it originally in my answer - AR = relate current observation to all previous error "shocks", MA = relate current observation to $q$ previous error "shocks".
Comment: Isn't the footnote for epsilon should be $t-n-1$?

How to understand SARIMAX intuitively?


How can you programmatically make the "mouseover" item into the selected item in a tree/list?

Question: I would like to programmatically change a selected item, in a tree or list, to the item currently "marked/focused" under the mouse pointer .
I'm working with an Flex Air standalone application.
I was thinking in the lines of:
myTree.selectedItem = EVENT.TARGET (where EVENT could be a mouseover/rightclick/rollOver event, and TARGET should be the node/item currently under the mouse pointer).
Is there a way of doing this (or in any other way)?
Ahh, and i want to do it without left clicking ;-)
Thank you in advance,
Sebastian
Comment: Welcome at SO! Some more effort would be appreciated from your side. I think you are going in the right direction.
Answer: I found this interesting enough so I am asking if this is the easiest way to achieve this. First off, instead of the list, you need to add the rollOver-listener to the ItemRenderer, not to the list itself (as the event.target and event.currentTarget will just show your list).
So lets create a custom ItemRenderer and add a rollOver listener
<xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
            xmlns:s="library://ns.adobe.com/flex/spark"
            xmlns:mx="library://ns.adobe.com/flex/mx"
            autoDrawBackground="true" height="20" rollOver="itemrenderer1_rollOverHandler(event)">
<fx:Script>
    <![CDATA[

        protected function itemrenderer1_rollOverHandler(event:MouseEvent):void
        {
            this.dispatchEvent(new CustomEvent(CustomEvent.SELECT_ITEM, data, true));

        }

    ]]>

    <s:Label id="label1" text="{data.label}"/>

</s:ItemRenderer>

You need to somehow get the value of the selected item (which is the data on the itemRenderer) so I created a CustomEvent-class just to do so.
package
{
    import flash.events.Event;

    public class CustomEvent extends Event
    {

        public var selectedItem:Object;

        public static const SELECT_ITEM:String = "selectItem";

         public function CustomEvent(type:String, selectedItem:Object, bubbles:Boolean=false, cancelable:Boolean=false)
         {
            super(type, bubbles, cancelable);
            this.selectedItem = selectedItem;
         }
    }
}

then I added a eventListener to the main class and set the list.selectedItem property accordingly:
//for the main MXML initializer:
    this.addEventListener(CustomEvent.SELECT_ITEM, rollOverChangeSelected);

            //and the function:
    protected function rollOverChangeSelected(ce:CustomEvent):void{

            list.selectedItem = ce.selectedItem;

    }

Another way: bindable variable
The list:
s:List id="list" allowMultipleSelection="true"  selectionColor="red" rollOverColor="red" itemRenderer="customItemRenderer" selectedItem="{_rollOverSelectedItem}">

The variable and set / get methods:
        [Bindable] public var _rollOverSelectedItem:Object;

        public function get rollOverSelectedItem():Object
        {
            return _rollOverSelectedItem;
        }

        public function set rollOverSelectedItem(value:Object):void
        {
            _rollOverSelectedItem = value;
        }

and the ItemRenderer's rollOver-method:
protected function itemrenderer1_rollOverHandler(event:MouseEvent):void
        {

            this.parentApplication.rollOverSelectedItem = data;

        }

What is the best/proper way?


Suppose $\forall x\in \mathbb{R}, f'(x)=m$. Prove $f(x)=mx+b$ for some $b$ without the fundamental theorem of calculus.

Question: I'm trying to prove this assertion for arbitrary $f\colon U\subseteq E\to F$ where $U$ is an open in $E$ and $E,F$ are Banach spaces. In order to get some intuition, I tried proving it for the case $U,E,F=\mathbb{R}$ but can't think of a way that doesn't involve the fundamental theorem of calculus. I'm looking for hints for the following:
Let $f\colon\mathbb{R}\to \mathbb{R}$ be a differentiable function and assume that there is a $m\in \mathbb{R}$ such that for every $x\in\mathbb{R}$, $f'(x)=m$. Show that there is a $b\in\mathbb{R}$ such that $f(x)=mx+b$.
The restriction being: no FTC.
Comment: Well, do you know how to use the Mean Value Theorem to show that $F'(x)=0$ for all $x \in \mathbb R$ implies $F(x)$ is constant?  If so, apply that to $F(x)=f(x)-mx$.
Comment: @lulu Nice, this can easily be generalized to arbitrary Banach spaces through the Finite Increase Theorem. Thanks.
Answer: The task can be reduced to real valued functions of one real  variable.
Let $f:U\to F$ be differentiable at every point of $U$ and $f'(x)\equiv M,$ where $M\in B(X,Y).$ With no loss of generality we may assume that $U$ is a ball centered at $0.$ Fix $0\neq a\in U$ and $\varphi\in F_{\mathbb{R}}^*.$ By assumptions we have
$${\|f(v+u)-f(v)-Mu\|\over \|u\|}\underset{u\to 0}{\longrightarrow} 0,\quad v\in U$$ Thus for   $t,h\in \mathbb{R}$ and $0\le t<1+\delta$ we get ($v=ta,$ $u=ha$)
$${|\varphi(f(ta+ha))-\varphi (f(ta))-h\varphi (Ma)|\over |h|}\underset{h\to 0}{\longrightarrow} 0$$
This implies that the function $g(t)=\varphi(f(ta))$ is differentiable for $0<t<1+\delta$ and $g'(t)\equiv \varphi(Ma).$  Hence $$\varphi(f(ta))=g(t)=\varphi(Ma)t+g(0)\\=\varphi(Ma)t+\varphi(f(0))=\varphi(tMa+f(0))$$
Therefore
$f(ta)=tMa+f(0).$ For $t=1$  we get
$f(a)=Ma+f(0).$


Not able to use calculated value in CONCAT statement

Question: Case when sim.PickPackUom='IP' then  sim.InnerPackQuantity
else
   im.CaseQuantity
end
  as divqty
,concat (cast (i.QuantityOnHand as float)/divqty  ,' ',  sim.PickPackUom  )qty

concat is giving error. How can I make divqty value available for concat or division?
Comment: make it part of a sub-select
Comment: which error is giving you?
Comment: Tag your question with the database you are using.
Answer: You have to use the entire case condition instead of divqty:
Case when sim.PickPackUom='IP' then  sim.InnerPackQuantity
    else im.CaseQuantity
    end as divqty
,concat (
       cast (i.QuantityOnHand as float)/
             (Case when sim.PickPackUom='IP' then  sim.InnerPackQuantity
                   else im.CaseQuantity end),
       ' ',  sim.PickPackUom) qty


Como recuperar varias ações de uma activity para outra?

Question: Como enviar url de uma activity para outra com diferentes ações de cliques (vários botões)? Tentei usar intent.putextra mas não consigo recurar as urls dos outros botões, no caso estou usando duas activity a segunda esta com webview executei com loadurl, mas, como eu disse só consigo fazer que funcione um botão, e não sei como receber os outros na mesma activity.
enviando assim:
Home.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
  Intent intent = new Intent(inicio.this,INSMainActivity.class);
  intent.putExtra("hiphop", "https://m.youtube.com/channel/UCUnSTiCHiHgZA9NQUG6lZkQ");
                startActivity(intent);
            }
        });

recebendo:
String url = getIntent().getExtras().getString("hiphop");
    youtubeView = (WebView) findViewById(R.id.youtube_view);
    youtubeView.loadUrl(url);

Como visto no código estou tentando carregar gêneros a partir da primeira activity.
Answer: Estou utilizando o Intent em meu projeto e está funcionando normal, na hora de receber estou recebendo assim:
Crie a variavel String url junto com a classe e depois no onCreate
Bundle extras = getIntent().getExtras();
        if(extras != null)
        {
            url= extras.getString("hiphop");
        }

Dai depois você pode continuar o código
youtubeView = (WebView) findViewById(R.id.youtube_view);
    youtubeView.loadUrl(url);

Comment: vou testar assim
Comment: @MarcosFreitas Qualquer coisa só falar o que apareceu que tento verificar


CardView layout_width="match_parent" does not match parent RecyclerView width

Question: I have a fragment with contains a RecyclerView with layout_width="match_parent":
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity$PlaceholderFragment" />

The item in the RecyclerView is a CardView also with layout_width="match_parent":
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:layout_gravity="center"
        android:id="@+id/info_text"
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="match_parent"
        android:textAppearance="?android:textAppearanceLarge"/>
</android.support.v7.widget.CardView>

I inflate the item view as below:
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        CardView v = (CardView) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_listitem, null, true);

        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

But when I run the app, the CardView is rendered as wrap_content as shown below:

Note that this was run on emulator, not a real device.
Am I doing something wrong, or is it a bug?
Comment: When inflating the CardView, are you supplying the parent view with a true parameter?
Comment: Hi @NiekHaarman, please see the edit. I added the inflating code. And yes I have passed the true parameter.
Answer: The docs for inflate:

Inflate a new view hierarchy from the specified xml resource. Throws
  InflateException if there is an error.
Parameters
resource  ID for an XML layout resource to load (e.g.,
  R.layout.main_page) root
view to be the parent of the
  generated hierarchy (if attachToRoot is true), or else simply an
  object that provides a set of LayoutParams values for root of the
  returned hierarchy (if attachToRoot is false.)
attachToRoot  Whether
  the inflated hierarchy should be attached to the root parameter? If
  false, root is only used to create the correct subclass of
  LayoutParams for the root view in the XML. Returns The root View of
  the inflated hierarchy. If root was supplied and attachToRoot is true,
  this is root; otherwise it is the root of the inflated XML file.

It is important here to not supply true, but do supply the parent:
LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_listitem, parent, false);

Supplying the parent View lets the inflater know what layoutparams to use. Supplying the false parameter tells it to not attach it to the parent just yet. That is what the RecyclerView will do for you.
Comment: The solution didn't work for me because the ListView's `layout_width` was `wrap_content`. Its weird because this shouldn't affect the list view! So my understanding is that when you provide false as a parameter to the layoutinflater, the ListView adds the list items to the ListView with layout parameters matching the ListView itself! :0
Comment: I think the correct understanding is that when you set attachToRoot to false, you need to supply an object with defined LayoutParams value. That object is not necessarily the parent. "...simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)..." But I don't understand why inflater cannot read the LayoutParams that defined in the CardView but need another object parameter to inform it?
Comment: could you post a little more code, because I think I'm doing the same, but actually it isn't working
Comment: I am inflating how you suggestion and match_parent is not working for me.
Comment: If I use custom view, how to deal with it? I mean `ViewHolder onCreateViewHolder(...) { View v = new MyItemView(parent.getContext); return new ViewHolder(v); }`
Comment: Could you explain why supplying true would cause it to be `wrap_content` in the first place?
Comment: @nhaarman can you please help me to solve this issue https://stackoverflow.com/questions/50066346/cardview-gridlayout-with-recyclerview-is-not-fit-for-all-screen-sizes-in-andro
Comment: @Nikson No I cannot.
Answer: Use RelativeLayout as the immediate parent to CardView.
<RelativeLayout
    android:layout_width="match_parent" ... >
    <CardView
        android:layout_width="match_parent" ... >
    </CardView>
</RelativeLayout>

Comment: it's been ages, android x is in production, still the bug is not fixed !
Comment: the easiest way.
Comment: It works for me, but I don't know why do this can solve the problem.
Does anyone can explain why?
Comment: Yes this seemed to work for me as well.  I was using LinearLayout and the suggestion above didn't work since I was already doing exactly that (ie not attaching to root, but providing a parent).  You have to do both RelativeLayout + not attaching parent, but providing one.
Comment: I had a similar problem and this worked for me to correct the width of my card view but I am having a similar problem with the height? Can you suggest me something for that as well?
Comment: Work like charm
Answer: This worked for me,
 View viewHolder= LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item, null, false);
 viewHolder.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
 return new ViewOffersHolder(viewHolder);

Answer: The way I did it is:
View view = mInflater.inflate(R.layout.row_cardview, null, true);
            WindowManager windowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
            int width = windowManager.getDefaultDisplay().getWidth();
            view.setLayoutParams(new RecyclerView.LayoutParams(width, RecyclerView.LayoutParams.MATCH_PARENT));

Explanation:
In your onCreateViewHolde once you get card view, get the screen width and then set the layout param accordingly for card view.
Comment: please improve this slightly. It basically says "Try this"
Comment: Added Explanation. Please check and if need any further help, comment here.
Answer: This appears to be fixed in 'com.android.support:recyclerview-v7:23.2.1'
See: RecyclerView wrap_content for further discussions.
Answer: Default implementation force the use of wrap_content in the default layout manager :
  @Override
public LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
}

All you have to do is to override this method in your LayoutManager like this :
  @Override
public LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
}

Answer: Simply set new layout params
view.setLayoutParams(new RecyclerView.LayoutParams(
    RecyclerView.LayoutParams.MATCH_PARENT,
    RecyclerView.LayoutParams.WRAP_CONTENT
));

Comment: I found doing this in onBindViewHolder() useful when using a custom view class that inherits from ConstraintLayout.
Comment: It is not a good answer because the margin that is been set to the layout will be affected.
Answer: This works for me
View view = inflator.inflate(R.layout.layout_item, ***null***, false);

Answer: Use  card_view:contentPadding with a negative value
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    card_view:contentPadding="-4dp"
    card_view:cardElevation="0dp"
    android:layout_height="wrap_content">

It worked for me
Answer: Wrap CardView in a Layout that has width:match_parent


How do I use python fastCGI on dreamhost?

Question: I've been using CGI since 1996 or so, so it's probably time to move to FastCGI or something else. (Flask?)
I'm using Dreamhost. I did some googling and found this article, but the article claims to be out of date and, sure enough, it doesn't work.
One of the things I really like about CGI is being able to change the script and instantly see the results. I know that flask leaves a single Python script running and re-uses it, but as a result you need to modify some file to tell flask to re-read your Python file. That seems odd---why can't flask see that the file has been modified? But I guess it makes sense for large programs that have literally hundreds of python includes.
Is FastCGI just not a thing anymore?
Answer: FastCGI came and mostly went, too. PHP still uses a variant of it, known as FPM, but everyone else has moved on to language specific application servers that speak HTTP and are generally proxied from a web server that handles things like authentication and static files.
As for hot reloading, this is useful in development, but it really doesn't matter in production, since you aren't going to do it there.
As for Dreamhost, it looks like their currently supported method for deploying Python apps is with Passenger. I personally think that's an odd choice, but I'm sure they have their reasons.
Comment: Thank you for such a clear answer. When I looked at Dreamhost and Passenger I discovered that they want it enabled for an entire domain. So I gather that I create an `apps` domain which is used for the scripts. Thanks again.
Comment: I also have a bad history of developing on production servers. But I guess that's because I never *really* move things into production.


Como Relacionar uma Tabela com Outra Tabela onde o campo para relacionar é um XML

Question: Estou com um banco SQL Server de um sistema que foi descontinuado. Neste banco, existe uma tabela MOVIMENTACAO e uma tabela EQUIPAMENTO, onde configuraria um relacionamento N:N.
O problema é que ao invés de ter uma terceira tabela, há um campo na tabela MOVIMENTACAO com os IDs dos EQUIPAMENTOS em formato XML.
EX:

<ArrayOfInt xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <int>39254</int>
  <int>39255</int>
  <int>79349</int>
  <int>79351</int>
  <int>79354</int>
  <int>79456</int>
  <int>79539</int>
  <int>79547</int>
</ArrayOfInt>

Dúvida: Há alguma forma de montar uma QUERY onde eu possa fazer esse relacionamento?
Comment: Se entendi correto, que POG fizeram aí hein. Acredito que o melhor seja jogar isso em uma linguagem de programação, criar uma regra para tratar esses IDs jogado nesse xml e fazer uma relação N:N realmente válida.
Answer: A melhor forma seria normalizar estes dados em uma tabala gerada da relação N:N e alterar o código da aplicação para lidar com esta nova estrutura.
Se isso não for possível, podemos fazer o seguinte:
Tabela MOVIMENTACOES

Tabela EQUIPAMENTOS

Agora precisamos criar um script que normalize o XML em linhas (equipamentos) junto com suas respectivas movimentações.
/*Tabela virtual para armazenar a relação N:N*/
DECLARE @TAB_NORMALIZADA TABLE(
  cod_movimentacao int,
  cod_equipamento int
)

/*Normalização dos dados*/
INSERT INTO @TAB_NORMALIZADA
SELECT
  cod_movimentacao,
  T2.lin.value('(.)[1]', 'varchar(100)')
FROM   MOVIMENTACOES
CROSS APPLY xml_equipamentos.nodes('/ArrayOfInt/int') as T2(lin)

/*Select com nome do equipamento e código de movimentação*/
SELECT
  T.* ,
  E.equipamento
FROM @TAB_NORMALIZADA T INNER JOIN EQUIPAMENTOS E
ON T.cod_equipamento = E.cod_equipamento

Se você puder alterar a estrutura do banco, crie uma tabela nova para substituir a minha tabela virtual e uma trigger na tabela de movimentação para popular esta nova tabela.


What is the degree of the zero polynomial and why is it so?

Question: My teacher says-

The degree of the zero polynomial is undefined.

My book says-

The degree of the zero polynomial is defined to be zero.

Wikipedia says-

The degree of the zero polynomial is $-\infty$.

I am totally confused and want to know which one is true or are all true?
Comment: Wanna be more confused? I think I have also seen it be defined as $-1$. Haha.
Comment: Yet, I'd argue that the book is wrong, since defining $\deg(0)=0$ thwarts one of the _main_ uses of degree (for univariate polynomials over a field), namely to get the property that Euclidean division of any$~a$ by any nonzero element$~b$ is possible leaving a remainder with _strictly_ lower degree than $\deg(b)$.
Comment: It's a matter of convention, and there are a few reasons to argue that the best convention is $-\infty$.
Comment: I agree, the book is wrong. __What book is that?!__ The definition used by your teacher and the definition used by Wikipedia are both useful and common. So you have to be careful what definition the author you read uses.
Comment: It happens all the time that a Wikipedia page only reflects the page author's thought. Just don't consider it to be the ultimate truth. On the other hand, I very much prefer to consider the degree of the zero polynomial either equal to $-\infty$ or to leave it undefined. When it comes to definitions, none is *right* or *wrong*: definitions don't admit "proofs".
Comment: @JeppeStigNielsen  -Would you like to contact the authors?I can give you their email.They say in the preface any criticism or comments on the book contents are welcome...
Comment: I agree, whatever the degree of the zero polynomial is, it should be strictly less than zero.
Answer: Well, it depends.
Mathematical practice shows that sometimes it is useful to define the degree of the zero polynomial to be zero, sometimes to define it to be $-\infty$ and sometimes to leave is undefined. Which option one chooses depends on what one is trying to do.
This is quite different with what happens with the degree of all other polynomials, which is always defined in the same way (*) But don't think that if for the slightiest of reasons we were to fnd it useful to change the definition to do something we wanted, we would.
(*) Actually, that is not exactly true: we sometimes put degrees on polynomials which are different from the usual ones, but usually only on polynomials with more than one variable.
Comment: Well, for example: the degree of the product of two nonzero polynomials is the sum of the degrees of the factors. If you want to extend this to include the possibility that the factors be zero, one needs to do something, and a natural option is to define the degree of $0$ to be $-\infty$.
Comment: For some purposes it i useful to know that the degree of a polynomial $f$ to be the least number $i$ such that the $i$th derivative $f^{(i+1)}$ is equal to zero, and if this is going to work for the zero polynomial too, then you need to define its degree to be $-1$. &c.
Comment: So it has yet to be found where $\deg 0=0$ is any good.
Comment: Can you give an example of where each kind is used?
Comment: There are also contexts for which it makes sense to define the degree of the zero polynomial to be $+\infty$. For example, for nonzero polynomials $P$ and $Q$, it's true that if $P$ divides $Q$ then $\deg P \le \deg Q$; setting $\deg 0=+\infty$ is the only way to extend this fact to the zero polynomial. (Another reason: $\deg P$ equals the number of roots of a polynomial over $\Bbb C$.)
Comment: @GregMartin: But in _every_ Euclidean domain the Euclidean function (the statistic used to express that a remainder must be strictly smaller than the divisor) suffers from a similar problem: on one hand its value for the zero element must be strictly smaller than for every nonzero element$~b$ (because one can always have a division by$~b$ be exact), but on the other hand the zero element is always multiple of$~b$ so divisibility goes in the opposite sense for (only) this case. By the way this shows that $\deg(0)$ should be definitely strictly less than $0$ to be of any use.
Comment: Yep, I agree that it's problematic, which is why it's typically undefined.
Comment: Leaving it undefined does not resolve any problem, for you need to be careful never to use the degree of the zero polynomial.
Answer: I think $-\infty $ make sense. Indeed, let $P$ a polynomial of degree $\geq 1$. Then, you have that $$\deg(PQ)=\deg(P)+\deg(Q),$$
for every polynomial $Q$. Now, if you define $\deg(0)=0$, you'll get $$\deg(0\cdot P)=0+\deg(P)>0,$$
which is not compatible with the degree formula. The only way to give a sense to this formula is to define $\deg(0)=-\infty $.
Same if you defined $\deg(0)=-1$, the formula won't be compatible if $\deg(P)\geq 2$.
Comment: @Vim This isn't really enough to justify $-\infty$: why not $+\infty$ which also acts as a black hole?  (Yes, I understand why, but this isn't explained in the answer).  In fact, naively $\infty$ is a very natural suggestion since it generalizes the theorem "a polynomial of degree $d$ has at most $d$ roots".
Comment: Indeed, only $-\infty$ can act as a black hole. But anyway this's only one aspect of mathematical practices.
Comment: It makes sense if what you want is your first displayed formula to hold. If you are not interested in that, then it does not make a lot of sense for you migh be interested in some other property to hold which forces you to define $\deg 0$ differently. This is a matter of convention, and conventions are chosen with some purpose in mind.
Comment: @ErickWong I'd say its because there are some theorems that say "if $\deg P>\deg Q$, then blah blah" but unfortunately I've forgotten most of the algebra I learned so I can't name any :(
Comment: @Vim You're probably thinking of "if $\deg P > \deg Q$ then $\deg(P+Q) = \deg P$".  If $\deg 0 = +\infty$ then we could take $P=0$, and then we'd have $\deg Q = +\infty$ for any $Q$.
Answer: Defining it as $-\infty$ makes the most sense.
As mentioned in Surb's answer and comments, some properties of degrees are kept intact this way, e.g.

$\deg(PQ)=\deg P+\deg Q$
If $\deg P>\deg Q$ then $\deg(P+Q)=\deg P$

It also starts making more sense if you consider expressions that can take on negative powers as well. That is, instead of $\sum_{k=0}^na_kx^k$, consider $\sum_{k=-\infty}^{n}a_kx^k$. So you could have $3x^2+2x$ and $x+1+3x^{-2}$ and $2x^{-3}-\frac45x^{-5}$. Then degree is just "the supremum of all $k$s for which $a_k\neq 0$. The degrees of these 3 expressions are 2, 1 and -3 respectively. Then it's easy to see that 0, which has no nonzero coefficients, has a degree of $-\infty$.
The same works if you consider expressions than can also have fractional degrees. Then the degree of, say, $3\sqrt{x}-x^{-3}$ is $1/2$.
Of course, this inspires the definition of a "dual" degree, which is the infimum instead of the supremum. Then the degree of $3x^4+2x^3+5x^2$ will be 2, and the degree of $0$ will be $\infty$.
Keeping the degree of $0$ undefined is understandable (not everyone wants to deal with infinities). Defining it as $-1$ has merits (if you don't consider negative powers, $0$ is one step down from nonzero constants). But there is absolutely no sense in defining the degree as $0$. The $0$ polynomial has as much similarity with constants, as constants have with linear polynomials.


Six digit number combinatorics problem

Question: How many numbers with six digits(Basically from 100 000 to 999 999) have exactly two equal digits and the rest are all different?
What I tried:
first digit can't be a zero, so the number would have 5 digits.
I have at least 2 cases, the repeated digit is in the first slot or on another
first slot has the repeated digit:
I have 9 numbers to place on the first slot(an on the other repeated digit), and then I have 5C1 places to put the second repeated number, then I have 9*8*7*6 ways to place the other numbers.
So first case:9 * 5 * 9A4 = 136080
not first slot has the repeated digit:
5C2 places to put the repeated digits(all except the first) and I have 10 digits to use, then I have two cases.
I can have the number 0(zero) or not(this will cause trouble because I can't place the number 0 on the first slot, so I divided in two more cases)
There is not a zero:
Easy, 8A4(8*7*6*5)
There is a zero:
Hmmm, the first digit can't be a zero, so I have 8(I have 8 because I can't use the number 0 nor the repeated number) options left, then for the other 3 places I want to have a zero, otherwise I was just repeating the last case,I want 3 numbers, have a zero, so I want to pick two numbers, 7C2(7 possibilities, because out of 10 I used 0, the repeated and the first slot number), okay I have 3 numbers without order, so I do 3! or 3A3 to arrange them.
So the second case: 5C2 * 10 [8A4 + 8*7C2*3!] = 268800
So my solutions: 136080 + 268800 = 404880
However there is another solution that seems to be correct but gives a different result : 5C2 * 9A4 + 9[5C1*9A4 + 5C2*8*8*7*6] = 408240
Explaining briefly:
5C2 * 9A4, this case, the repeated number is 0, and is not on the first slot.
9*5C1*9A4, this case ocuppy the first slot(repeated number), I have 9 numbers/possibilities for the first slot and the repeated number, then 9 numbers left for all the other places 9A4
9*5C2*8*8*7*6, 9 numbers for the two choosen spots(not the first slot, there are 9 numbers and not 10, because that case is already done, it's the first case), then for the first slot I can't have number zero so 8, then for the other 3 slots I have 8*7*6, so that's the thought process.....
Which is the correct one, or are both wrong?
Comment: Does $001234$ count as a six-digit number?
Comment: I might be wrong but to my mind its $10P5=30240$
Comment: Please edit your question to show what you have attempted and explain where you are stuck so that you receive responses that address the specific difficulties you are encountering.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: Thanks, there's what I have attempted
Answer: The second solution is correct.

Let's look at the first solution.

first slot has the repeated digit:
I have 9 numbers to place on the first slot(an on the other repeated
  digit), and then I have 5C1 places to put the second repeated number,
  then I have 9*8*7*6 ways to place the other numbers. So first case:9 *
  5 * 9A4 = 136080

Looks ok.

not first slot has the repeated digit:
5C2 places to put the repeated digits(all except the first) and I have
  10 digits to use, then I have two cases. I can have the number 0(zero)
  or not(this will cause trouble because I can't place the number 0 on
  the first slot, so I divided in two more cases)
There is not a zero: Easy, 8A4(8*7*6*5)

Why? This case only seems to select 4 of the 5 distinct digits. I think it should be 9A5 in your notation.

There is a zero: Hmmm, the first digit can't be a zero, so I have 8(I
  have 8 because I can't use the number 0 nor the repeated number)
  options left, then for the other 3 places I want to have a zero,
  otherwise I was just repeating the last case,I want 3 numbers, have a
  zero, so I want to pick two numbers, 7C2(7 possibilities, because out
  of 10 I used 0, the repeated and the first slot number), okay I have 3
  numbers without order, so I do 3! or 3A3 to arrange them.

So far this is conditioned on the first digit not being repeated and one of the digits being a zero. You haven't chosen the repeated number, so the first digit has 9 possibilities. Then there are 4 distinct digits to select, one of which is 0, giving 9*8C3*4!.

So the second case: 5C2 * 10 [8A4 + 8*7C2*3!] = 268800

This should be 5C2 * (9A5 + 9*8C3*4!) = 272160.
Then the overall result is 136080 + 272160 = 408240, in agreement with the second approach.

As a bonus, here's a simpler solution.
Ignore for the time being the restriction that the first digit cannot be zero. We pick the two positions which have the repeat in 6C2 ways, and then we pick the five distinct values as 10A5. Now, by symmetry, exactly 1/10 of the patterns we've generated start with a zero, so the final solution is 6C2 * 10A5 * 9/10 = 408240.
Comment: Wow thanks for the amazing answer I'm in a hurry so i'll question better later, but in your simpler solution, I understand that out of 10 digits one is 0, but so chance of not being a 0 is 9/10.... but this doesn't seem correct at all, because that's not the only restriction, once you have a total of 5 places(with different numbers), shouldn't it be like1-1/(5*10) instead of 9/10?
Comment: Nevermind I got it
Comment: Thanks for the answer, I understand now clearly what I did wrong.

A quick question, I'm learning combinatorics in high school and these kind of exercises are the "ending point" of this subject , however It's the one I have the most curiosity to learn so I'd like to read a book about it, in your solution the "9/10" trick is completely new to me, does it come from your intuiton/classes, or did you read really good book?
So do you advice any? I'm willing to read **Principles And Techniques In Combinatorics**,Chen Chuan-Chong

I understand a bit about graph theory*
Comment: That was a flash of inspiration. I don't think I've ever formally studied combinatorics: I've taught myself bits which I found useful for tackling programming challenges like Project Euler. The only book on the subject I have is *Partitions* by Andrews and Eriksson. I don't know how far you'd be able to get through it without having to read up other stuff on Wikipedia, but as a high school student you probably have loads of free time ;-) and it's a cheap paperback.
Comment: Sorry, correction: the title is *Integer Partitions*.

Six digit number combinatorics problem


Segmented Regression of a Seasonal Time-series in R

Question: I have a time-series of diurnal temperature range (DTR), 1961 - 2013 from a single weather station. Visually, the first part of the TS seems to have a downward trend, so I used the package segmented to verify, and specifying 4 break points the downward trend is confirmed.
A downward trend would be significant for my research, but I want to avoid confirmation bias. Could the trend be an artefact of the strong seasonality of the TS?
Using changepoints to search for step changes of mean value confirms the segmented regression findings, but after attempting to deseasonalize the series by differencing it with lag = 371 days (the maximum ACF value), the trend is completely different.

What I want to ask is:
Is it correct to apply segmented regression (and/or changepoints detection) to the raw time-series, or does it need to be pre-processed somehow first?
Comment: changepoint detection needs to be done in concert with pulse detection , time trend detection , seasonal pulse detection , local time trends AND of course SARIMA detection.
Comment: I am positively not trying to predict the future of this time-series, and I am only concerned with the seasonal structure only insofar it impacts what I am actually after: the local time-trends, and in second place the global time-trend.

I'd like to minimize the workload and focus on my targets.
Comment: Whether or not you are trying to predict or to characterize , the same advice holds. One needs to segment signal and noise of the time series in order to clearly see the intrinsic patterns.
Comment: Does `changepoints` account for serial correlation and seasonality?  If not, you cannot trust its results--the approach may be right but the software could be wrong.  I cannot find documentation of any `changepoints` function in the `segmented` package.
Comment: it does not ...
Comment: @whuber, `changepoints` is a different package.
Answer: your graph doesn't suggest a downwards trend , it suggests (slightly ) 1 or more level shifts. A level shift is not a trend but a change in intercept... The program you are using only tests for level shifts. It appears to me that your sample size is soooo large it might be falsely suggesting level shifts.
The only way to resolve this is to 1) adjust pulse anomalies ; 2) identify any persistant sarima structure ; AND then 3) test for time trends and/or step/level shifts as laid out by Intervention Analysis Coding in R TSA Package and Time series trend


I'm suddenly getting the error :EntityMetadataWrapperException

Question: I'm running a Drupal 7.21 site that uses the Entity Reference module (v.7.x-1.0) to support reusing image nodes in other node types. After several months of smooth sailing , I'm seeing a new error when I try to view image nodes on my site. The error is:

EntityMetadataWrapperException: Unknown data property
  field_entity_image. in EntityStructureWrapper->getPropertyInfo()

The property named in the error, "field_entity_image", is the name of an Entity Reference field that exists on other node types (article, basic page). However, those other content types don't throw the error when I try to view them. What is new is the fact that I created a new node type (bio) that also uses the existing field_entity_image field.
I've seen this error discussed in relation to certain modules (Commerce being one) but not as the result of creating new content type or adding entity reference fields. If anyone has insights into this, all help will be much appreciated.
Comment: Just to update this post, we've now upgraded to Drupal 7.22, and the issue is still with us. I've also noticed that the error isn't confined to nodes whose fields include an image field or entity reference field. It appears to affect all content nodes other than Basic Page and Article, i.e. all the custom types we've created. Does anyone have any updated info about this error and what might be causing it? Again, many thanks.
Comment: (I work with Laurance).  In fact, the issue appears to affect all content types that do not use the "field_entity_image" field.  Adding this field to the content type makes the error message go away.  Deleting it again makes the error come back.  This doesn't seem right, but it does seem to be the case.
Comment: I've also confirmed that the issue occurs with minimal contributed modules-- I was able to pare down to basically just field modules and their dependencies (Date, Date API, Computed Field, Entity Reference, Entitity API, and CTools) and the problem still exists.
Comment: Update your "Entity" and "Entity Refference" modules, it must resolve this issue
Comment: Hello. Are you suer about that? Could you point us to issue in queue that is resolved (fixed) and dealt with this problem?
Answer: Your site has not been running on Drupal 7.21 for several months. You have recently upgraded.
There was a security fix in the drupal core image module in 7.20 which broke several contributed modules. 7.21 has a new variable to mitigate the problem, but if your issue involves images, it is probably related to the security fix. For more information read the release notes.
Comment: This doesn't appear to be the same issue we're experiencing, unfortunately.  See comments above for more detail.
Answer: I have had similar weirdness with the Entity API data wrappers.  The root cause of the problem in my case, and in the Commerce module, was the stable version of UUID.  Upgrading the the dev version solved all of my issues.  Searching for UUID in both of the issue queues will give you more insight.
Comment: Unfortunately this doesn't appear to be module related-- we've confirmed that the issue persists with minimal contributed modules (see comments on original question).


PHP problem sets for beginners

Question: There are plenty of tutorials and step by step guides out there on the internet, but they give mostly examples which you can run in the computer.
Is there a good separate set of problems that beginners can try to solve themselves. If existing solutions are available, even better.
Update
To put it more clearly, is there any resource online with a collection of Practice Questions which beginners can refer to? A set of problems in using operators, using arrays, etc?
Comment: Could you please refine what you are looking for? Do you mean something like http://projecteuler.net? What is meant by *separate set of problems* and what is the issue with *guides […] that have to be run in a computer*. I mean, isnt that what programming languages are for?
Answer: Take a look at these sets http://codingkata.org/ . They're language independent and cover some important beginner fields: arrays, string operations, recursion, regular expressions, etc.
I wouldn't recommend Project Euler as it has more to do with math and advanced programming and it won't help you develop too many useful skills.
Answer: I hope this doesn't come across as spam but I'm actually working on a project right now that is going to allow people to upload their own projects so that people like yourself can browse through real life example of peoples work. - booyahachieved.com
I do need people to contribute code first though! and please remember it's still in development!

PHP problem sets for beginners


Como executar uma função javascript no fechamento do browser?

Question: Estou desenvolvendo uma aplicação web e preciso executar uma função quando o cliente clicar no X do browser ou simplesmente fecha-lo.
Para ser mais especifico preciso executar uma chamada ajax nesse fechamento.
Existe alguma forma de se fazer isso?
Comment: Você quer saber como chamar esta função quando o a página for fechada (qual evento deve usar)? Ou quer saber como fazer a função que faça a chamada AJAX?
Answer: Não é possível distinguir entre o usuário clicar no CLOSE do navegador, quando ele fecha a aba ou quando ele sai do seu site através de um link, mas, felizmente, é possível detectar quando um destes eventos acontecem, e é através dos eventos onunload e onbeforeunload.

onunload: executado em concorrência com o fechamento do browser. Pode ser ruim em navegadores como o IE, pois algumas vezes ele simplesmente ignora o javascript que você quiser executar ao mesmo tempo.
onbeforeunload (recomendado): executado antes do browser iniciar seu fechamento. É mais recomendado pois o seu JS pode ser executado antes, e evita alguns problemas com IE.

Recomendo o uso com jQuery, pois você já trata possíveis diferenças entre os browsers:
http://api.jquery.com/unload/


What is the best way to plot a HoD line using this code

Question: I have this script, but is there way to have the HoD line, straight / horizontal, stead of the wavey following a new intraday high? For example, if at new HoD is $105.55, a straight line will be horizontal at $105.55, then if there is a new HoD is $105.76, the straight line moves to $105.76?
<code>indicator("My script", overlay=true)

var float high_price = na
var int high_time = na

is_new_day = ta.change(time("D"))
bgcolor(is_new_day ? color.new(color.blue, 85) : na)

if (is_new_day)
    high_price := high
    high_time := time
else
    if (high > high_price)
        high_price := high
        high_time := time

plot(high_price)````

Thanks

I tried adding plot(high_price[1]) But that did not work
</code>
Answer: You want to use the line.new function. This will draw a line starting at the first bar of a new day until the last bar on your chart. It will adjust to the high of the day throughout the day.
<code>//@version=5
indicator("My script", overlay=true)

var float high_price = na
var int high_time = na
var line hodLine = na

is_new_day = ta.change(time("D"))
bgcolor(is_new_day ? color.new(color.blue, 85) : na)

if (is_new_day)
    high_price := high
    high_time := time
else if (high > high_price)
    high_price := high

if barstate.islast
    hodLine := line.new(high_time, high_price, chart.right_visible_bar_time, high_price, xloc = xloc.bar_time)
</code>


Single quote in in filter return exception querySelectorAll

Question: I face a problem when filter with single quote in field.
Anyone know why? And how to disable this exception?
Comment: The problem with single quote exists in 8.5.1 as well. What you uncovered is a possible security vulnerability with single quotes not being sanitized on a text input!
Comment: Weird I can't seem to recreate the problem. If you find the answer don't forget to post it here for future reference!
Comment: On Drupal 8.5.1 I entered a single quote in the same "content" view & did not get any errors. Do you have any custom JS running?
Comment: Thanks 100pic. This is the original drupal source to reference, I only add Admin toolbar and no custom js, no theme, no custom function. I will run update to 8.5.1 to see any difference (it is 8.5.0)
Comment: @100pic yes, the issue exists in 8.5.1 as Sensimple said. I found some patches can ignore the exception in console log and answer my question as your advice.
Answer: I found a solution for this by using patch.
https://www.drupal.org/project/drupal/issues/2902769
Because this is a core funtion patch, I marked it as can-solve but not plan to use it myself, because the filter works still only some annoying console log.