Kohana - Validate ORM

Question: I'm using Kohana for some time now. I'm using "has_many", "has_one", "belongs_to" without a problem, my question is:
If I have 2 tables like this:
tbl_foo1
id | tbl_foo2_id | field1
-------------------------
1  | 2           | bar
2  | 1           | foo

tbl_foo2
id | field1
-----------
1  | foo
2  | bar

I have to have a relation like: tbl_foo1 belongs to tbl_foo2 and tbl_foo2 has many tbl_foo1
So far so good.
The problem is when I try to save the relation in the controller..
So I have this code:
$t1 = ORM::factory('tbl_foo1')->values($values, $expected)->create();
$t2 = ORM::factory('tbl_foo2', $_POST['id']);
$t1->tbl_foo2_id = $t2;
$t1->save();

Ok, this should work, but I think this is not the best solution neither the most beautiful. For 2 reasons, 1 because of performance - it does 3 queries (1 to save $t1, 2 to find $t2, 3 to save relations of $t2 with $t1) and 2 because it may save empty records, because it doesn't validate the existence of the records in $t2.
So my main questions is, how this should be done?

My own solution
I used the solution that biakaveron gave me, thank you.
But still, there was the validation problem.. so I spent some time and came up with a solution, using the same example:
$t2 = ORM::factory('tbl_foo2', $_POST['id']);
$t1 = ORM::factory('tbl_foo1')->values($values, $expected);
$t1->foo2 = $t2; // foo2 is a belongs_to relationship
$t1->create();

in the tbl_foo1 model I added the rules function:
public function rules()
{
    'foo2_id' => array('not_empty')
}

So this way, I don't have to do another query, which is good for performance and it's a simple way to do it. And it works, because, when the ORM tries to find the id of the model tbl_foo2, if it doesn't find it, it returns NULL, so it will always empty no matter what!
Note: I used the DB transactions too (because this is just a portion of the process), so if one of the queries breaks for some reason, well no query will run. Just remember, you have to use one database engine that supports transactions (mine is InnoDB).
Comment: I found out [this question](http://stackoverflow.com/questions/9574548/kohana-orm-validate-the-belongs-to-relationship-exists), which is related with my, but still there's the problem of performance.. Kohana must have a better way to do it!
Comment: Please post your solution in its own answer, not as an edit.
Answer: 1 You can save model with belongs_to object:
$t2 = ORM::factory('tbl_foo2', $this->request->post('id'));
if (!$t2->loaded())
{
    // wrong ID for tbl_foo2
}

$t1 = ORM::factory('tbl_foo1')->values($values, $expected);
$t1->foo2 = $t2; // foo2 is a belongs_to relationship
$t1->create();

2 Check tbl_foo2_id with special callback.
Comment: Thanks for the tip about the "belongs_to" relationship. So how can I throw an error about the "missing" `tbl_foo2_id`, like the ones when the model rules doesn't meet? Thanks.
Comment: You should add rule (callback or closure) for `tbl_foo2_id`, which will generate an error. Maybe a simple `not_empty` rule?!
Comment: That was what I did! If you read my question, I putted my solution to this kind of problems :)

Kohana - Validate ORM


Is there any limit on subfolders within folder

Question: Hi All,
I want to know is there any limit on subfolders within folder in Linux and windows?
can any one provide information on how many subfolders can be created in one folder?
Thanks in advance for any input.
Comment: Usually if you have to ask this question, you've designed something wrong. That's just my experience though. Care to share the reason why you're asking?
Answer: If you are using ext3 in Linux, the limit is explained by Wikipedia:

There is a limit of 31998
  sub-directories per one directory,
  stemming from its limit of 32000 links
  per inode.
Answer: For FAT16 filesystems (mostly irrelevant these days, but still default on some USB mass storage / memory card devices) there is a limit of 512 directory entries in the root directory.
This can be less than 512 files/folders when long filenames are used.
Sub-folders do not have this problem.
Answer: The number of possible directories/sub folders is limited by the number of inodes for the file system.  In ext3, for example, it is typically V/2 where V is the volume size bytes.  So there is no limit in how many nested levels you can go for folders.
However, the maximum number of sub directories in one directory, for ext3, is limited to around 32000.
Comment: Note however that in order to access the files you need to provide a path < PATH_MAX which in Linux is usually set at 4096. So if your path is over 4k in length you might experience some failures
Answer: These theoretical limits are all well and good but in reality you will see serious performance problems with too many folders or files in a single folder under fat, ntfs or ext3 anyway.  You wouldn't really want more than about 10,000 in any single folder.


warning: function returns address of local variable [-Wreturn-local-addr]

Question: I get this error when compiling and have checked out other questions here with no further progress:

funciones.c: In function 'Lyapunov': ../funciones.c:55:2: warning:
  function returns address of local variable [-Wreturn-local-addr]
  return rgb;

First of all, I call the 'Lyapunov' function here in another .c :
*Please note that in this '.c' I have only posted the part of the code where Lyapunov is called and also the declaration of rgb.
unsigned char rgb[3];

while((int)linea>inicial){
        for(col=0;col<asize;col++){
               rgb = Lyapunov(col,linea);

               fwrite(rgb, 3, image);
        }
        linea++;
}

and the Lyapunov function from where I get the warning is here:
#include "lyapunov.h"
#include <math.h>

#define CLAMP(x) (((x) > 255) ? 255 : ((x) < 0) ? 0 : (x))

unsigned char *Lyapunov(int ai, int bi){
    int n, m;
    double a, b, lambda, sum_log_deriv, prod_deriv, r, x, rgb_f[3];
    unsigned char rgb[3];

    double lambda_min = -2.55;
    double lambda_max = 0.3959;

    a = amin + (amax-amin)/asize*(ai+0.5);
    b = bmin + (bmax-bmin)/bsize*(bi+0.5);
    x = 0.5;

        for (m = 0; m < seq_length; m++) {
            r = seq[m] ? b : a;
            x = r*x*(1-x);
        }

    sum_log_deriv = 0;
    for (n = 0; n < nmax; n++) {
        prod_deriv = 1;
        for (m = 0; m < seq_length; m++) {
                r = seq[m] ? b : a;

                prod_deriv *= r*(1-2*x);
                x = r*x*(1-x);
        }
        sum_log_deriv += log(fabs(prod_deriv));
    }
    lambda = sum_log_deriv / (nmax*seq_length);

    if (lambda > 0) {
        rgb_f[2] = lambda/lambda_max;
        rgb_f[0] = rgb_f[1] = 0;
    } else {
        rgb_f[0] = 1 - pow(lambda/lambda_min, 2/3.0);
        rgb_f[1] = 1 - pow(lambda/lambda_min, 1/3.0);
        rgb_f[2] = 0;
    }

    rgb[0] = CLAMP(rgb_f[0]*255);
    rgb[1] = CLAMP(rgb_f[1]*255);
    rgb[2] = CLAMP(rgb_f[2]*255);

    return rgb;
}

I assume there must be some kind of 'malloc' but my attempts trying to fix it have been a disaster.
Thank you in advance. Any help is appreciated.
Comment: Duplicate hundreds of times over.
Comment: possible duplicate of [warning C4172: returning address of local variable or temporary](http://stackoverflow.com/questions/3740151/warning-c4172-returning-address-of-local-variable-or-temporary)
Comment: Instead of returning an array pointer, I would pack 3 bytes of RGB into single `int` and return it, without messing with dynamic allocation.
Comment: You're trying to return `rgb`, which is a local array, and which will therefore be out of scope when you return.
Answer: You can use malloc as suggested, but looking at your code better idea would be to have a single static buffer passed to a function to have it's result (since you are using the buffer just once, and then discarding it's data), such that the function signature will be:
void Lyapunov(int ai, int bi, unsigned char rgb[]);

Then prior the use of the function you will need to define the buffer:
unsigned char rgb[3];

and then use it in your loop
Lyapunov(col,linea, rgb);

This way you will not need to worry about any memory leaks (resulting from the function).
Comment: This one is definitely the most sensible. I don't know why I got so blind about the memory handling. Thank you.
Answer: to avoid all the messy malloc/free calls, etc.  define the rgb in the caller and pass the address to the function.
Answer: unsigned char rgb[3];

is local to function and the scope of this array is within the function Lyapunov so once you exit the function this memory is no more valid. So the warning you are getting is the right one which says never return the local variables address which will lead to undefined behavior when used outside its scope.
Have your memory allocated of heap and then return the pointer as shown below.
unsigned char *rgb = malloc(3);

Comment: Since the function is used in loop, it would be a good idea to free it  each iteration.
Comment: Using dynamic memory allocation is somewhat heavyweight and requires that the caller "knows" that the memory returned must be free'd.  A better approach is for the caller to pass the required buffer to the function, and allocate/declare it as appropriate.
Answer: You trying to return an array rgb which stops existing outside of its local scope ( also the scope of the function ), which stops existing when you return from the function. Arrays cannot be returned by value.
You can put the array in a struct:
struct rgb_hold
{
    char rgb[3] ;
} ;

and return the struct, which can be returned by value.
Comment: @user3629249 : "Always" is a bit strong.  To be done advisedly perhaps.  In this case the size of the object returned is less that that of `double` for example.
Comment: always a bad idea to return other than fundamental data types and pointers
Comment: Code is not "returning an array `rgb`" - OP is only hoping to do that.    `unsigned char *Lyapunov()` returns a pointer to a `unsigned char`.  Yet returning a structure a valid approach. +1
Comment: In this case it may even make sense to use `struct rgb { char r, char g, char b } ;` (possibly with zero-packing if the file format requires three contiguous characters).  It would certainly make the code clearer.


PostgreSQL custom type + Hibernate mapping

Question: I am using PostgreSQL (9.1) and Hibernate (4.1.4). I want to map my custom PostgreSQL type into object in Hibernate.
I've created type in PostgreSQL like this:
create type nill_int as (value int8, nill varchar(100));

Now I want to map this type on Hibernate:
package my;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang.ObjectUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.usertype.CompositeUserType;

public class PGNillableIntegerType implements CompositeUserType {

    @Override
    public String[] getPropertyNames() {
        return new String[] {"value","nill"};
    }

    @Override
    public Type[] getPropertyTypes() {
        return new Type[] {IntegerType.INSTANCE, StringType.INSTANCE};
    }

    @Override
    public Object getPropertyValue(Object component, int property)
            throws HibernateException {
        if( component == null ) {
            return null;
        }

        final NillableInteger nillable = (NillableInteger)component;
        switch (property) {
            case 0: {
                return nillable.getValue();
            }
            case 1: {
                return nillable.getNill();
            }
            default: {
                throw new HibernateException("Invalid property index [" + property + "]");
            }
        }
    }

    @Override
    public void setPropertyValue(Object component, int property, Object value)
            throws HibernateException {
        if(component == null)
            return;

        final NillableInteger nillable = (NillableInteger) component;
        switch (property) {
            case 0: {
                nillable.setValue((Integer)value);
                break;
            }
            case 1: {
                nillable.setNill((String)value);
                break;
            }
            default: {
                throw new HibernateException("Invalid property index [" + property + "]");
            }
        }
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names,
            SessionImplementor session, Object owner)
            throws HibernateException, SQLException {

        assert names.length == 2;
        Integer value = (Integer) IntegerType.INSTANCE.get(rs, names[0], session);
        String nill = (String) StringType.INSTANCE.get(rs, names[1], session);

        return new NillableInteger(value, nill);
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index,
            SessionImplementor session) throws HibernateException, SQLException {
        if(value == null) {
            IntegerType.INSTANCE.set(st, null, index, session);
            StringType.INSTANCE.set(st, null, index + 1, session);
        } else {
            final NillableInteger nillable = (NillableInteger)value;
            IntegerType.INSTANCE.set(st, nillable.getValue(), index, session);
            StringType.INSTANCE.set(st, nillable.getNill(), index + 1, session);
        }
    }

    @Override
    public Class returnedClass() {
        return NillableInteger.class;
    }

    @Override
    public boolean equals(Object x, Object y) throws HibernateException {
        return ObjectUtils.equals(x, y);
    }

    @Override
    public int hashCode(Object x) throws HibernateException {
        assert (x != null);
        return x.hashCode();
    }

    @Override
    public Object deepCopy(Object value) throws HibernateException {
        return value;
    }

    @Override
    public boolean isMutable() {
        return false;
    }

    @Override
    public Serializable disassemble(Object value, SessionImplementor session)
            throws HibernateException {
        return (Serializable) value;
    }

    @Override
    public Object assemble(Serializable cached, SessionImplementor session,
            Object owner) throws HibernateException {
        return cached;
    }

    @Override
    public Object replace(Object original, Object target,
            SessionImplementor session, Object owner) throws HibernateException {
        return original;
    }

}

and use this in my entity:
package my;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;

import org.hibernate.annotations.Type;

@Entity
@Table(name = "test_test")
public class TestObj {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "IdGenerator")
    @TableGenerator(
        name = "IdGenerator",
        pkColumnValue = "test",
        table="SeqTable",
        allocationSize=1, initialValue=1)
    private Long id;

    private String test;

    @Type(type = "my.PGNillableIntegerType")
    @Column(columnDefinition = "nill_int")
//  @Columns(columns = {
//          @Column(name = "val"),
//          @Column(name = "reason")
//  })
    private NillableInteger nill;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }

    public NillableInteger getNill() {
        return nill;
    }

    public void setNill(NillableInteger nill) {
        this.nill = nill;
    }

}

where NillableInteger looks like this:
package my;

import javax.persistence.Column;
import javax.persistence.Entity;

public class NillableInteger {

    private Integer value;
    private String nill;

    public NillableInteger() {

    }

    public NillableInteger(String str) {
        str = str.substring(1,str.length()-1);
        String[] splitted = str.split(",");
        value = Integer.parseInt(splitted[0]);
        nill = splitted[1];
    }

    public NillableInteger(Integer value, String nill) {
        this.value = value;
        this.nill = nill;
    }

    @Override
    public String toString() {
        return "(" + value + "," + nill + ")";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((nill == null) ? 0 : nill.hashCode());
        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        NillableInteger other = (NillableInteger) obj;
        if (nill == null) {
            if (other.nill != null)
                return false;
        } else if (!nill.equals(other.nill))
            return false;
        if (value == null) {
            if (other.value != null)
                return false;
        } else if (!value.equals(other.value))
            return false;
        return true;
    }

    public String getNill() {
        return nill;
    }
    public void setNill(String nill) {
        this.nill = nill;
    }
    public Integer getValue() {
        return value;
    }
    public void setValue(Integer value) {
        this.value = value;
    }

}

This configuration throws something like this:
org.hibernate.MappingException: property mapping has wrong number of columns: my.TestObj.nill type: my.PGNillableIntegerType

Everything works fine when I use @Columns annotation instead of @Column in the TestObj, but this creates two separate columns in test_test table (TestObj mapping table) with types integer and character varying(255). What I want to achieve is that in the table will be one column with type nill_int (created custom PostgreSQL type) and Java objects will looks like above.
Any ideas?
Thanks, Arek
Comment: Full and explained solution in this link [network postgres types on hibernate][1]

  [1]: http://stackoverflow.com/questions/20019866/hibernate-postgresql-network-address-type-inet-cdir/22759209#22759209
Answer: Ok, this is what I've done to achieve above goal: I've changed my type to something which looks like this:
package my;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;

public class PGNillableIntegerType implements UserType {

    @Override
    public int[] sqlTypes() {
        return new int[] { Types.OTHER };
    }

    @Override
    public Class returnedClass() {
        return NillableInteger.class;
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names,
            SessionImplementor session, Object owner)
            throws HibernateException, SQLException {

        return new NillableInteger(rs.getString(names[0]));
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index,
            SessionImplementor session) throws HibernateException, SQLException {
        if(value == null) {
            st.setObject(index, null, Types.OTHER);
        } else {
            final NillableInteger nillable = (NillableInteger)value;
            st.setObject(index, nillable.toString(), Types.OTHER);
//          IntegerType.INSTANCE.set(st, nillable.getValue(), index, session);
//          StringType.INSTANCE.set(st, nillable.getNill(), index + 1, session);
        }
    }

    @Override
    public Object replace(Object original, Object target, Object owner)
            throws HibernateException {
        return original;
    }

    public Object assemble(Serializable cached, Object owner)
            throws HibernateException {
        return cached;
    }

    public Object deepCopy(Object value) throws HibernateException {
        return value;
    }

    public Serializable disassemble(Object value) throws HibernateException {
        return (Serializable) value;
    }

    public boolean equals(Object arg0, Object arg1) throws HibernateException {
        return arg0.equals(arg1);
    }

    public int hashCode(Object object) throws HibernateException {
        return object.hashCode();
    }

    public boolean isMutable() {
        return false;
    }

}

Now you can use @Column with PostgreSQL type in columnDefinition. Unfortunately, the problem are queries to hibernate (after some searching - I think the only way is to use SQL queries like this - if anyone knows how to do this with HQL or criteria it would be great...).
Comment: Any idea how to implement NillableInteger[] ?


Missing Zip Codes in Google APi

Question: We have enables Google Autocomplete on our Website but we have found some zip codes do not register with the API. 60514 will populate Clarendon Hills, IL 60514, but the follow zip codes do not work.
32312 – Tallahassee, FL
48260 – Detroit, MI
10510 – Westchester County, NY
29302 – Spartanburg, SC
24001 – Roanoke, VA
All these zip codes are active and verified from Zip-codes.com. You can even find the zip code in Google Maps but not in the Google API Autocomplete.
Comment: I'm voting to close this question as off-topic because this is something you should take up with Google support.
Comment: report it here: https://support.google.com/maps/answer/3094088?hl=en
Comment: Hey Mat. The Zip codes I provided show up in Google Maps but there is an issue with the autocomplete. Check out the Autocomplete when you sign up for an account with stack Over Flow. if you type in 29302 it will not autocomplete to Spartanburg, SC
Answer: In some cases, you may have to pass the country code ("US") following the zip code to the GeocodingApi.geocode function as the argument for the address to be resolved. Most US zip codes are resolved without that, but some would yield empty results unless followed by "US". For example:
`14264` yields no results
`14264, US` yields "Buffalo, NY, 14264, US"

Missing Zip Codes in Google APi


Proof of Segner's lemma for the number of sign alternations in polynomials

Question: In the context of Descartes' Rule of Signs, Segner's lemma is often stated as follows:

The polynomial $(x-1)p(x)$ has more alternations of signs than $p(x)$, for any real polynomial $p(x)$.

This is discussed e.g. in arXiv:1309.6664, but I was looking for a more focused treatment about this particular aspect, possibly including images to better visualise what's going on with the argument.
Answer: Write the polynomial as $P(x)=\sum_{k=0}^n a_k x^k$ with real coefficients $a_k\in\mathbb R$. We can always represent this polynomial via its sequence of coefficients $\boldsymbol a\equiv (a_0,...,a_n)$.
The number of alternations of signs, denoted with $v(P)$, is the number of times in the sequence $\boldsymbol a$ that we go from a positive to a negative sign, or vice versa. Equivalently, it's the number of indices $0\le k\le n-1$ such that $a_k a_{k+1}<0$.
This definition has to be somewhat adapted when $c_k=0$ for some $k$. Here we can simply ignore these so-called lacunary coefficients. This means that we count as an alternation of sign only a pair of successive nonzero coefficients with different signs. For example, $\boldsymbol a=(1,0,0,-1,1)$ has two alternations, as it is equivalent to $\boldsymbol a=(1,-1,1)$ for our purposes.
Multiplying by $(x-1)$ (or $(x-\alpha)$ for any $\alpha>0$ for that matter), gives the polynomial
$$(x-1)P(x) = -a_0 + (a_0-a_1)x + + \cdots + (a_{n-1}-a_n)x^n + a_n x^{n+1}.$$
Our question is thus how the number of alternations of signs in $(x-1)P(x)$ relates to $v(P)$.
Denote with $\boldsymbol a'$ the coefficients of $(x-1)P(x)$. Note that $a_k'=-a_k+a_{k-1}$, with the understanding that in this formula $a_{-1}=a_{n+1}=0$.
TL;DR

We consider how the signs of the coefficients of $P(x)$ relate to the signs of the coefficients of $(x-1)P(x)$.
We observe that trailing and leading zeros in the sequence of coefficients of $P$ can be neglected for the purpose of counting sign alternations. Similarly, we observe that we can replace any subset of repeated signs with a single one.
We are left considering sequences made of $+1,-1,$ and $0$s, without repetitions. We observe that the $0$s can also be neglected as far as sign alternations are concerned.
We are left with simple sequences of alternating $\pm1$ signs. For these we can easily count the number of sign alternations and reach the conclusion.

Full argument
Because we only really interested in the signs of the coefficients, let us denote with $\boldsymbol s$ and $\boldsymbol s'$ the signs corresponding to $\boldsymbol a$ and $\boldsymbol a'$. We chose $s_k,s_k'=\pm1$ if the corresponding coefficients $a_k,a_k'\lessgtr0$, or $s_k,s_k'=0$ if $a_k,a_k'=0$.
There are a few main observations we can make here:

$s'_0=-s_0$
If $s_k s_{k+1}<0$ (a sign alternation in the original sequence) then $s'_{k+1}=s_k$
If $s_k s_{k+1}>0$ (a sign permanence in the original sequence) then $s'_{k+1}$ cannot be determined from $\boldsymbol s$ alone.
If $s_k=0$, then $s'_{k}=s_{k-1}$ and $s'_{k+1}=-s_{k+1}$.

These rules convert the problem into a puzzle in which given a few ground rules we want to figure out how many sign changes are in the second sequence given those in the first one. Here is a bunch of examples of these rules applied to random $6$-elements sequences:

Here, each second row gives $\boldsymbol s'$ corresponding to the $\boldsymbol s$ reported in the first row. I'm denoting with a question mark the signs we cannot infer from $\boldsymbol s$.
A few things that are clear from observing these examples (or equivalently, from analysing the abovementioned rules) are:

Leading and trailing zeros can be safely ignored, as they don't change the number of sign alternations.
Similarly, repeated adjacent zeros can be replaced with a single zero

Let us then focus, without loss of generality, on the sequences without these features. Here's a few examples:

Observe now that, whenever we have repeated adjacent identical signs in the first row, we correspondingly get question marks in the second row. Question marks represent our inability to assess sign changes with the given knowledge. Still, these question marks can never decrease the number of sign changes in the second row, only possibly increase it. If we then forego trying to get an exact estimate, but limit ourselves to get a lower bound on the number of sign changes on the second row, we can ignore these question marks. This corresponds to ignoring sign permanences in the first rows. Let us then do this and consider sequences that do not have sign permanences. Here is a few examples:

We are almost there.
Focus now on the $0$ elements. Observe that we cannot simply remove these. For example, a $(+,0,+)$ pattern results in $(\square,+,-)$ (square denoting something that depends on the elements on the left of the pattern), while without the zero we would get a question mark due to the repeated $+$.
Instead, we can have two different types of patterns around a zero. Either $(s,0,s)$ with $s=\pm$, or $(s,0,-s)$ with $s=\pm$. In the former case, the second row has the pattern $(-s,s,-s)$, while in the latter case the second row has the pattern $(-s,s,s)$.
So when we have the pattern $(s,0,s)$, we get two additional sign changes in the second row, while with the pattern $(s,0,-s)$ there is no additional sign change.
All this is telling us that we can neglect all zeros from our sequences, and in the process only neglect zero or two additional sign changes.
Once the zeros have also been removed safely, we are left with simple sequences of alternating signs. More precisely, we have sequences of the form $(s,-s,s,-s,...,\pm s)$ of length $n$. Any such sequence has exactly $n-1$ sign alternations. Any such sequence becomes another sequence of the form $(-s,s,-s,s,...,\pm s)$ of length $n+1$, which has exactly $n$ sign alternations.
We thus proved that $(x-1)P(x)$ has at least one sign alternation more than $P(x)$.

To generate the images I used the following Mathematica snippet:
<code>signsAfterProd[listOfSigns_] := ReplacePart[
    listOfSigns,
    {
     1 -> -listOfSigns[[1]],
     j_ :> Which[
        listOfSigns[[j]] == 0 && listOfSigns[[j - 1]] == 0, 0,
        listOfSigns[[j]] == 0, listOfSigns[[j - 1]],
        listOfSigns[[j - 1]] == 0, -listOfSigns[[j]],
        listOfSigns[[j]] == 1 && listOfSigns[[j - 1]] == -1, -1,
        listOfSigns[[j]] == -1 && listOfSigns[[j - 1]] == 1, +1,
        True, 5
        ] /; 1 < j <= Length@listOfSigns
     }
    ] // Append[#, Last@listOfSigns] &;

prettyDoubleRowGrid[listOfLists_] := listOfLists /. {
     1 -> Style["+", Red, Background -> LightRed],
     -1 -> Style["-", Blue, Background -> LightBlue],
     0 -> Style["0", Background -> LightGray],
     5 -> Style["?", Background -> LightPurple]
     } //
   Grid[#, Frame -> All, ItemStyle -> Directive[Larger, Bold]] &;

makeNewSequence[sequence_] := {#, signsAfterProd@#} &@sequence;

Table[makeNewSequence@RandomChoice[{+1, 0, -1}, 6] //
   prettyDoubleRowGrid, 5, 5] // Grid

Table[RandomChoice[{+1, 0, -1}, 6], 1000] //
    Select[#[[1]] != 0 && #[[-1]] != 0 &&
       Not[Or @@
         Thread[Greater[Length /@ SequenceCases[#, {0 ..}], 1]]] &] //
    prettyDoubleRowGrid@*makeNewSequence /@ #[[;; 25]] & //
  Partition[#, 5] & // Grid

Table[RandomChoice[{+1, 0, -1}, 6], 1000] //
    Select[#[[1]] != 0 && #[[-1]] != 0 &&
       Not[Or @@
         Thread[Greater[
           Length /@ SequenceCases[#, {(0 .. | 1 .. | -1 ..)}],
           1]]] &] //
   prettyDoubleRowGrid@*makeNewSequence /@ #[[;; 25]] & //
  Partition[#, 5] & // Grid
</code>
Answer: Here is how I think of it for the case where there are no zero coefficients. Let p(x) be such a polynomial. We can always restrict ourselves to having the leading coefficient as 1. Imagine replacing each coefficient of p(x) with a + or - according to whether the coefficient is positive or negative, and imagine organizing these pluses and minuses in blocks, giving something like:
[++++][----][+++++]....
The number of sign changes for p(x) is one less than the number of blocks.  It is easy to show that multiplying by (x-a) for a>0 will produce a negative term when a + block meets a - block and a positive term when a - block meets a + block.  Ignoring what happens in between, we have a number signs equal to the number of sign changes for p(x), meaning that we have a number of sign changes that is one less than for p(x).  There will additionally be a x^n+1 term adding a + at the beginning, and the constant term will be opposite to that of the last block, adding a sign change at the end, so in total there must be at least one more sign change in (x-a)p(x) than in p(x).
Working with zero coefficients is similar.  Think of including 0 blocks. A minus block after a zero block still gives a negative term at the beginning and a plus block following a zero block still gives a positive term at the beginning.  I will let you work out the details as to why the zero blocks can be removed and still get the same results.


Setting iOS background/lockscreen image programmatically?

Question: I'd like to be able to set the lockscreen background image programmatically. I'm aware that this is only possible for jailbroken iOS devices.
Here are some things that I've tried:

Place a LockBackground.png in /private/var/mobile/Library/SpringBoard/. This works but requires a hard respring. notify_post("com.apple.language.changed"); doesn't work for a soft respring.
Use class-dump to dump private methods of UIKit. UIKit in 4.2 used to have a method called + (void)setDesktopImageData:(id)fp8; but it appears to be missing in 4.3 and above.

Is there anything that I'm missing?
Comment: Why don't you dump SpringBoard instead?
Comment: I thought I did and didn't find anything useful.. I'll try again.
Comment: If your interested in this question why not support the Area 51 proposal for a [jail-breaking Stack Exchange site](http://area51.stackexchange.com/proposals/18154/ios-jailbreaking-development?referrer=EuWVi6IpN0_KzzEhC7I-Qw2)
Answer: I found this in the SpringBoard dump which I think will be of use to you:
In SBWallpaperView.h:
- (void)replaceWallpaperWithImage:(id)image;

And in SBUIController.h:
- (id)wallpaperView;

So you can do something like:
[(SBWallpaperView *)[SBUIController sharedInstance] wallpaperView] replaceWallpaperWithImage:anImage];

That's one way.
The other one I found was to use SBWallpaperView's + (void)noteWallpaperPreferencesChanged;, I'm not that sure about this one, but it seems like if you do what you did in the first thing you tried, and then use this instead of a respring, it might work.
Comment: Where did you find these header files?
Comment: I dumped the SpringBoard executable.
Comment: If this answer worked for you, would you mind accepting it and giving me the the bounty?
Comment: My bad dude,  last time I used bounties it got awarded to the highest rep question. Anyway, I've accepted your answer, hope that some consolation. I haven't had a chance to test this though :(


How to prevent Angular2 core making dozens of HTTP requests on page load?

Question: So I'm developing an Angular2 application, and just by bootstrapping Angular2, I'm sent over 250 requests for nearly every js file present in the @angular/core node module package:

Specifically, everything seems to be imported from zone.js:101. Here is my application entry point, just to demonstrate I'm not doing anything unusual:
import { bootstrap }    from '@angular/platform-browser-dynamic';
import { LiveComponent } from './components/live.component';

bootstrap(LiveComponent);

Here is my HTML:

And here is systemjs.config.js:
(function(global) {

    // map tells the System loader where to look for things
    var map = {
        'app':                        'app', // 'dist',
        'rxjs':                       'node_modules/rxjs',
        'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
        '@angular':                   'node_modules/@angular'
    };

    // packages tells the System loader how to load when no filename and/or no extension
    var packages = {
        'app':                        { main: 'main.js',  defaultExtension: 'js' },
        'rxjs':                       { defaultExtension: 'js' },
        'angular2-in-memory-web-api': { defaultExtension: 'js' },
    };

    var packageNames = [
        '@angular/common',
        '@angular/compiler',
        '@angular/core',
        '@angular/http',
        '@angular/platform-browser',
        '@angular/platform-browser-dynamic',
        '@angular/router',
        '@angular/router-deprecated',
        '@angular/testing',
        '@angular/upgrade',
    ];

    // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
    packageNames.forEach(function(pkgName) {
        packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
    });

    var config = {
        map: map,
        packages: packages
    }

    // filterSystemConfig - index.html's chance to modify config before we register it.
    if (global.filterSystemConfig) { global.filterSystemConfig(config); }

    System.config(config);

})(this);

What's going on here?
Answer: That setup is for development only.
For production, you should create a bundle.
SystemJS has the SystemJS Builder.
JSPM will give you more options.
EDIT to answer your comment:
Yes, it's a build step. This seed project uses gulp, TypeScript, TSLint, SystemJS and JSPM to build the front end.
It has distinct gulp configurations for the development build and production build.
Also, in that seed project you'll see that the package.json dependencies section is empty. That is because he uses JSPM (this config) to manage the dependencies.
Now the bundler will follow the import {} from 'dependency's used by you code and only add to the bundle what was really used.
Comment: Can you go into a bit more detail? This is a pre-processing step correct? I.e. it'd get included in something like a gulp task?
Answer: There is new systemjs config in official quickstart
https://angular.io/guide/quickstart
Here is the copy
// Add package entries for angular packages
  ngPackageNames.forEach(function(pkgName) {
    packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
  });

So we can use their UMD bundle, and I tried it, from ~400 requests to about ~60 requests.


What assumptions are needed to get two integrals close to each other?

Question: I have functions $A,B,C$, where $\int_{\mathbb{R}} |A\cdot B - C| <\varepsilon$, and want to be able to say that $\int_{\mathbb{R}} A \approx \int_{\mathbb{R}} \frac{C}{B}$. What extra assumptions do I have to make on $A,B,C$ to get this to happen?
Answer: I'm not sure if this is what you're looking for, but if $B$ is bounded away from zero (i.e., if there exists $M$ such that $\frac{1}{|B(x)|} \leq M$ for all $x$, or almost all $x$), then we could say the following:
$$ \left| \int A - \int \frac{C}{B} \right| = \left| \int \left( A - \frac{C}{B} \right) \right| \leq \int \left| A - \frac{C}{B} \right| = \int \frac{1}{|B|} \left| AB - C \right| \leq M \int \left| AB - C \right| \leq M \epsilon $$
So we would have that $\int A$ is within $M \epsilon$ of $\int \frac{C}{B}$.


The partial expectation $\mathbb{E}(X;_{X>K})$ for an alpha-stable distributed random variable

Question: The partial expectation $\mathbb{E}(X;_{X>K})$ for an alpha-stable distributed random variable:
By playing with convolutions of Characteristic Functions of alpha-Stable distributions $S(\alpha, \beta, \mu, \sigma)$ and a payoff $K$, assuming $\mu=0$ and deriving under the integral sign, found the partial expectation $\mathbb{E}(X;_{X>K})$ , i.e., where F(x) is the distribution function of X, $\int_K^\infty x\, \mathrm{d}F(x)$ (which is not to be confused with the conditional expectation).
I am ending up with a difficult integral (easy to evaluate numerically but hard to get explicitly). With $1<\alpha\leq 2$:
$$\psi (\alpha, \beta, \sigma,  K) = \frac{1}{2 \pi }\int_{-\infty }^{\infty } \alpha  \sigma ^{\alpha } \left| u\right| ^{\alpha -2} \left(1+i \beta  \tan \left(\frac{\pi  \alpha }{2}\right) \text{sgn}(u)\right) \exp \left(\left| u \sigma \right| ^{\alpha } \left(-1-i \beta  \tan \left(\frac{\pi  \alpha }{2}\right) \text{sgn}(u)\right)+i K u\right) du$$
The solutions is easy for $K=0$, so
$$\psi(\alpha,\beta,\sigma,0)=-\sigma\frac{\Gamma \left(-\frac{1}{\alpha }\right) \left(\left(1+i \beta  \tan \left(\frac{\pi  \alpha }{2}\right)\right)^{1/\alpha }+\left(1-i \beta  \tan \left(\frac{\pi  \alpha }{2}\right)\right)^{1/\alpha }\right)}{\pi  \alpha }
.$$
Also, there is a well known solution for symmetric cases in Zolotarev's book. But it is the $K \ne 0$ that is critical.
Comment: One never knows. I was able to explicit form for the PDF when $\beta=\pm 1$ and we can get explicit expectations for $\mu=0$.
Comment: Alas, $K=0$ so far. But I can play by shifting $\mu$ and $K$.
Comment: Sorry but my first comment seems to fully apply to your question as it is stated. If you have a restricted setting in mind (such as K=0, or some other), please mention it.
Comment: Figured out an explicit solution for the general case where $\mu=0$ and $K=0$, cases for which we do not have explicit PDF and added to question above.
Comment: Hello, Nero. Comments can only be edited for 5 minutes, then they are locked. Of course, you can delete comments anytime you wish. Next, [based on this](https://twitter.com/nntaleb/status/549546351332442112), may we infer that you found a solution? If so, please consider posting it as an answer. Such things are allowed, actually encouraged! It is always nice to see you here.
Comment: I need to clean it up but that "solution" is semi-explicit (it has functions) and there is a slightly cleaner one. Thanks Ellie.
Comment: What makes you suspect this could have an explicit form (when defined, that is, for $\alpha\gt1$) while even the PDF has not?
Comment: For every K? $ $
Answer: Finally, the semi-explicit (but quite useable) answer for $K \neq 0$, which I jot down quickly before coming back with clean derivations and proofs.
$$\psi[\alpha, \beta,\sigma,K]=\sigma \frac{\Gamma \left(\frac{\alpha -1}{\alpha }\right) \left(\left(1+i \beta  \tan \left(\frac{\pi  \alpha }{2}\right)\right)^{1/\alpha }+\left(1-i \beta  \tan \left(\frac{\pi  \alpha }{2}\right)\right)^{1/\alpha }\right)}{2 \pi }+\sum _{k=1}^\infty \frac{i^k K^k \Gamma \left(\frac{k+\alpha -1}{\alpha }\right) \left(\beta ^2 \tan ^2\left(\frac{\pi  \alpha }{2}\right)+1\right)^{\frac{1-k}{\alpha }} \left((-1)^k \left(1+i \beta  \tan \left(\frac{\pi  \alpha }{2}\right)\right)^{\frac{k-1}{\alpha }}+\left(1-i \beta  \tan \left(\frac{\pi  \alpha }{2}\right)\right)^{\frac{k-1}{\alpha }}\right)}{2 \pi \sigma^{k-1} k!}$$
Summing to $p$, we get an approximation, with $p=3$ that seems to beat numerical integration for $K$ values "at-the-money", i.e., not far from the center).
The idea is to get rid of $\exp(i K u)$ which caused trouble because of oscillations around the center.


Switch out of postgres UNIX acount

Question: Using postgresql at an Ubuntu 14.04 command line.
sudo -i -u postgres puts me at
postgres@me-iMac:~$

How do I get back to my usual UNIX user, that is, to
me@me-iMac:~$

as I cannot sudo (don't know or cannot set postgres password for UNIX account)? I can close the terminal window, but do I have to?
Answer: Ctrl+D, exit or logout should un-sudo you.
Comment: Didn't realize it was so simple. Thanks.

Switch out of postgres UNIX acount


HTML -Espaçamento entre tds

Question: Existe alguma forma de dar espaçamento entre  como na figura abaixo?
OBS: Com espaçamento apenas na direita da .
Comment: Pode usar margin em cada uma. Exemplo, use no seu css: td{margin-right:10px;}
Comment: @TiagoP.C já tentei, não pega margin em td's
Comment: Então com padding, como diz a resposta do Pedro, abaixo.
Comment: padding é espaçamento interno, no meu caso quero dar espaçamento externo.
Answer: Sim, há uma forma utilizando o border-collpse e border-spacing no CSS:

table td {
  border: solid 1px #000;
}
table{
  border-collapse: separate;
  border-spacing: 10px;
  margin: 0 0 0 0;
}

        Coluna 1

          Coluna 2

        Coluna 1

          Coluna 2

Comment: Danilo, tinha feito com o cellspacing, mas vi que ele não é suportado pelo HTML5.
Comment: Sim ele nao é suportado, foi editar a minha resposta
Answer: Consegui o efeito que você precisa colocando uma classe na td da coluna em questão e usando um css personalizado pra ela:

td { background: gray; padding:10px }
.tdEspaco { display: table; float:left; margin-right:10px }
table { border-spacing: 5px; }

    1
    2
    3

    1
    2
    3

    1
    2
    3

Comment: Há uma maneira mais fácil do que utilizar o padding, o padding é espaçamento interno
Comment: O padding que eu coloquei não influencia na resposta. Foi só questão de estética.
Answer: Pode utilizar a propriedade css border-spacing na sua table.

table {
  border-spacing: 15px 10px;
}
table>tbody>tr>td {
  background: blue;
  padding: 5px 20px;
}

    Coluna 1

      Coluna 2

    Coluna 1

      Coluna 2

Comment: padding é espaçamento interno, no meu caso quero dar espaçamento externo.
Comment: Tente isso, nem sempre padding dá espaço interno.
Comment: Não deu cara, já tentei.
Comment: @BrendolL. Eu que não li direito sua pergunta. =/  Vou editar a resposta.
Comment: Consegui fazer com  border-collapse: separate; e  border-spacing: 10px 3px; mais desse jeito nao consigo tira a margin da direita =/
Comment: @BrendolL. confere as alterações que fiz.
Comment: margin-right: 0 não resolve, para tirar a margin da direita? Olhe minha resposta.
Answer: Consegui mais simples impossivel
border-right: solid 10px #fff;
border-bottom: solid 3px #fff;

Comment: Isso me parece gambiarra. É melhor você aprender do jeito certo do que fazer esse tipo de coisa.
Comment: Mais aí você não está dando espaço. Você esta deixando a borda mais espessa na cor branca.

HTML -Espaçamento entre tds


Complex numbers proof problem

Question: If $|z|,|w| \leq 1$, show that
$|z-w|^2 \leq (|z|-|w|)^2 + (\arg(z)-\arg(w))^2$, where $z,w$ are complex numbers.
How can I solve such a problem?
Comment: By doing some geometry. Can you solve the question when |z|=|w| first?
Answer: Let $z=r_1e^{\varphi_1},w=r_2e^{\varphi_2}$. We need to prove $$|r_1\cos\varphi_1-r_2\cos\varphi_2+i(r_1\sin\varphi_1-r_2\sin\varphi_2)|\leq (r_1-r_2)^2+(\varphi_1-\varphi_2)^2\iff$$$$ r_1^2+r_2^2-2r_1r_2\cos(\varphi_1-\varphi_2)\leq r_1^2+r_2^2-2r_1r_2+(\varphi_1-\varphi_2)^2\iff$$$$r_1r_2(1-\cos(\varphi_1-\varphi_2))\leq\frac{(\varphi_1-\varphi_2)^2}{2}$$ Since $r_1,r_2\leq 1$ we obtain $r_1r_2(1-\cos(\varphi_1-\varphi_2))\leq1-\cos(\varphi_1-\varphi_2)$. $1-\cos x\leq\frac{x^2}{2}$ is a well-known inequality wich can be proven using derivatives, substituting $x=\varphi_1-\varphi_2$ we obtain the desired inequality.
Answer: Let $z=r_1(cos\theta_1+isin\theta_1)$ and $w=r_2(cos\theta_2+isin\theta_2)$. Then $arg(z)=\theta_1$, $arg(w)=\theta_2$. It suffices to prove $-2r_1r_2cos(\theta_1-\theta_2)\leq-2r_1r_2+(\theta_1-\theta_2)^2$. To prove this, just need to prove $2r_1r_2(1-cos(\theta_1-\theta_2))\leq(\theta_1-\theta_2)^2$.Since $r_1\leq 1, r_2\leq 1$, we just need to prove $2(1-cos(\theta_1-\theta_2))\leq(\theta_1-\theta_2)^2$. This is obvious since it's easy to prove $2(1-cosx)\leq x^2.$ We finish the proof.
Answer: Hint:
Let $z = (a+bi)$ and $w= (c+di)$ and work with the LHS !!

Complex numbers proof problem


Why string and symbol are working inconsistently regarding discriminated unions?

Question: Why the second implementation is emitting an error in the following code?
type Op<T> = (value: T) => void
// Usecase: we need to mix some Op<string> with some Op<ohter> in one array

// implementation 1
type MixedOp<T> =
    | (Op<string> & { __isString: true }) // __isString is used for runtime check
    | (T extends string ? never : (Op<T> & { __isString: false }))

function run<T>(funcs: MixedOp<T>[], value: string, transform: (value: string) => T) {
    for (let fun of funcs) {
        if (fun.__isString) {
            fun(value)
        } else {
            fun(transform(value))
        }
    }
}

// implementation 2
// the only difference from implementation 1 is replaced __isString with a symbol
// while that replacement leads to an error
const IsStringSymbol: unique symbol = Symbol()

type MixedOp2<T> =
    | (Op<string> & { [IsStringSymbol]: true })
    | (T extends string ? never : (Op<T> & { [IsStringSymbol]: false }))

function run2<T>(funcs: MixedOp2<T>[], value: string, transform: (value: string) => T) {
    for (let fun of funcs) {
        if (fun[IsStringSymbol]) {
            fun(value) // Argument of type 'string' is not assignable to parameter of type 'string & T'.
        } else {
            fun(transform(value)) // Argument of type 'T' is not assignable to parameter of type 'string & T'.
        }
    }
}

Playground link
Comment: I don't understand how the question title applies; why do you think this has to do with distributive conditional types?  Looks more like an issue about discriminated unions to me.
Comment: You're right, my apologize. I just don't have a decent understanding of these concepts. And I've changed the title.
Answer: This looks like a current design limitation or missing feature in TypeScript.  According to microsoft/TypeScript#36463 and microsoft/TypeScript#36230, you currently cannot use a symbol-named property as the discriminant of a discriminated union.

If I have a regular discriminated union where the discriminant key is a string literal,
const k = "a"
type U = { [k]: true, b: number } | { [k]: false, c: string };
declare const u: U;

then I can use it to discriminate a value of that union type, as long as I access the property directly via a literal key:
// direct access
if (u["a"]) { // you could also write u.a
    u.b.toFixed(); // okay
} else {
    u.c.toUpperCase(); // okay
}

If I try to access the discriminant where the key is a const stored in a variable, it breaks:
// via variable
if (u[k]) {
    u[k].toFixed(); // error
} else {
    u[k].toUpperCase(); // error
}

The compiler doesn't attempt to do this because apparently the check ("is this k a const of a discriminant type?") degrades compiler performance.  Code indexes into objects all the time, so anything extra the compiler has to do for each such access will slow things down.  Does it degrade performance too much to be worthwhile? Not sure.  That's what microsoft/TypeScript#36230 is about.

If you try to do the same thing where the discriminated key is a symbol, you run into an issue because there is no way to use the key directly:
const k = Symbol();
type U = { [k]: true, b: number } | { [k]: false, c: string };
declare const u: U;

/*
if (u[???]) { // what do I put in the ???
    u.b.toFixed();
} else {
    u.c.toUpperCase();
}
*/

if (u[k]) {
    u[k].toFixed(); // error
} else {
    u[k].toUpperCase(); // error
}

This has the effect that you cannot use a symbol-named property to discriminate a union.  Which is what microsoft/TypeScript#36463 is about.

So, what can you do? Presumably you should still just use the __isString string key and move on.  Additionally, you could go to microsoft/TypeScript#36463, give it a , and explain why you need this feature (since the issue is marked as "awaiting feedback", the want to hear why people want this and how useful it would really be to implement).
Playground link to code


Como estilizar texto dentro da tag code?

Question: Eu gostaria de deixar um trecho de código estilizado assim como é nas ide mas não sei como fazer isso, procurei aqui e não encontrei nada a respeito, eu gostaria de deixar algo parecido com o que está na imagem abaixo com os nomes das variáveis, função, parâmetros, etc. com uma cor definida, ao invés de só o texto com a cor preta padrão da tag code.
.
Comment: Considere usar uma lib. Existem várias: [Prism](https://prismjs.com/) ou [HighlightJS](https://highlightjs.org/) são exemplos disso.
Answer: Após seu comentário, entendi do que se trata.
Se o que você quer é identar para exibir essa informação para o usuário final, recomendo utilizar essa lib do JS que o próprio github, slack e outros utilizam,
a Highlight.js, aqui também tem a sua documentação.
Existem algumas formas de utilizar, como é possível ver no tutorial do getting the library. Caso não use nenhum framework, pode importar direto da CDN que a lib é disponibilizada. Espero ter ajudado, qualquer coisa, só comentar.
Comment: Opa, boa noite, a imagem que inseri foi apenas um exemplo, eu gostaria mesmo era de saber como estilizar as variáveis, funções, etc. mas desde já, obrigado


Mathematical description of problem where sample is asked about three most liked brands?

Question: I have a population of branded products lets say diary food and want to know which brand is the most liked.
I ask 1001 people to tell me their three most liked brands. What is the mathematical description of the problem?
Answer: You ask an open-ended question, so responses are formatted (worded) freely. You have to categorize responses into bins of same or similar foods before you can produce summary statistics for the study. To decide that responces A and B are similar enough to constitute the same food for you you need to decide first where similarity between various foods ends and dissimilarity starts. This implies that you need to have pre-existent concept of whole population of foods. Thereby it cannot be infinite population for you anymore.
Comment: makes sense to me. I will refine the question
Answer: If you ask different set of brands each time. For example compare two of them or choose among 5. Then it can be solved as Descriptive choice algorithm to select best among others.
Comment: Do you have a description of descriptive choice algo?
Comment: I preffer Rank Maximum Entropy you can find implementation and some theory in lingpipe http://alias-i.com/lingpipe/docs/api/com/aliasi/dca/DiscreteChooser.html


Documenting PHP multiple inheritance with PhpDoc

Question: I have multiple inheritance like this one: Can I extend a class using more than 1 class in PHP? (let's not discuss this approach itself please) and want my IDE to know about inherited class methods and properties. Is there a way to do it with PhpDoc?
Comment: I don't like to call this trick multiple inheritance, but rather delegation.
Comment: Is your question more related to PhpDoc or more related to "how displays the appropriate auto-completion inside the editor"?
Comment: Savageman, it's about PhpDoc but it's also good to know if there are IDE specific tricks.
Answer: It seems there is currently no way to do it easily. I've created a ticket at PhpStorm issue tracker. Maybe they will add support for this feature.
http://youtrack.jetbrains.net/issue/WI-1730
Comment: This works in PHPStorm simply by using the special phpDoc param `@mixin` like so: `/* @mixin \Another\Class\Or\Namespace */` in the top of the class.
Comment: And finally they did it :)
Answer: The @method anotation should be used for classes implementing __call. On a related note, for __get, __set and __isset, the @property annotations should be used. The only thing I don't know for sure is whether Eclipse PDT supports these annotations. I know NetBeans does.
Comment: Thanks, I know I can use these but it's hard to redeclare all "inherited" methods and properties one by one. My hope is that there is some kind of PhpDoc I've missed that can delegate class methods and properties to another class.

btw., PhpStorm supports both @property and @method.
Answer: there is no support for multiple inheritances at class level. This means you can't extend more than one class at a time. However multiple inheritance is supported in interfaces. An interface can extend an arbitrary number of other interfaces
at a time.


Trying to delete values in an array

Question: The problem I'm having is that a Vehicle object is not being deleted from an array (I'm not sure if it's even storing correctly.)
The user must first add a Vehicle object to the array. And then it brings them back to the menu to ask if they want to add another, or delete an Vehicle.
The method in this class accepts a choice (either 1 or 2) to add a Vehicle to an array, or delete a vehicle from an array:
private void validate(int choice, File file) throws FileNotFoundException
{
    Vehicle[] vehicle =  new Vehicle[4];
    switch(choice)
    {
    case 1:
        store = new Store(file);
        store.addVehicle(vehicle);
        run();
        break;
    case 2:
        store = new Store();

        if(store.deleteVehicle(vehicle) == false)
        {
            System.out.println("Vehicle not deleted");
        }
        run();
        break;
}

Let's say the user wants to add a vehicle. It gets passed to the Store class:
My declarations in the Store class:
Vehicle[] vehicles = new Vehicle[4];

The addVehicle method in the Store class:
public void addVehicle(Vehicle vehicle[]) throws FileNotFoundException
{
    boolean found = false;
    if(canAddVehicle())
    {
        for(int i = 0; i < vehicles.length || !found; i++)
        {
            if(vehicles[i] == null)
            {
                Scanner reader = new Scanner(file);
                vehicle[i] = new Vehicle();
                vehicle[i].readRecord(reader);
                found = true;
                reader.close();
            }

        }
        System.out.println("Vehicle Added!");
    }
    else
    {
        System.out.println("You can not add more than 4 vehicles.");
    }

    System.out.println(vehicle[0].getVIN());
}

I added that last line at the bottom to test if it was storing the variables in the Vehicles class from when I called readRecord(). (It shows up correctly.)
Now it will go back to the first method posted and let's say the user wants to delete a Vehicle. It gets passed to the Store class method (deleteVehicle(vehicle)):
public boolean deleteVehicle(Vehicle vehicle[])
{
System.out.println(vehicle[0].getVIN());

    Scanner input = new Scanner(System.in);
    String VIN = null;

    System.out.println("Please enter the VIN of the vehicle you want to delete:");
    VIN = input.next();
    for(int i = 0; i < vehicles.length; i++)
    {
        if(vehicle[i] != null)
        {
            if(vehicle[i].getVIN().equals(VIN))
            {
                vehicle[i] = null;
                return true;
            }
        }
    }
    return false;
}

I added that line at the top to see if there was still a value for the VIN in slot 0 of the vehicles array... it turns out I get a NullPointerException error there... so it seems the first Vehicle object added is not being stored in the array correctly? I'm new to arrays and kind of lost as to what I am doing wrong. Any help would be appreciated. Thanks!
Answer: case 2:
    store = new Store();

    if(store.deleteVehicle(vehicle) == false)
    {
        System.out.println("Vehicle not deleted");
    }
    run();
    break;

Since you set store to new Store() every time, this is a fresh new instance of the Store class, so there is nothing to be deleted.
Comment: Thank you, that was one of the problems, another one was that I was declaring `Vehicle[] vehicle = new Vehicle[4];` each time the method was called
Answer: It seems to me that the problem might not be your array logic at all, but the fact that you are using different "store" objects in each call to your validate method.
Answer: To remove an element from an array is bit difficult. You can use System.arraycopy method to move/copy some of elements from source array to the destination array. However, I suggest to use ArrayList<T> instead of arrays.
Answer: Arrays store references to objects.  You can modify these objects however you'd like (maybe even "marking" them as deleted, but nothing that you do to the objects contained within the array will affect the array itself.  Furthermore, you can't just add or remove items from an Array - all you can do is replace them.  (So you could set a given array position to null - but then you'd have to remember to always check for this.)
If you really need to add or remove elements from an array, you need to re-create the array to the appropriate size, then copy over the remaining elements.  There are built-in methods with the Java API to help with many of these operations.  Alternatively, use a Collection - e.g. an ArrayList.
Comment: Yeah the assignment says I need to replace the arrays with null and then always check for null arrays
Answer: Tyr using ArrayList and
 ArrayList<Vehicle> vehicleList=new ArrayList<Vehicle>();
 //Add vehicle
 vehicleList.add(new Vehicle());
 vehicleList.remove(index);

Using this you can have any nos of elements in your list.
Answer: The design here is rather frightening. A lot of the functionality in store should be in vehicle, and the store should contain a the array of veichles, it shouldn't be passed to the store. A basic design would be something like this:
 class Vehicle {
        public Vehicle(/*parameters*/)
        static Vehicle readVehicle();
        public boolean equals(Vehicle other);
        // a ton of things to deal with vehicle data.
 }
 class Store {
       //an array of vehicles, or an arrayList of vehicles.
       public void addVehicle(Vehicle v);
       public boolean removeVehicle(Vehicle v);
 }

Now that your data structures make more sense, we can move on to what the actual algorithm should be. I assume that you want only one store, which might be initialized elsewhere, but which will be modified as you read and delete more vehicles.
validate() is a confusing choice for a name, because you're not validating the input, you're actually changing your data. In psudeocode, I think you want something like this:
  Store s = new Store(file);
  int choice;
  while((choice=getChoice())!=CHOICE_QUIT)
      runChoice(choice, s);

with the new runChoice function looking something like
  void runChoice(int choice, Store store){
        //perhaps this is not appropriate for all choices?
        //Where would you move it if not?
        Vehicle v = Vehicle.readVehicle();
        switch(choice){
         //i think you know what to do  ....
        }
  }

Comment: Thanks I realize this, but this is a project and it is required to be the way it is

Trying to delete values in an array


Can I borrow 15 bits for specific netmask in class B

Question: I read that I can't borrow 15 bits to create a specific netmask from a default class B netmask.
According to my calculation, borrowing 15 bits gives :
specific netmask = 255.255.255.254
Why did they say this is impossible ?
Comment: Classful networking is dead, killed over 20 years ago by RFCs 1518 and 1519. Please, let it rest in peace. Seriously, modern network equipment does classless routing.
Comment: /15 bitmask is 255.254.0.0. I don't understand the rest of your question.
Answer: RFC 3021 describes using 31-bit prefixes for point-to-point links. This leaves 1 bit for the host-id portion of the IP address. Normally a host-id of all zeros is used to represent the network or subnet, and a host-id of all ones is used to represent a directed broadcast. Using 31-Bit prefixes, the host-id of 0 represents one host, and a host-id of 1 represents the other host of a point-to-point link.
Local link (limited) broadcasts (255.255.255.255) can still be used with 31-bit prefixes. But directed broadcasts are not possible to a 31-bit prefix. This is not really a problem because most routing protocols use multicast, limited broadcasts, or unicasts.
For more information look at the Cisco Documentation.
Answer: 11111111.11111111.11111111.11111110  --> Network ID
11111111.11111111.11111111.11111111  --> Only available host ID BUT it's an all 1's host ID therefore a broadcast
Conclusion : No actual machine ID will be usable here hence a /31 is not possible if we want to do networking with client machines
Thanks Flippy


Solution to second order differential equation

Question: I'm reading a paper in which the authors solve the following equation:
$\frac{d^{2}}{dz^{2}}\hat{p}$($\bf{q}$$,z)$-$q^{2}\hat{p}$($\bf{q}$$,z)$-$\frac{iq_{y}}{(2\pi)^{2}}\delta(z-z_{2})$=0
here $\bf{q}$=$(q_{x},q_{y})$ and $q^{2}$=$q_{x}^{2}$+$q_{y}^{2}$
$\hat{p}$($\bf{q}$$,z)$ is the fourier transform of the real function $p$($\bf{s}$$,z)$:
$\hat{p}$($\bf{q}$$,z)$= $\int$$p$$(\bf{s}$$,z)$$e^{-i\bf{q}\cdot\bf{s}}$$d\bf{s}$
$z_{2}$ is a parameter in the differential equatin , $i$ is the imaginary unit.
the autors report the following solution:
$N_{1} cosh(qz)$+$N_{2} sinh(qz)$-$\frac{iq_{y}}{8\pi^{2}q}$$e^{|z-z_{2}|}$
$N_{1}$ and $N_{2}$ are coefficients that depend on the boundary conditions.
when i'm solving that equation with mathematica i'm getting different results:
I'm considering $p$ as being just a function of $z$ and treating $\bf{q}$ as a parameter
<code> DSolve[p''[z] - (q^2) p[z] - (I*qy/(2 Pi)^2) DiracDelta[z - z2] == 0,
  p[z], z]
</code>
and i get:
<code>p[z] = E^(q z) C[1] + E^(-q z) C[2] + (
 i E^(q z - q z2) qy HeavisideTheta[z - z2])/(8 Pi^2 q) - (
 i E^(-q z + q z2) qy HeavisideTheta[z - z2])/(8 Pi^2 q)
</code>
which is different from the one the authors are reporting in the paper.
Please can someone explain me how to corectly solve that equation?
thanks in advance
Comment: One thing you should do if you haven't already is compare the two answers for a specific choice of boundary conditions. It may be that the expression in Heaviside step functions is equivalent to theirs (which is plausible, given that absolute values also change their behavior discontinuously at 0)
Comment: I have not done it yet, because i don't have the boundary conditions directly on $\hat{p}$ but i need to substitute the solution for $\hat{p}$ in another expression. I Suspect that the origin in the difference between the two solutions lies in the fact that $\hat{p}$ is a complex function while mathematica solves the differential equation as if $\hat{p}$ was a real function.
Comment: eh, maybe. but even if you don't know which boundary conditions you 'really' want, you can still pick some more or less arbitrarily just to test the correspondence
Comment: anyway i considered the case in which all the constants are zero, the solution given by mathematica doesn't match in this case. this is because the part with heavyside adds a contribution to the solution only when $z > z_{2}$ while the abslute value is active even if $z < z_{2}$
Comment: thank you very much, i'm really having bad times with this problem...
Comment: Also, is this a quantum problem? (This looks like a free particle scattering off a delta potential to me.) If so, you should tag this with quantum-mechanics.
Comment: no, it actually comes from the solution of the Stokes equations (fluid dynamics): $\bigtriangledown^{2} \bf{u}$-$\bigtriangledown p$ = $\bf{0}$ and $\bigtriangledown \cdot \bf{u}$ = 0  I'm trying to solve this system of partial differential equation for a point force (that explain the Dirac delta) when i have two infinite parallel walls. I take the fourier transform in direction parallel to the walls (in which the domain is infinity) and i reduce the PDEquations to a system of ODE in which however the unknown function are complex functions.
Comment: Ahh. Well, there is a fluid-dynamics tag as well. That said, the quantum problem is well-known; [Wikipedia](http://en.wikipedia.org/wiki/Delta_potential) has an entire article on it. So reading that article may give you another way to check your understanding of the fluid problem.
Comment: $\displaystyle{\large\Theta\left(-x\right){\rm e}^{x} + \Theta\left(x\right){\rm e}^{-x} = \Theta\left(-x\right){\rm e}^{-\left\vert\,x\,\right\vert} + \Theta\left(x\right){\rm e}^{-\left\vert\,x\,\right\vert} =\overbrace{\left[\Theta\left(-x\right) + \Theta\left(x\right)\right]\,\,\,}^{=\ 1}\,\,\,\,\, {\rm e}^{-\left\vert\,x\,\right\vert}={\rm e}^{-\left\vert\,x\,\right\vert}}$
Comment: i know felix, the problem is that i don't have $\Theta (-x) e^{x} + \Theta (x) e^{-x}$ but rather $\Theta (x) e^{x} + \Theta (x) e^{-x}$ so i cannot manipulate the expression to get the correct result, there must be a mistake in the procedure
Answer: First, note that the first two terms of their solution are equivalent to your first two terms under the identification $(C_1,C_2)=\frac{1}{2}(N_1+N_2,N_1-N_2)$. So the only potential problem is in the second halves of the two results; even there, we can recognize a common factor of $-i q_y/8\pi q^2$, so the only issue is the exponentials themselves.
To see the issue more clearly, let's explicitly distinguish the $z<z_2$ and $z>z_2$ cases. We have $$e^{-q|z-z_2|}=\begin{cases} e^{q(z-z_2)}, & z<z_2 \\ e^{q(z_2-z)}, & z>z_2 \\  \end{cases}$$

This can be written in terms of Heaviside step functions as
$\Theta(z-z_2) e^{q(z_2-z)}+\Theta(z_2-z) e^{q(z-z_2)}$, so that the chice of which sign is in the exponent flips at $z=z_2$. This is nearly the same as the Mathematica answer, except that the step functions in the Mathematica answer are identical. Consequently the Mathematica answer has the second half of the answer being zero for $z < z_2$ and equal to the wrong value for $z > z_2$. So I'd trust the paper's result more than Mathematica...
If you really want Mathematica to do it right, you probably have to introduce the Dirac delta via boundary conditions rather than in the function itself. That is, you should integrate your ODE from $z=z_2-\epsilon$ to $z=z_2+\epsilon$. This will imply a 'jump' condition for the first derivative, which can be used as an internal boundary condition for the problem.
Comment: thanks very much for the answer, i already recognized that the difference lied only in the second part of the solution, i will try what you suggest and let you know the result.
Comment: hi, i tried to solve the equation in the following way:        DSolve[{p''[z] - p[z]*q^2 == 0, p[z2] == (I*qy/(4*Pi^2))}, p[z],  z] however i get this solution:  p[z] = 1/
  4 E^(-q z) ((i E^(q z2) qy)/Pi^2 + 4 E^(2 q z) C[1] -
    4 E^(2 q z2) C[1]) which is clearly not correct,
Comment: I think the following is happening: i'm solving a differential equation in the indipentent variable z and treating $\bf{q}$ as a parameter, therefore when mathematica solves the differential equation when it crosses $z_{2}$ applies the dirac delta effects. However $\hat{p}(\bf{q},z)$ the Dirac delta is multiplied by $i q_{y}$ meaning that the Dirac delta is not applied exactly at $z_{2}$ but rather at $z_{2} + i*q_{y}$. Maybe because $\hat{p}(\bf{q},z)$ is a complex function i have to split it into the real part and the imaginary part? have i been clear?


Unity UWP: Holographic Remoting for HoloLens

Question: I followed this Unity Blog Post tutorial. Everything works in Unity IDE but when I build it, UWP app throws an Exception:
InvalidOperationException: Enable VR Streaming to allow connection to remote holographic device

My Unity Version: 2018.03
Does anybody know any workaround?
Comment: Have you tried enabling VR streaming?
Comment: Unfortunately, I do not know how to enable VR streaming!
Answer: If using the MRTK, use the menu item to apply project settings.
Mixed Reality Toolkit > Configure > Apply Mixed Reality Project Settings

Otherwise, follow Microsofts instructions on working with hololens/Unity, which the tutorial you linked assumed was already done.  The key option is likely:
Player Settings > Universal Windows Platform tab > XR Settings group > Virtual Reality Supported

Comment: Strange, the error message seemed clear cut to me!  If it was me I'd make a new project and follow the instructions I posted and then the tutorial you posted again, in that order, in case the VR setting in your project got corrupted/messed up somehow...
Alternatively, I just tested remoting working on the latest Unity 2017 LTS version, but going back to that build might not be ideal...
Answer: Here is a solution for it:
As for having Holographic Remoting functionality in Unity UWP build, you should turn on 'WSA Holographic Remoting' in Player XR Setting and load two SDKs, the first one should be set to 'None' and the second one set to 'Windows Mixed Reality'. If you do not do that, your UWP app will be opened in Mixed Reality Portal instead of a normal App.
Be you you load your WindowsMR SDK anywhere in your script in Start() method like this:
private void Start()
{
    StartCoroutine(LoadingWindowsMrWrapper());
}

private IEnumerator LoadingWindowsMrWrapper()
{
    yield return new WaitForSeconds(1);
    StartCoroutine(LoadDevice("WindowsMR"));
}

private static IEnumerator LoadDevice(string newDevice)
{
        XRSettings.LoadDeviceByName(newDevice);
        yield return null;
        XRSettings.enabled = true;
}

If you have a UI Connect button, you can then call your HolographicRemoting.Connect(ipAddress);. By now you should be connected.
Also before application quit be sure you are disconnected.
Let me know if it did not workout for you.


Samples from Conditional Posterior Distribution in Pymc3

Question: Let us consider the following Hierarchical Bayesian model:

$w \sim\ Beta(20, 20)$
$K = 6$
$a = w * (K - 2) + 1$
$b = (1 - w) * (K - 2) + 1$
$theta \sim\ Beta(a, b)$
$y \sim\ Bern(theta)$

The above is the example of figure 9.3 in the book Doing Bayesian Data Analysis by John Kruschke.
I use the pymc3 to construct the model as follows:
import numpy as np
import pymc3 as pm
import arviz as az

K = 6
D = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0])

with pm.Model() as mdl:

    w = pm.Beta('w', alpha=20., beta =20.)
    a = w * (K - 2) + 1
    b = (1 - w) * (K - 2) + 1
    theta = pm.Beta('theta', alpha=a, beta=b)
    y = pm.Bernoulli('y', p=theta, observed=D)
    trace = pm.sample(10000, tune=3000)

My question is the following:

How can I compute the conditional posterior probability $p(theta|w=0.25,D)$? In other words how can I obtain samples from the conditional posterior distribution of $theta|w=0.25, D$?
Answer: I think you just need to fix the value of $w$ in your code, i.e.,
import numpy as np
import pymc3 as pm
import arviz as az

K = 6
D = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0])

with pm.Model() as mdl:

    w = 0.25
    a = w * (K - 2) + 1
    b = (1 - w) * (K - 2) + 1
    theta = pm.Beta('theta', alpha=a, beta=b)
    y = pm.Bernoulli('y', p=theta, observed=D)
    trace = pm.sample(10000, tune=3000)

You may find the comparison for the two distributions as follows: (orange is the one with $w=0.25$)

In your original code, the resulting samples follow $p(w, \theta \vert D)$, which is given by
$$
p(\theta, w \vert D) \propto p(D \vert \theta, w)p(\theta\vert w)p(w).
$$
The desired conditional distribution $p(\theta \vert D, w=0.25)$ is given by
$$
p(\theta \vert D, w=0.25) \propto p(D \vert \theta, w=0.25)p(\theta\vert w=0.25),
$$
that's why you just need to fix the value of $w$ in the code.
Comment: Thank you so much


How to correctly get Form API single checkbox value variable from database?

Question: I created an additional_settings fieldset for node type forms that holds a single checkbox:
$form['MY_SETTING']['enabled'] = array(
  '#type' => 'checkbox',
  '#title' => t('Enable'),
  '#default_value' => variable_get('MY_SETTING_' . $form['#node_type']->type, FALSE),
);

When I check the checkbox and save the node type form the value gets stored like that: MY_SETTING_MY_NODETYPE[0] = 'enabled'. The #default_value only understands TRUE and FALSE and doesn't work with enabled. I've sneaked in other modules (p.e. comments module) and have seen that they solved that with constants. But how to apply a constant in that form logic and let it be saved to the database?
Answer: You could use constants in place of string literals, sure, but that's not related to the issue you're having. That's simply a matter of converting the statement you already have to a boolean.
Which is as easy as:
$bool_enabled = variable_get('MY_SETTING_' . $form['#node_type']->type, 'disabled') == 'enabled';
$form['MY_SETTING']['#default_value'] = $bool_enabled;

Incidentally, the string "enabled" evaluates to TRUE in PHP, so it's not possible for it "not to work with enabled", it's just that 'disabled' also evaluates to TRUE, so you won't ever see a falsey value.
Personally I think the simplest solution is store the variable as an integer, 1 or 0. Then you can just assign it straight to the form element and let PHP's implicit integer -> boolean conversion take over. That's how all core (and contrib, that I've seen) modules handle it.


Does Gaussian Naive Bayes have paramter to be tuned

Question: I am trying to implement the Gaussian Naive Bayes from a scikit-learn library. I know that the Naive Bayes is based on the Bayes' theorem which is defined in high level as:
posterior = (prior * likelihood) / evidence.
As far as I know, the prior and evidence are learned from the training data.
I am not sure about likelihood whether Q1: is it also learned from the training data or by using Maximum likelihood estimation ?. Q2: Is there any hyper-parameter required to be tuned or not ?.
Comment: This question is better suited for [statistics.se]
Comment: Thanks, @juanpa.arrivillaga for sharing this website. I will ask the question there.
Comment: For the future, please keep in mind that [cross-posting](https://stats.stackexchange.com/questions/481189/does-gaussian-naive-bayes-have-paramter-to-be-tuned_) verbatim questions at more than one SE sites is [not allowed](https://meta.stackexchange.com/questions/64068/is-cross-posting-a-question-on-multiple-stack-exchange-sites-permitted-if-the-qu)
Answer: Suppose you have  Bayes Theorem as,
P(A|B) = (P(B|A)*P(A))/P(B)
Where,
P(A|B) = Posterior Probability
P(B|A) = Likelihood
P(A) = Prior Probability
P(B) = Marginal Likelihood

Answers to Your Question

Likelihood is calculated using the training data, and the Maximum Likelihood estimation is used to calculated the maximum value of the likelihood.

Naive Bayes has almost no hyperparameters to tune, so it usually generalizes well.
Comment: Please do **not** include pleads for accepting/upvoting in the post itself (edited out). Moreover, notice that the privilege of voting up is earned at 15 rep points, i.e. OP here has not yet reached it.


Generalized matroids

Question: Consider the following definition of matroid.

A matroid over a set $X$ is a family $\mathcal B\subseteq\mathcal P(X)$ of subsets of $X$ (the set of bases) with the following properties:

$\mathcal B$ is non-empty.
(base exchange property) For any two $A,B\in \mathcal B$ and $a\in A\setminus B$, there is a $b\in B\setminus A$, so that $$A\setminus\{a\}\cup\{b\}\in \mathcal B\qquad\text{and}\qquad B\setminus\{b\}\cup\{a\}\in \mathcal B $$

I am interested in a generalization, lets call it $k$-matroids, in which I replace the second axiom by the following:

For any two $A,B\in \mathcal B$ and distinct $a_1,...,a_k\in A\setminus B$, there is are distinct $b_1,...,b_k\in B\setminus A$, so that $$A\setminus\{a_1,...,a_k\}\cup\{b_1,...,b_k\}\in \mathcal B\qquad\text{and}\qquad B\setminus\{b_1,...,b_k\}\cup\{a_1,...,a_k\}\in \mathcal B $$

Is this generalization known and if so, where to read about it. If not, are there some obvious connections to classical matroids (which are 1-matroids).
Comment: Isn't your original definition of matroid the definition of a $\delta$-matroid, which is already a generalization of matroids?
Comment: @quarague I was under the impression that this was one of the equivalent definitions of matroids (from [Wikipedia](https://en.m.wikipedia.org/wiki/Matroid)). What exactly is a $\delta$-matroid? Is it because the exchange property is symmetric, that is it makes a statement about $A\setminus\{a\}\cup\{b\}$ *and* $B\setminus \{b\}\cup\{a\}$ instead of just one? I learned that this is equivalent to just one direction. But actually, I do not need the symmetry. If this is the problem I would rather edit the question.
Comment: You are correct, you defined a matroid. Your definition is the one that is generalized when defining $\delta$-matroids, that's why I got confused. In a $\delta$-matroid one uses symmetric difference and not all bases need to have the same cardinality. See https://en.wikipedia.org/wiki/Delta-matroid
Answer: Your second condition still defines a matroid, no?
By a repeated application of the standard basis exchange you can obtain your "stronger" k exchange property on all matroids I think:
Apply basis exchange to get another base B' = B1 - a_1 + b_1 for some b_1. Then apply basis exchange on B' and B2 to replace a2 with something from B2 again, etc.
Comment: Note that $k$ is a fixed number, so for example, in a 2-matroid the usual base exchange property does not necessarily hold. But yes, every $k$-matroid is also a $dk$-matroid for every $d\ge 1$.
Comment: Oh ok I see now thanks

Generalized matroids


Should I hold down Arpeggios for their duration?

Question: Their are 2 Arpeggios on this picture:

I know I should play their notes from the bottom to top very quickly BUT should I hold each note pressed down for their duration (dotted half note) OR should I release them immediately after being played?
Answer: The notes are written as dotted minims (three beats), lasting the whole bar. So they should be heard until the end of the bar.
That can be done in a couple of ways. Keep hold of the lowest note (played first), then play the other(s), and keep hold of all until you need to play the next bar. Or, play the first, catch it with the sustain (damper) or sostenuto pedal as you play the other(s), and release at the end of the bar, when the next ones come along.
The note in the treble clef should be played at the same time as the lower bass note, although depending on style, it could sound more effective being played as part of the arpeggio. Try both, and decide.
Answer: If you want to play the music as notated, you hold them for their notated duration.
Except, when you execute the arpeggio properly, those durations won't literally be the notated values, except for the lowest, first note of the chord.
Looking at the second chord, the D will be played first, on the beat. The C above it will be play a very small fraction of a beat after the D, a fraction too small to bother notating literally with rest values before the C.
The D is notated with a dotted half note. Its duration will be 3 beats.
The C is also notated with a dotted half note, but it comes after the D, and it ends at the measure's bar line. The C will stop at the same time the D stops. Obviously, if the C starts after D, but the end at the same time, the C has a literal shorter duration that the notated three beat dotted half note.
Only the bottom note of the chord will get its literal notated duration. All the other chord notes will be very slightly shorter. All of this is understood in the method of playing the embellishment of an arpeggio. The wavy bar is a notation convenience instead of writing out literal durations which would only clutter up the score.
Comment: I'm also avoiding getting into this because I don't think it's the OP's intent, but there's a question of expression: Are *any* notes always held for the entire duration? Not necessarily. I like to tell students "The duration doesn't really tell you 'how long the note lasts,' it tells you 'when the next note happens.'" But that's a level of hair-splitting nuance that I don't think the OP is looking for.
Comment: While the lowest note of the chord will be the longest, it might not have the literally notated duration; it could be a bit longer.  I recently heard Ivo Pogorelić playing Chopin; he achieved a remarkable independence of voices, and one aspect of this was not aligning everything in time.  Then, a few days later, I saw [this analysis of early 20th-century performance practice by Early Music Sources](https://m.youtube.com/watch?v=qFPW9ENtNKA) showing that performers in those days took far more liberty with meter.
Comment: There is artistic license and interpretation with anything. I'm answering what the basic meaning of the score is. When someone long ago explained to me what the arpeggio sign meant, it was perfectly clear, no follow up question about durations. The OP worded the question in a way that leads to a tedious answer about the slightly shortened durations. Otherwise I don't understand the reason for the question. Why would dotted half notes be played short because of an arpeggio sign? Other than you just don't want to play what is written.
Comment: It seems different people do it differently. In this video at 11:59 and 12:23 Barenboim seems not to have held the keys? https://www.youtube.com/watch?v=FZ1mj9IaczQ (My hands are not big so it's hard to hold all the keys)
Comment: I think the OP may have thought (as I did) one possibility may be to just "run through" all the notes from bottom to top note without holding any key after that, like a quick broken chord, which would be easier for my smaller hands than holding all keys.
Answer: You need to hold all the notes in the chord for their full value (dotted half note).
Answer: The notation asks you to play a chord, held for 3 beats, with an arpeggiated attack. (Not necessarily VERY quickly, it's not a race!)  There's no technical problem in doing this, holding the keys down with your fingers, so no need for  damper or sostenuto pedals.  Just do what it says.


What are the advantages and disadvantages of using Exchange in native mode vs pop3 connector

Question: I've a client which has Exchange 2010 installed. He is thinking to have POP3 connector to get all emails from his provider  as opposed to native redirection of all MX records to this server. He feels safer that emails are never lost there when he occasionally reboot server or do some other stuff on it and theoretically POP3 connector gives him that.
I've told him that we can always do MX redirection to his server and then keep his provider emails MX server as 2nd one so when his server gets rebooted emails will go to 2nd server and we will get his emails with connectors for his safety.
To make it even harder currently this client uses dynamic IP which means we can't use anything else then connector but if he's convinced to Exchange as native solution he would buy out the static IP.
So what are benefits and downsides of having Exchange working in native mode?
I can name a few myself.
Advantages:

control over how emails are handled
using pop3 connectors may not always work
access to OWA is much greater probability to work with static IP then dynamic one

Disadvantages:

spam / viruses have to be taken care of which means buying a software to do so (but you do get better control over what your email server accept and what they not as opposed to provider email system)
have to pay attention to your IP to not get marked as spammer yourself (as for example spamming computer in your network may cause your all emails to be marked as spam later on)
bigger costs due to need for static IP and additional software
longer downtime can cause emails to be lost (short downtime's usually have no impact on email flow
Answer: I'm not sure that the MX redirection will be a 100% solid solution.
In the past I've routed the MX records via a mail gateway service which then forwards on the Exchange.  This gives the benefit of spam/virus filtering outside the permiter (which saves bandwidth) with the added bonus that the gateway provider has lots of redundant kit which can queue up mail whenever the Exchange server has to go down for maintenance or a problem.
When there's a problem with Exchange you can generally still access the queueing e-mails via a  web control panel if there's any urgent stuff.
Answer: The POP3 connector will always be slower than a direct MX record pointer to the Exchange server, as the connector only polls every 15 minutes by default. This interval can be increased using the "ScheduleAccelerator" registry value but it's still doing a "pull" of mail versus a direct "push" to the server. I don't know if the POP3 connector functionality in Exchange 2010 has changed much since my past experience with SBS2003 but my vote is still with the direct MX record setup.
I echo Chris's suggestion of a hosted mail gateway for filtering and spooling. We use the McAfee (formerly MX Logic) SaaS E-mail Protection service for our clients with great results. Downtime for on-premise Exchange servers is no problem as McAfee immediately starts to spool/queue e-mail on their servers and holds it until the target server comes back online.
Comment: Matthew POP3 connector is only included in SBS and not Exchange itself so I won't be able to use built-in one. I have to choose external, pay solution.
Comment: My mistake - as I mentioned my only experiencing with POPing to an Exchange server has been with SBS2003. Either way - 3rd-party or not - you'll be polling for updates on a schedule and pulling them in versus having mail flow directly into Exchange.


Creating Omega sub theme manually

Question: I'm trying to create a functioning sub theme of Omega 4.4. I've worked  with Drush before with it, but the site is on a host that I'm not administrator of. I've tried the Drush Webservice module but not succeeded in executing the Omega Wizard. In short, the Omega Wizard may be extremely helpful, but I can't get it to work.
Next, I've tried to manually create a sub theme using the instructions here. However, the results of this is a theme catalogue in the Themes-folder, but the theme not showing up in Drupal. Perhaps I'm using the wrong instructions for the wrong version of Omega?
Anyhow, does anyone have instructions for how to install an Omega 4.4 sub theme manually for Drupal 7?
Answer: This documents manually copying the default starterkit subtheme in Omega 4.4. The instructions are similar for both "dusty" and "default" starter kits. Note that the "default" theme has libsass, and has less files then "dusty."

Dusty: the original omega front-end set up, which is becoming increasingly outdated.
Default: a more contemporary subtheme, front-end development wise. This is the better option.

Note: since I use a simple, one-word theme name in this example I can replace THEME-placeholders with one value. If you wish to have a more complex subtheme name, consider this array from the drush omega subtheme function:
'/{{ THEME }}/' => $machine_name,
'/{{ THEME NAME }}/' => $name,
'/{{ THEME SANITIZED }}/' => str_replace('_', '-', $machine_name),
'/{{ THEME CAMELCASE }}/' => $camel,
'/{{ THEME CAMELCASE LOWER }}/' => lcfirst($camel),

Prerequisite: Your theme's name. I'm using "mytheme" Substitute mytheme with your theme name.

Copy themes/omega/omega/starterkits/default (or dusty) to themes/mytheme
Copy default.starterkit.inc to mytheme/mytheme.info
Changes to mytheme.info

Change the name value to 'mytheme'
Insert base theme = omega to line 3
Change the theme file names from {{  THEME SANITIZED }} to mytheme
For example - from:
stylesheets[all][] = css/{{ THEME SANITIZED }}.reset.css
To:
stylesheets[all][] = css/mytheme.reset.css
Change the scripts name to css/mytheme.behaviors.js
Add regions info:
; ========================================
; Regions
; ========================================
regions[branding] = Branding
regions[header] = Header
regions[navigation] = Navigation
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[sidebar_first] = First Sidebar
regions[sidebar_second] = Second Sidebar
regions[footer] = Footer

Update theme name in files:

package.json: {{ THEME }} to mytheme
template.php: {{ theme name }} to mytheme
theme-settings.php: {{ THEME }} and {{ theme name }} to mytheme
preprocess/page.preprocess.inc: {{ THEME }} to mytheme
process/page.process.inc: {{ THEME }} to mytheme
sass/README.md {{ THEME SANITIZED }} to mytheme
The following renames are in dusty only:

.ruby-gemset
bower.json
libraries.make

Rename files as necessary:

Rename css files to css/mytheme.reset.css (default subtheme only) and css/mytheme.styles.css
Rename scss files to sass/mytheme.reset.scss (default subtheme only) and sass/mytheme.styles.scss
The following file-renames are in dusty only:

Rename css files to css/mytheme.hacks.css, css/mytheme.no-query.css and css/mytheme.normalize.css
Rename scss files to sass/mytheme.hacks.css, sass/mytheme.no-query.scss and sass/mytheme.normalize.scss

And there it is:
I've created a github of that shows the comparitive starterkit to wizard-created subthemes. Using this link, you can see all the necessary modifications you'll need to make, for dusty here or for default, here
I've updated this document out of pure curiosity. If I were in your situation, however, I would simply run the omega-wizard on my local dev environment, and push the theme to my server.

Creating Omega sub theme manually


How to sum and group for specific period of time

Question: I have 30 min data and would like to sum hours and group by daytime from 02:00 AM of current date to 02:00 AM next date, how can I do that?:
create table test (code varchar2(50), hour number, daytime date);

insert into test (code, hour, daytime) values ('K11','0.5','23-Feb-17')
insert into test (code, hour, daytime) values ('K11','0.5','23-02-17 00:30')
insert into test (code, hour, daytime) values ('K11','0.5','23-02-17 01:00')
insert into test (code, hour, daytime) values ('K11','0.5','23-02-17 01:30')
insert into test (code, hour, daytime) values ('K11','0.5','23-02-17 02:00')
insert into test (code, hour, daytime) values ('K11','0.5','23-02-17 02:30')
insert into test (code, hour, daytime) values ('K11','0.5','24-Feb-17')
insert into test (code, hour, daytime) values ('K11','0.5','24-02-17 00:30')
insert into test (code, hour, daytime) values ('K11','0.5','24-02-17 01:00')
insert into test (code, hour, daytime) values ('K11','0.5','24-02-17 01:30')
insert into test (code, hour, daytime) values ('K11','0.5','24-02-17 02:00')
insert into test (code, hour, daytime) values ('K11','0.5','24-02-17 02:30')
insert into test (code, hour, daytime) values ('K12','0.5','23-Feb-17')
insert into test (code, hour, daytime) values ('K12','0.5','23-02-17 00:30')
insert into test (code, hour, daytime) values ('K12','0.5','23-02-17 01:00')
insert into test (code, hour, daytime) values ('K12','0.5','23-02-17 01:30')
insert into test (code, hour, daytime) values ('K12','0.5','23-02-17 02:00')
insert into test (code, hour, daytime) values ('K12','0.5','23-02-17 02:30')
insert into test (code, hour, daytime) values ('K12','0.5','24-Feb-17')
insert into test (code, hour, daytime) values ('K12','0.5','24-02-17 00:30')
insert into test (code, hour, daytime) values ('K12','0.5','24-02-17 01:00')
insert into test (code, hour, daytime) values ('K12','0.5','24-02-17 01:30')
insert into test (code, hour, daytime) values ('K12','0.5','24-02-17 02:00')
insert into test (code, hour, daytime) values ('K12','0.5','24-02-17 02:30')

at end I'd like to get following data:
'K11',3,'23-02-17'
'K12',3,'23-02-17'

So it sum hours for example for K11 from ('K11','0.5','23-02-17 02:00') to ('K11','0.5','24-02-17 01:00')
Answer: You can do this by subtracting two hours.  Here is one method:
select trunc(date - 2/24) as dte, sum(hours)
from t
group by trunc(date - 2/24)
order by dte;

Oracle now supports interval syntax, so you can also d:
select trunc(date - interval 2 hour) as dte, sum(hours)
from t
group by trunc(date - interval 2 hour)
order by dte;

Comment: no, that doesn't work, it add two hours, that's it but no grouping.
Comment: @JoeGreen . . . I don't understand your comment.  First, this *subtracts* two hours, it does not *add* them.  Second, the `group by` does the aggregation.