How can I prove or disprove that the following functions are linear

Question: $f: \mathbb{R}^2 \rightarrow \mathbb{R}^2, (x,y) \mapsto (-x, |y|)$
$g:\mathbb{R}^3 \rightarrow \mathbb{R}^3, (x,y,z) \mapsto (y-x,0,x-y)$
$h: \mathbb{R}^3 \rightarrow \mathbb{R}, (x,y,z) \mapsto  \sqrt[3]{(x^3+y^3+z^3)}$
$t: \mathbb{R}^2 \rightarrow \mathbb{R}^4, (x,y) \mapsto (x+y,x,x-y,x^2-y^2)$
Can someone tell me please how to prove that a function is linear or disaprove it. I have found on the internet that a function is linear if these conditions are held:
If $f:\mathbb{V} \rightarrow \mathbb{W}$ is a map between vector $\mathbb{V}$ and $\mathbb{W}$ over the real numbers $\mathbb{R}$ (over any field $\mathbb{F}$), then f is linear if and onl if:
1) $f(v_1+v_2)=f(v_1)+f(v_2)$
2) $f(av)=af(v)$
for all $v,v_1,v_2\in \mathbb{V}$ and all $a\in \mathbb{R}$
If someone can explain maybe why this is true and how to use it.
And yes, I have been loking on internet but can't finds anything.
Comment: Why is this true? It is the definition of a linear mapping, one can't ask wether it's true or false. And regarding your question: you just have to check if the given functions have the two properties you listed, e.g. for the first one, if $$f(v_1+v_2)=f(v_1)+f(v_2)$$ all you have to do is pluck in $v_1=(x_1,y_1),v_2=(x_2,y_2)$ and check if the equation holds.
Answer: To disprove linearity, you'll need some kind of example.
Take the first function.  This one is not linear.  To show that this is the case, we need an example such as
$$
v_1 = (0,1), \quad v_2 = (0,-1)
$$
We find that
$$
f(v_1 + v_2) = f[(0,0)] = (0,0)
$$
On the other hand,
$$
f(v_1) + f(v_2) = f[(0,1)] + f[(0,-1)] = (0,1) + (0,1) = (0,2)
$$
So, the first function is not linear.
Proving linearity, on the other hand, requires that we show linearity holds for every possible input.
Take the second function.  To show that this is linear, we need to show that both parts of the definition hold.  To prove the first property, we consider any pair of inputs $(x_1,y_1,z_1),(x_2,y_2,z_2)$.  We then have
$$
f[(x_1,y_1,z_1) + (x_2,y_2,z_2)] =
f[(x_1+x_2,y_1+y_2,z_1+z_2)] = \\
= \cdots =
f(x_1,y_1,z_1) + f(x_2,y_2,z_2)
$$
Answer: Hint:
Simply apply the definition to the given functions.
1) $f(v_1+v_2)=f(v_1)+f(v_2)$
2) $f(av)=af(v)$
becomes, for $f: \mathbb{R}^2 \rightarrow \mathbb{R}^2, (x,y) \mapsto (-x, |y|)$:
1) $f((x_1,y_1)+(x_2,y_2))=f((x_1+x_2,y_1+y_2))\\=(-(x_1+x_2),|y_1+y_2|)\\=f((x_1,y_1))+f(x_2,y_2)\\=(-x_1,|y1|)+(-x_2,|y_2|)\\=(-(x_1+x_2),|y_1|+|y_2|)$
2) $f(a(x,y))=f((ax,ay))=(-ax,|ay|)=af(x)=a(-x,|y|)=(-ax,a|y|)$.
What do you think about these assertions ?


Dynamically loop a dataset for all column names

Question: I am working on project where I have around 500 column names, but I need to apply coalesce function on every table name .
df1 schema
-id
-col1
...
-col500

df2 schema
-id
-col1
...
-col500

Dataset<Row> newDS=  df1.join(df2, "id")
.select(
                df1.col("id"),
                functions.coalesce(df1.col("col1"),df2.col("col1")).as("col1"),
                functions.coalesce(df1.col("col2"),df2.col("col2")).as("col2"),
...
functions.coalesce(df1.col("col500"),df2.col("col500")).as("col500"),
                )

        .show();

What I have tried
 Dataset<Row> j1 =  df1.join(df2, "id");
Dataset<Row> gh1 = spark.emptyDataFrame();

    String[] f =  df1.columns();
     for(String h : f)
     {
         if(h == "id")
             gh1 = j1.select(df1.col("id"));
        else{
            gh1 = j1.select(functions.coalesce(df1.col(h),df2.col(h)).as(h));

        }

     }

     gh1.show();

Comment: What is the issue you are having?
Answer: df1.columns will returns the String Array, so cannot invoke streams on it, refer.
Column[] coalescedColumns =
                Stream.of(df1.columns())
               .map(name -> functions.coalesce(df1.col(name),df2.col(name)).as(name))
                 .toArray(Column[]::new);

        Dataset<Row> newDS = df1.as("a").join(df2.as("b")).where("a.id == b.id").select(coalescedColumns);

Answer: If I understand correctly, you have two dataframes with the same schema and you want to coalesce their 500 columns 2 by 2 without having to write everything.
This can be achieved easily by providing a sequence of columns to select. Also since select does not accept sequences of columns but rather a variable number of column arguments, you need to add : _* to let scala know that it needs to treat all the elements of the sequence as separate arguments.
val cols = df1.columns.filter(_ != "id")
df1
    .join(df2, "id")
    .select(col("id") +: cols.map(n => coalesce(df1.col(n), df2.col(n)) as n) : _* )

Answer: In Java, you can pass an array of values to methods expecting variable number of arguments, so you can rewrite your code like this :
Column[] coalescedColumns = Stream.of(df1.columns())
             .map(name -> functions.coalesce(df1.col(name),df2.col(name)).as(name))
             .toArray(Column[]::new);

Dataset<Row> newDS = df1.join(df2, "id").select(coalescedColumns)

I didn't exclude the id column since coalesce will work as expected on this column as well


How to make text alignment in textview

Question: I have an app where there's a dialog which contains conditions with a button below named as "Got it". My problem is that I want the text in the TextView to be in proper alignment line by line.
code:-
 <TextView
    android:id="@+id/HeaderText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/mainImage"
    android:layout_centerInParent="true"
    android:fontFamily="sans-serif-light"
    android:gravity="center_vertical"
    android:padding="10dp"
    android:layout_marginLeft="10sp"
    android:layout_marginRight="10sp"
    android:text="*kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
    android:textColor="#000"
    android:textSize="16sp"/>

Image:
Comment: Possible duplicate of [How do I center text horizontally and vertically in a TextView on Android?](http://stackoverflow.com/questions/432037/how-do-i-center-text-horizontally-and-vertically-in-a-textview-on-android)
Comment: You can use `android:gravity="center"` or ` android:gravity="center_vertical|center_horizontal"`'
Comment: see i want kkkk below kkkkkk not below *
Comment: A TextView doesn't know the difference between `*` and `k`. It only cares that all characters are properly displayed according to the view configuration. It will always put the 1st character on a new line right below the first character on the previous line, hence `k` will always be below `*` in this case.
Answer: Try below code......
<TextView
        android:id="@+id/HeaderText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/mainImage"
        android:layout_centerInParent="true"
        android:fontFamily="sans-serif-light"
        android:gravity="center_vertical"
        android:text="*kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
        android:textColor="#000"
        android:textSize="16sp" />

Answer: You can try a combination as :
android:gravity="left|center"

How to make text alignment in textview


Why isn't my mod_rewrite rule working?

Question: The rule is:
RewriteRule ^r/([^/.]+)/?$ generateIssuePage.php?r=$1 [L]

When a browser requests myip.com/r/thing, it should redirect to myip.com/r/generateIssuesPage.php?r=thing.
If I just type in www.myip.com/r/generateIssuesPage.php?r=thing, it works fine. But if I request www.myip.com/r/thing, I get 404. What's wrong with it?
Answer: A great tool for testing out your htaccess rules is http://htaccess.madewithlove.be/
Using that tool, it suggests that the htaccess is setup correctly, so that http://www.myip.com/r/thing redirects to http://www.myip.com/r/generateIssuesPage.php?r=thing
Have you checked that htaccess is working at all for you, but creating a simple global redirect?

Why isn't my mod_rewrite rule working?


maximum number of maximal independent set in a graph with n vertices

Question: Is it always true that for any connected graph G with n vertices, the maximum number of maximal independent set is at most n?
Answer: No.
A concrete example: Let $P$ be the 8-vertex path $P=u_1u_1\ldots u_8$. Then
$\{u_1,u_3,u_5,u_7\}$, $\{u_1,u_4,u_6,u_8\}$, $\{u_1,u_3,u_6,u_8\}$, $\{u_1,u_3,u_5,u_8\}$, $\{u_1,u_4,u_7\}$, $\{u_2,u_4,u_6,u_8\}$, $\{u_2,u_5, u_8\}$, $\{u_2,u_4, u_7\}$,$\{u_2,u_5, u_7\}$ are all maximal independent sets in $P$ and there just listed are $9>8$ such sets.
In fact for a path $P_n$ on $n$ vertices; $n$ large, there are an exponential number (in $n$) of maximal independent sets.


Sum of Poisson process and i.i.d. random variable

Question: I'm stuck on one problem from my stochastic class, which writes as follows:
$(N(t),t\geq 0)$ defines a Poisson process with parameter $\lambda$, and $S_n$'s are the $n$th point of arrival, following $\Gamma(n, \lambda)$. Suppose $Z_n, n\geq 1$ are i.i.d. random variables, with p.d.f. $p(x)$.
Now define $$W = \min_{n\geq1} \{S_n + Z_n\}$$
What is the probability $P(W>w)$?
Obviously $W>w$, if and only if $S_n + Z_n > w, \forall n$
But what then? Since $S_n$'s are not independent, I think there should be a smart way of doing this.
Thanks in advance!
Answer: [I'm going to assume that $P[Z_n>0]=1$ and that $(Z_n)$ is independent of $\{N(t),t\ge 0\}$.] The key to a "smart" approach to this is the observation that the collection $\{(S_n,Z_n): n\ge 1\}$ is a Poisson point process (call it $\Pi$) in the quadrant $(0,\infty)\times(0,\infty)$ with intensity $k(x,y)=\lambda p(y)$ with respect to Lebesgue measure. The event $\{W>w\}$  can be expressed as $\{\Pi(T_w)=0\}$, where $T_w$ is the solid triangle $\{(x,y): 0<x\le w, y\le w-x\}$. The random variable $\Pi(T_w)$ has the Poisson distribution with parameter $\int_{T_w}k(x,y)\,dx\,dy$. Once you evaluate this integral, the probability $P[\Pi(T_w)=0]$ will be at hand.
A second approach involves conditioning on the value of $N(w)$.
Clearly $\{N(w)=0\}\subset\{W>w\}$ For $n\ge 1$, given that $N(w)=n$, the arrival times $S_1,S_2,\ldots,S_n$ have the same distribution as the order statistics of an iid collection $\{U_1,\ldots,U_n\}$ of random variable uniformly distributed on $(0,w)$. Thus,
$$
P[W>z|N(w)=n] =P[U_k+Z_k>w, k=1,2,\ldots,n]=\left(P[U+Z>w]\right)^n,
$$
where $Z$ has density $p$ and $U$ is independent of $Z$ and uniformly distibuted on $(0,w)$. Therefore,
$$
P[W>z|N(w)=n] =\left(\int_0^w G(w-s)\,ds\right)^n,
$$
where $G(y)=\int_y^\infty p(z)\,dz =P[Z>y]$. Use the Law of Total Probability and the known distribution of $N(w)$ to conclude.


How to change default region/culture settings in Windows 2012

Question: I have researched this topic through the web but can't find a definitive answer.
Our server team has recently upgraded our SQL Servers VMs from Win 2003 to Win 2012.
Given our region we run all our in-house built apps under en-ZA.
However we have a work around where SQL Server 2012 needs to run under an account with en-US settings. This is to support a legacy metastorm workflow application.
The issue comes into play when the sql server agent job triggers a console app (en-ZA) to generate a comma delimited file with large monetary values.
The agent is running under en-US so the app goes "SOMEWHERE" (I am hoping an editable OS store of sorts) and gets the "DEFAULT" en-ZA settings which have changed since Win 2003.
The comma delimited file now has a decimal separator of "COMMA" instead of "DOT". Previous Win 2003 version had a "DOT" decimal separator for large monetary values.
The comma in the monetary values causes an issue in another importer app down the line.
The question is where are the default values for the region stored? and how can they be changed? I need to know this so I can revert the default settings for en-ZA to the way it was in Win 2003.
I know region settings can be customized for an account but how can the actual default en-ZA settings be changed.
If I can understand this then maybe this can be corrected via group policy.
Answer: You can also do it from the Control Panel, without changing manually the registry. There's an option allowing you to apply the Current User settings to the System Accounts.
Open Language --> Advanced settings --> Apply language settings to...

Then click the button "Copy Settings" and check the option "Copy to Welcome Screen and System Accounts".
Done.
Answer: Regional settings are applied per user. For the system account you can change it via the regisrty, see here
Change the HKEY_USERS/.DEFAULT/International/sDecimal key
Answer: What you're looking for is the "regional settings".
In Server 2012, (at least with US English), you can access them by opening up the Start menu and typing "Regional."  It's under settings, and the only item that comes up, titled Change date, time or number formats.
If you click the Additional settings... button, and then the Currency tab, you can customize the format, and change your "decimal symbol" and/or  "Digit grouping symbol" to something that won't cause problems form your SQL server.

If you wish to change this via GPO, or heaven forbid, editing the actual registry values, there's a technet blog on how to do it that way as well.  It's done through a Computer Group Policy Preference Registry collection (Computer Configuration -> Preferences -> Windows Settings -> Registry), and the registry subkeys you want are located under HKEY_CURRENT_USER\Control Panel\International.


Derivation of expected loss ESL (integrating over conditional expectation confusion)

Question: I am trying to understand the derivation of expected loss (equation 2.11 in Elements of Statistical learning) and there is a specific step I do not understand.
We start with
$EPE(f) = E(Y - f(x))^{2}$
and I understand the derivation up to:
$\int_{x} E_{Y \lvert X}(L(x,y)) p(x) dx$
(all omitted steps can be seen here Confused by Derivation of Regression Function)
However, I do not understand how the above is equivalent to:
$E_{X}E_{Y \vert X}L(x,y)$
Why are we multiplying $E_{X}$ by $E_{Y \vert X}$. Where does $E_{X}$ come from? What probability rule/theorem is responsible for this?
Answer: $E_XE_{Y\mid X}$ is not a multiplication, it's a composition.
If both $X,Y$ are random, then $L(X,Y)$ is a real-valued random variable.
By taking the first expectation, you "integrate out" $Y$, which produces a new random variable
$$ Z(x) = E_{Y\mid X}\left[L(x,Y)\mid X=x\right]$$
This variable is still random because $X$ is. For each event $X=x$ you have $Z(x) = z$.
As with any random variable, you can take the expectation of $Z$ with respect to $X$:
$$ E_X[Z(X)] = E_X\left[E_{Y\mid X}\left[L(X,Y)\right]\mid X\right] $$


What is the best filesystem for backing up on external hard drive?

Question: I have a 1TB consumer grade NAS and I can use whatever file system I please on it. I only plan to ever use it with linux based systems, so windows compatibility is not really a priority. What is the best file system for archiving? JFS? Ext3? Ext4? btrfs?
Answer: ext4 with journaling turned on and delayed allocation (dealloc) turned off.  The extents (introduced in ext4, but also available in xfs) will speed up dealing with large files--which I assume you'll be using.
Comment: Could you expand a bit on why you recommend those exact settings for journaling and delayed allocation?
Comment: @kasperd This is a 6 year old answer, but... the only suggestions I gave were journalling on, delayed allocation off.  Both prevent data loss, and there are a variety of articles about why these settings are valuable.
Comment: This may be a 6 year old answer, but it was edited just a couple of hours before my comment.
Answer: Btrfs is quite stable nowadays [well, at least relatively :-) for 2.6.37 kernel] and it supports on-fly compression, amongst other nice features.
Ext4 is quite nice as well. Unless you're risky enough for Btrfs EXT4 could be good choice, but it's also not such matured comparing to EXT3.
JFS as a surprise, supports extents for a long time, formats/mounts fast and hence can be a good choice for back-ups (just remember that it has to be fsck'ed on unclean shutdown).
Answer: I use btrfs. Why do I use something that isn't production quality? Because I've got several different backups, so corruption in one isn't a very big problem for me. And btrfs does checksums of data, so if I can recover from the backup, I can be sure that the data is intact.
Comment: Btrfs is still unstable. Mike wants a filesystem for backup, which means archival, perhaps for a long time (who knows when that data will be necessary?). I wouldn't recommend a filesystem that is not considered stable yet.
Comment: I think he meant what happens if 5 years later you go back to the data only to find the specification was finalised after you wrote it and you cant read it back any more ?
Comment: @Juliano: And you think I failed to bring this up in my answer?


error from a server in java

Question: I have the follwing code which is a thread pool in java which accepts only one client
public class ServerThread implements Runnable {

    ServerSocket serverSocket;
    Socket clientSocket;
    protected boolean isStopped = false;
    int serverPort = 6500;
    private String serverIpAddress = "127.0.0.1";
    DataInputStream is;
    ObjectOutputStream os=null;

    protected BlockingQueue queue = null;

    protected ExecutorService threadPool2 =
    Executors.newFixedThreadPool(1);

    public ServerThread(BlockingQueue queue) {
        this.queue=queue;
    }

    public void run() {
        try {
            InetSocketAddress serverAddr = new InetSocketAddress(serverIpAddress, serverPort);
            serverSocket = new ServerSocket();
            serverSocket.bind(serverAddr);

            System.out.println("s-a creat");

        } catch (UnknownHostException e) {
            System.err.println("Don't know about host");
        } catch (IOException e) {
            e.printStackTrace();
        }

        while(!isStopped()){
            clientSocket=null;

            try{
                clientSocket = serverSocket.accept();
    }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            WorkerServerRunnable workerRunnable = new WorkerServerRunnable(queue,clientSocket);
            this.threadPool2.execute(workerRunnable);

        }
        this.threadPool2.shutdown();
        System.out.println("Server Stopped.");
    }

    private synchronized boolean isStopped(){
        return this.isStopped;
    }

    public synchronized void stop() {
        this.isStopped = true;
        try {
            this.serverSocket.close();
        } catch (IOException e) {
            throw new RuntimeException("Error closing server", e);
        }

    }

}

But the problem is that I cannot get my server in ON state.
I mean once I press run I get the following error:

java.net.SocketException: Socket is not bound yet
      at java.net.ServerSocket.accept(Unknown Source)
      at servers.ServerThread.run(ServerThread.java:60)
      at java.lang.Thread.run(Unknown Source)
  java.net.BindException: Address already in use: JVM_Bind
      at java.net.PlainSocketImpl.socketBind(Native Method)
      at java.net.PlainSocketImpl.bind(Unknown Source)
      at java.net.ServerSocket.bind(Unknown Source)
      at java.net.ServerSocket.bind(Unknown Source)
      at servers.ServerThread.run(ServerThread.java:44)
      at java.lang.Thread.run(Unknown Source)

Even if I shutdown my whole app and run it again still the same error....has anyone any idea why?Thank u!
Comment: This is really painful to read unindented code. Please format it.
Comment: Did you try a different port?
Comment: @Talha you can (and should!) edit the question.
Comment: I believe my code is correct formatted!
Comment: For small code I do love to indent, but its really a big code. Anyway I guess the question has been answered.
Answer: Some other program is already using port 6500.  Check that you're not running another instance of your program.
Try running
netstat -lp

to see what processes are using which ports.  Make sure the port on which you wish to listen is not listed in the output from netstat.
Answer: In the run() method, when you are creating a ServerSocket and assigning it to serverSocket variable:

serverSocket = new ServerSocket();

Please give a port number in the ServerSocket constructor, like 5000

serverSocket = new ServerSocket(5000);

error from a server in java


Amazon EC2 inbound filter for private IP

Question: I have two ec2 instances created in Amazon cloud, one with public IP(Elastic IP), and another with only private IP 172.31.5.151.
Then, set security group to the instance with public IP to limit https inbound access like
172.31.5.151/32, allowing only private IP to the instance with public IP.
But it doesn't work. Access denied when https access from instance with private IP to instance with public IP.
When I chanage the https inbound filter to 0.0.0.0/0, then everything works fine.
The question is: how to set inbound filter for a private IP?
Thanks.
Comment: I assume you are using VPC instances. Is the same security group associated with both instances?
Answer: For information, if you are using VPC, you need to make the difference between security groups and Network ACLs

consider the security group as your "instance firewall" (hence you can disable your instance software firewall such as internal iptables or Windows firewall)
NACLs define the allowed/denied traffic within your subnet (http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html)

Can you describe more precisely what you are trying to achieve with these 2 instances ?
Comment: Thank you. In my case NACLs are not used. Only security group is used for access control. Now I have an instance with public IP, say 188.8.131.52, and an instace with private IP, say 172.31.5.151. I want to limit the https access to public IP. That is only 172.31.5.151 is allowed to connect to 188.8.131.52 in https. So, I add inbound rule 172.31.5.151/32 to the security group. It seems reasonable but doesn't work. Don't know why.
Comment: Thank you for the update David,
I am pretty sure that your solution won't work as you are trying to communicate from instance with the private IP to hit your other Public IP instance. The security group won't recognize the private IP if you are not part of a VPC, hence the NACLs...
The best workaround you would use is assign a public IP to your "private instance" and allow this public IP in your sec group.

Let's have an example :
"Public" instance = inst A
"Private" instance = inst B

assign a public IP to inst B = B.B.B.B
allow the B.B.B.B/32 ip to your inst A secgr
allow SSH or RDP
Answer: If you can access (any) public IP from your "private" instance, it is either using NAT instance or has public IP assigned (by default if launched in default public subnet). In any case, when you try to hit your "public" instance, source IP (from the security group's point of view) is not your instance's private address, so you will need to grant access based on the public IP address.
(To confirm this, add 0.0.0.0/0 to filter, connect to https, then check netstat or IIS logs for source IP address)
Perhaps simpler solution would be to access "public" instance using its private ip address.
Comment: Thank you. I forgot there is a NAT between these two instances. Great help.


CGAL 3D surface mesh generation setting initial points

Question: I use CGAL for meshing an implicit surface and up to now this example is close to what I want to accomplish.
However,the implicit surface consists of several connected components among which one may not be detected.
For example, if the number of initial points is set to 800
  // meshing surface
  CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Manifold_with_boundary_tag(),800);

it is possible to find the concrete components.
However, I would rather provide explicit start points, which are easy to find by my program. Unfortunately I do not understand how to accomplish this with CGAL.
From the documentation I found that this method may help
SurfaceMeshTraits_3::Construct_initial_points()
I can not figure out, how to integrate this.
Could someone, who is "in the know" with CGAL template programming give me a rough sketch how to proceed - maybe just the template<...>class XXX public: YYY {
 Construct_initial_points ... } as would be used in the example code above?
Comment: Same problem, but even increasing the initial number of points fails to detect the missing component (my implicit surface is the union of two shapes, each homeomorphic to a torus, they are not small and my bounding sphere is correct)
PS: Hi from 7 years later
Answer: If I have understood correctly , you actually want to construct a surface from a point set. There is a tutorial just for that.
To help a bit:
CGAL::make_surface_mesh(c2t3,                                 // reconstructed mesh
                        surface,                              // implicit surface
                        criteria,                             // meshing criteria
                        CGAL::Manifold_with_boundary_tag());  // require manifold mesh

the code above shows what you have to provide in order to build the surface. Your result is stored in c2t3 , and you can generate the implicit surface from a set of points as shown in the example by using a poisson function:
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Poisson_reconstruction_function<Kernel> Poisson_reconstruction_function;
Poisson_reconstruction_function function(points.begin(), points.end(),
        CGAL::make_normal_of_point_with_normal_pmap(PointList::value_type()) );

There are two ways to proceed:

include the initial points in the pointset generated from your implicit function and define a poisson reconstruction function on that.

provide that SurfaceMeshTraits_3 traits class model that you can the pass onwards.

In principle two is difficult , and you have to either redefine it from start, modify an existing one, or derive from a current and implement :
construct_initial_points_object()

Tip: concepts in CGAL are abstract classes, models are the concrete implementations.
Once done there you can use
CGAL::Surface_mesh_complex_2_in_triangulation_3< YOUR_NEW_TRAITS >

to use it.
In order to achieve custom reconstruction ( e.g. without
Comment: No, I do *not* want to construct from a point set, but from an explicitly computable implicit function - as described in the example that I gave. The only problem is, that the zero set of this function in the bounding sphere consists of several components, some of which are not found in the default arrangement of things. It would be sufficient just to supply one point on each component before calling make_surface_mesh(..) and this should and can be done somehow with SurfaceMeshTraits_3::Construct_initial_points().
Comment: @JürgenBöhm so why don't you replace the poison reconstruction function with your own?
Comment: The reconstruction package from point sets computes an implicit reconstruction function and meshes then with marching cubes (so says the documentation). The 3D Surface mesh package takes an implicit function and meshes with another (not marching cube) method, based on Delaunay triangulations. I presume from general considerations that the latter meshing method is superior for my application in terms of speed and accuracy. In fact the results of this Delaunay-meshing look quite good, and if the problem of the components not found can be solved, it would fully suit my needs.
Comment: I must correct the statement above: The point set reconstruction package uses for meshing the same 3D Surface mesh package that is used in my initial example (I was misled by the statement of "marching cubes"). Nevertheless, after fixing by hand the poisson reconstruction function, I would be just in the situation where my question starts.
Comment: @JürgenBöhm , so actually you want to provide the start points for the solving the implicit surface onto the mesh generated from your point set . Is that correct?
Comment: I just want to accomplish what is done in the initial example that I gave: I have an implicit equation that I can compute concrete values of and I want CGAL deliver a mesh in the form of a C2t3 object. This works already quite well, up to the problem of some components not found, which could be solved immediately if one could hand over at least one initial/seed point on each component to CGAL. This is done by SurfaceMeshTraits_3::Construct_initial_points(), the point is that I just do not know to define the necessary classes and templates to integrate that into the example from which I started
Comment: @JürgenBöhm , This answer suggests that you generate a pointset by sampling your generator , include the so called start_points and pass the to the implicit function. However, you want to actually provide the reconstruction function. SurfaceMeshTraits_3 is a concept , you have to define it yourself, you could possibly do that with inheritance and overloading the initial points constructor. It is cumbersome to work with exact points though.


How can I calculate even intervals within a timestamp?

Question: I know this is some simple thing, and I used to know it, but I just can't recall it.
I'm writing an application that takes screenshots of videos in a user's library. If a video is 35 minutes long, I want to take five screenshots, which are evenly spaced from each other and from the beginning and end.
My best guess so far is to say that interval = length / (num_screenshots + 2), where length is the video's total length as a number of seconds. Then I take a screenshot at 0 + (interval * 1), 0 + (interval * 2), etc up to 5.
But is that the correct/simplest way to calculate this? It feels like there's some obvious thing I'm missing.
Answer: For n evenly spaced screenshots, there are n + 1 total intervals, so the formula for each interval should be interval = length / (num_screenshots + 1).  The first mark will be at (interval * 1), the second at (interval * 2), and ending in (interval * n).  I don't see a much simpler way to due this, it seems quite simple to me.
Interval Visualization


Examining trends with interactions and with stratification - obtaining discordant results

Question: I'm examining the effect of income (categorized into quintiles) on a response variable during different years (from 2003 to 2014). I adjust for some other covariates and have repeated measurements on the same individual.
The problem: To obtain the effect of income on the response variable each year, I include an interaction term between year and income quintile. This gives me implausible results, since those who are rich tend to have higher adjusted values, which is unlikely. So I redid the analysis, fitting one separate regression model each year, and that gave me plausible results; i.e the rich had lower adjusted values.
Shouldn't the two methods yield somewhat similar results?
My calculations:
    > # START
    >
    > # Converting the year variable into a factor
    > data$year <- as.factor(data$year)
    >
    > # Fitting a model with random effects for person
> require(lme4)
> fit  <- lmer(response ~ income*year + sex + age + education + biomarker + (1 | id), data=data)
> # Using lsmeans to predict means (95% confidence intervals)
> require(lsmeans)
> results1 <- lsmeans(fit, ~ income*year)
> summary(results1)
 income     year   lsmean        SE       df lower.CL upper.CL
 Quintile 1 2003 64.95472 0.2826723 190216.2 64.40069 65.50875
 Quintile 2 2003 65.49504 0.2716893 189962.8 64.96254 66.02755
 Quintile 3 2003 65.39961 0.2713204 189648.3 64.86782 65.93139
 Quintile 4 2003 65.51872 0.2715941 189734.3 64.98640 66.05103
 Quintile 5 2003 65.47502 0.2744592 190425.5 64.93709 66.01296
 Quintile 1 2004 64.03440 0.2541402 191982.7 63.53630 64.53251
 Quintile 2 2004 65.04364 0.2472738 191720.0 64.55899 65.52829
 Quintile 3 2004 64.98069 0.2425866 191644.4 64.50523 65.45616
 Quintile 4 2004 65.14219 0.2459067 191477.1 64.66022 65.62416
 Quintile 5 2004 65.25515 0.2496510 191947.6 64.76584 65.74446
 Quintile 1 2005 63.62453 0.2345767 192988.5 63.16476 64.08429
 Quintile 2 2005 64.18179 0.2294655 192853.2 63.73205 64.63154
 Quintile 3 2005 64.00250 0.2308264 192458.4 63.55008 64.45491
 Quintile 4 2005 63.79620 0.2276547 192775.7 63.35000 64.24240
 Quintile 5 2005 64.70116 0.2344171 193212.2 64.24171 65.16062
 Quintile 1 2006 64.17463 0.2228096 193482.8 63.73793 64.61134
 Quintile 2 2006 64.37025 0.2158588 193425.3 63.94717 64.79333
 Quintile 3 2006 64.30762 0.2141169 193366.8 63.88795 64.72728
 Quintile 4 2006 64.38315 0.2168376 193329.6 63.95815 64.80814
 Quintile 5 2006 64.22019 0.2198772 193526.5 63.78923 64.65114
 Quintile 1 2007 63.84188 0.2185725 193602.5 63.41349 64.27028
 Quintile 2 2007 63.92346 0.2104634 193527.6 63.51096 64.33597
 Quintile 3 2007 63.67954 0.2094212 193511.7 63.26908 64.09000
 Quintile 4 2007 64.08718 0.2103912 193478.5 63.67482 64.49955
 Quintile 5 2007 64.03627 0.2113704 193649.9 63.62199 64.45055
 Quintile 1 2008 64.65587 0.2043770 193372.1 64.25529 65.05644
 Quintile 2 2008 64.30141 0.1957655 193499.2 63.91772 64.68511
 Quintile 3 2008 65.04454 0.1955247 193589.4 64.66131 65.42776
 Quintile 4 2008 64.94073 0.1947715 193488.8 64.55898 65.32247
 Quintile 5 2008 65.00096 0.1979129 193119.2 64.61305 65.38886
 Quintile 1 2009 64.74611 0.1941592 191979.5 64.36556 65.12666
 Quintile 2 2009 64.68663 0.1872505 192801.9 64.31962 65.05363
 Quintile 3 2009 64.89048 0.1858611 192919.0 64.52620 65.25476
 Quintile 4 2009 65.19469 0.1848586 192734.9 64.83238 65.55701
 Quintile 5 2009 65.18344 0.1896058 192025.8 64.81182 65.55506
 Quintile 1 2010 64.99407 0.1863001 188874.1 64.62893 65.35922
 Quintile 2 2010 65.14159 0.1758624 190272.3 64.79691 65.48628
 Quintile 3 2010 65.21003 0.1740553 190655.7 64.86889 65.55118
 Quintile 4 2010 65.65492 0.1731845 190157.8 65.31548 65.99435
 Quintile 5 2010 65.42802 0.1774762 189156.3 65.08017 65.77587
 Quintile 1 2011 65.77711 0.1807193 179035.8 65.42290 66.13131
 Quintile 2 2011 65.81373 0.1719076 186787.1 65.47679 66.15066
 Quintile 3 2011 66.25649 0.1692650 187174.9 65.92473 66.58824
 Quintile 4 2011 66.24046 0.1672252 185968.9 65.91271 66.56822
 Quintile 5 2011 66.31895 0.1717513 184631.5 65.98232 66.65558
 Quintile 1 2012 66.45412 0.1815487 178604.9 66.09829 66.80995
 Quintile 2 2012 66.39743 0.1691640 185466.1 66.06587 66.72899
 Quintile 3 2012 66.61760 0.1674829 185934.4 66.28934 66.94586
 Quintile 4 2012 66.69909 0.1672601 185774.9 66.37126 67.02692
 Quintile 5 2012 66.74211 0.1697808 183081.3 66.40934 67.07487
 Quintile 1 2013 66.20088 0.1804738 177511.5 65.84716 66.55461
 Quintile 2 2013 66.05285 0.1710873 185354.9 65.71752 66.38817
 Quintile 3 2013 65.57061 0.1667456 185103.9 65.24379 65.89742
 Quintile 4 2013 65.96563 0.1669031 184335.3 65.63851 66.29276
 Quintile 5 2013 66.19121 0.1723801 183746.1 65.85335 66.52907
 Quintile 1 2014 65.37137 0.3060358 191891.8 64.77155 65.97120
 Quintile 2 2014 66.37503 0.2882805 188873.8 65.81001 66.94006
 Quintile 3 2014 65.49851 0.2876551 188265.5 64.93471 66.06231
 Quintile 4 2014 66.08503 0.2867954 188729.4 65.52291 66.64714
 Quintile 5 2014 65.98435 0.2901786 189169.5 65.41561 66.55309

Results are averaged over the levels of: sex, education
Confidence level used: 0.95
> # As you can see above, the richest (quintile 5) has higher values of a harmful biomarker, this is not likelybiomarker, this is not likely
    >
    > # Redo the analysis by stratification, i.e one regression each year (I'll give 4 examples, years 2005, 2008, 2010 and 2014)
    > fit2005  <- lmer(response ~ income + sex + age + education + biomarker + (1 | id), data=data[data$year=="2005",])
        > fit2008  <- lmer(response ~ income + sex + age + education + biomarker + (1 | id), data=data[data$year=="2008",])
    > fit2010  <- lmer(response ~ income + sex + age + education + biomarker + (1 | id), data=data[data$year=="2010",])
        > fit2014  <- lmer(response ~ income + sex + age + education + biomarker + (1 | id), data=data[data$year=="2014",])
    >
    > lsmeans(fit2005, "income")
     income       lsmean        SE      df lower.CL upper.CL
     Quintile 1 64.57677 0.3644627 7104.87 63.86232 65.29123
     Quintile 2 63.65426 0.3715929 7114.04 62.92582 64.38269
     Quintile 3 63.97948 0.3773103 7119.28 63.23984 64.71912
     Quintile 4 63.46368 0.3727073 7117.62 62.73306 64.19429
     Quintile 5 63.57556 0.3853513 7117.67 62.82016 64.33096

    Results are averaged over the levels of: sex, education
    Confidence level used: 0.95
    > lsmeans(fit2008, "income")
     income       lsmean        SE      df lower.CL upper.CL
     Quintile 1 64.27986 0.3268165 9880.81 63.63924 64.92049
     Quintile 2 65.07827 0.3288624 9866.53 64.43363 65.72291
     Quintile 3 64.98781 0.3265577 9859.02 64.34769 65.62793
     Quintile 4 64.89630 0.3305190 9868.49 64.24842 65.54419
     Quintile 5 63.66509 0.3428045 9898.35 62.99313 64.33706

    Results are averaged over the levels of: sex, education
    Confidence level used: 0.95
    > lsmeans(fit2010, "income")
     income       lsmean        SE       df lower.CL upper.CL
     Quintile 1 65.39530 0.2961521 11897.22 64.81480 65.97581
     Quintile 2 65.61791 0.2911321 11892.26 65.04724 66.18858
     Quintile 3 65.48423 0.2947050 11892.60 64.90656 66.06190
     Quintile 4 65.14303 0.2914349 11925.62 64.57177 65.71429
     Quintile 5 63.89145 0.3030998 11935.15 63.29733 64.48558

    Results are averaged over the levels of: sex, education
    Confidence level used: 0.95
    > lsmeans(fit2014, "income")
     income       lsmean        SE      df lower.CL upper.CL
     Quintile 1 67.05015 0.4888236 4523.42 66.09182 68.00849
     Quintile 2 65.41100 0.4801968 4523.32 64.46958 66.35242
     Quintile 3 65.35658 0.4740396 4525.63 64.42723 66.28592
     Quintile 4 65.03556 0.4793119 4526.56 64.09587 65.97524
     Quintile 5 64.94690 0.5001898 4529.88 63.96628 65.92751

    Results are averaged over the levels of: sex, education
    Confidence level used: 0.95

I must have misunderstood something (important) here...
Any advice?
Comment: I think this is kind of a Simpson's paradox situation. When you fit separate models by year, you are allowing different effects of all the predictors for each year. In essence, this is including interactions between year and the other predictors, compared to your combined model that assumes those predictors' effects are the same each year. If you include the interactions, you'll get comparable estimates (but not comparable standard errors because a combined error term is used)
Comment: Thanks for guidance. When You write "If you include the interactions, you'll get comparable estimates", which interactions are You referring to? Include more interactions? Specific interactions?
Comment: All the interactions between year and the other predictors in the model.
Comment: I had intended to look at the data, but you removed the link. Can you add that back in?
Comment: Sorry. Uploaded again. A thousand thanks for taking time on this. I did try your advice, but with little success unfortunately.
Comment: I cannot reproduce your results. The `id` variable is missing, and guessing it was `interaction(education, age, sex)` didn't give me the same results.
Comment: https://www.dropbox.com/s/qdmb517400ii8nn/data2.csv?dl=0
Comment: link above = new data file (new sample, actually). I'll try your interaction as well.
Comment: Meanwhile, I answered using `lm` instead of `lmer`. You can verify what I'm saying with your mixed-model analysis.
Comment: Your MODEL does not include the interaction between income and year - just the lsmeans call. Refit the model and do the lsmeans again and I think you'll likely see a different pattern.
Comment: Thanks for taking time to comment. I can see now that the model described above did not include the interaction, but I assure you that the original call on my computer does, so I updated the post above now to include the interaction and new results - problem persists. I have uploaded sample data now. I think the issue is my lsmeans call in the model that has the interaction, because I only use the interaction in the lsmeans call...
Answer: I didn't have the id variable at the time of preparing this answer so I do not reproduce your results. But the explanation can be made using lm fits on these data.
First, your model without the id grouping. I'll show the model, LS means, and comparisons with the lowest income quintile for just 2005:
> data$year = factor(data$year)
> fit.lm  <- lm(response ~ income*year + sex + age + education + biomarker,
    data=data)
> lsmeans(fit.lm, trt.vs.ctrl1 ~ income, at = list(year = "2005"))

$lsmeans
 income       lsmean        SE    df lower.CL upper.CL
 Quintile 1 64.20122 1.0008221 19262 62.23952 66.16292
 Quintile 2 64.45945 1.0060940 19262 62.48742 66.43148
 Quintile 3 64.37015 0.9685111 19262 62.47178 66.26851
 Quintile 4 63.88540 0.9971111 19262 61.93098 65.83983
 Quintile 5 63.36031 1.0319215 19262 61.33765 65.38297

$contrasts
 contrast                  estimate       SE    df t.ratio p.value
 Quintile 2 - Quintile 1  0.2582246 1.417633 19262   0.182  0.9937
 Quintile 3 - Quintile 1  0.1689240 1.390806 19262   0.121  0.9976
 Quintile 4 - Quintile 1 -0.3158223 1.411699 19262  -0.224  0.9898
 Quintile 5 - Quintile 1 -0.8409129 1.437786 19262  -0.585  0.9013

(Note: I edited-out some annotations in the output.) Now here are the same results, using a model fitted to only the 2005 data:
> fit.lm2005  <- lm(response ~ income + sex + age + education + biomarker,
    data=data, subset = (year=="2005"))
> lsmeans(fit.lm2005, trt.vs.ctrl1 ~ income)

$lsmeans
 income       lsmean        SE  df lower.CL upper.CL
 Quintile 1 64.37016 0.9884950 998 62.43039 66.30993
 Quintile 2 64.31077 1.0036776 998 62.34121 66.28033
 Quintile 3 64.35983 0.9747897 998 62.44696 66.27270
 Quintile 4 64.05203 1.0154760 998 62.05932 66.04474
 Quintile 5 63.43306 1.0753143 998 61.32292 65.54320

$contrasts
 contrast                   estimate       SE  df t.ratio p.value
 Quintile 2 - Quintile 1 -0.05939015 1.385639 998  -0.043  0.9998
 Quintile 3 - Quintile 1 -0.01033274 1.357894 998  -0.008  1.0000
 Quintile 4 - Quintile 1 -0.31813180 1.400778 998  -0.227  0.9894
 Quintile 5 - Quintile 1 -0.93710083 1.465919 998  -0.639  0.8790

Now, consider changing the overall model so that income interacts with every other predictor:
> fit.lmint  <- lm(response ~ year*(income + sex + age + education + biomarker),
    data=data)
> lsmeans(fit.lmint, trt.vs.ctrl1 ~ income, at = list(year = "2005"))

$lsmeans
 income       lsmean       SE    df lower.CL upper.CL
 Quintile 1 64.33859 1.027770 19172 62.32408 66.35311
 Quintile 2 64.27920 1.034344 19172 62.25180 66.30661
 Quintile 3 64.32826 1.007009 19172 62.35444 66.30209
 Quintile 4 64.02046 1.047664 19172 61.96695 66.07398
 Quintile 5 63.40149 1.106308 19172 61.23303 65.56996

$contrasts
 contrast                   estimate       SE    df t.ratio p.value
 Quintile 2 - Quintile 1 -0.05939015 1.432060 19172  -0.041  0.9998
 Quintile 3 - Quintile 1 -0.01033274 1.403386 19172  -0.007  1.0000
 Quintile 4 - Quintile 1 -0.31813180 1.447706 19172  -0.220  0.9902
 Quintile 5 - Quintile 1 -0.93710083 1.515029 19172  -0.619  0.8878

The LS means are slightly different from the ones for fit.lm2005, but the comparisons are identical. The only reason the LS means are shifted is because different reference values are used for age and biomarker. In the code below, I show that we do get the same results (except fro sliht errors due to rounding) from fit.lmint if we use the same reference levels:
> ref.grid(fit.lm2005)
'ref.grid' object with variables:
    income = Quintile 1, Quintile 2, Quintile 3, Quintile 4, Quintile 5
    sex = Female, Male
    age = 41.511
    education = <10 years education, 10 to 12 years education, College/University
    biomarker = 26.133

> lsmeans(fit.lmint, ~ income, at = list(year = "2005",
    age = 41.511, biomarker = 26.133))
NOTE: Results may be misleading due to involvement in interactions
 income       lsmean       SE    df lower.CL upper.CL
 Quintile 1 64.37009 1.021611 19172 62.36765 66.37254
 Quintile 2 64.31070 1.037303 19172 62.27750 66.34391
 Quintile 3 64.35976 1.007447 19172 62.38508 66.33445
 Quintile 4 64.05196 1.049493 19172 61.99486 66.10906
 Quintile 5 63.43299 1.111337 19172 61.25468 65.61131

Take-home message: When you fit models separately by some factor, the fits will differ from those for a combined model, unless the combined model includes all interactions with the factor you used for the separate fits.
Also, please note that lsmeans only summarizes model results. If you use a spec like ~A*B in the lsmeans call, that does not add an A:B interaction to the model, if that interaction was not present.
Additional note added later:
With a mixed model, if the id variable is crossed with year, then you probably will not get identical results by just including the fixed-effects interactions. this is because you'd be estimating different id effects in each year too. You'd have to make the random part (1|id/year).
Comment: Thats a beautiful way of explaining this. Appreciate your efforts.
Comment: Just a small note:
lsmeans(fit.lmint, trt.vs.ctrl1 ~ income, at = list(year = "1996")) **and**
lsmeans(fit.lmint, trt.vs.ctrl1 ~ income, at = list(year = "2005"))

Yields the same estimates, as does any other year...
Comment: I tested this and I do *not* get identical results with these commands for each year. In fact, I didn't need to test it because the whole point is that one can reproduce the results for a given year separately fitted using `fit.lsmint`. You must have made an error. BTW, unrelated to this, I did add a comment about mixed models at the end of the answer.


Why do I get office updates for server 2012R2

Question: I was looking at updates for a Windows Server 2012R2 and noticed a bunch of office 2010 important updates. We don't have any office version on this server so wondering why these are here? Any insight is appreciated, Thanks!
Comment: Tim is right that any Office component can cause this. On the server in question, go to the control panel and open up the "Add/Remove Programs" tool and look for anything with the word "Office" in it.
Comment: please be sure what your doing.  Be able to restore if after your remove something , some service your offering doesnt work  But it definitely more secure, to remove anything to do with Microsoft office, and any components, services that you are not using
Answer: Office updates don't necessarily mean a full copy of office is installed. It can just be certain components (access database connectors, deployment tools, etc) related to office.  You'll probably find a common thread if you look closer.


Site Redirect, really odd

Question: I just set up Invision Powerboard on my server (Ubuntu 10.10).  We have the name server pointing to my IP via dns record (outside that hosting).
When you access the url in Safari, everything works. Using any other browser, it will redirect you after login to domain.com/domain.com/...
This seems really weird.
Details removed to protect security/privacy.
Using no .htaccess rewrite
The one generated by IPB, if I chose to enable it would be this:
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteBase .nflspot.com/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . .nflspot.com/index.php [L]
</IfModule>

However, this gives me a 500 error.
I'll jump for joy if this gets answered!
Comment: Well ... under closer inspection -- browser requests wrong URL in first place: Firefox `GET /admin.nflspot.com/public/style_css/css_1/ipb_print.css HTTP/1.1`; Safari `GET http:/admin.nflspot.com/public/min/index.php?f=admin/skin_cp/acp.css,admin/skin_cp/acp_content.css,admin/skin_cp/acp_editor.css` -- notice only one slash in protocol part. Safari musb be handling it better than other browsers...
Comment: Show us your rewrite rules -- most likely problem is there. For example this question: http://stackoverflow.com/questions/6452464/htaccess-rewrite-problem-in-ie -- he got working in ALL browsers except IE.
Comment: IE sucks...see my edit. :)
Answer: Looking at your login page, I think you are missing a slash (http:/ rather than http://) after the protocol in your form action. When I send the POST, it gets sent to admin.nflspot.com/admin.nflspot.com.... which 404s.
<form action='http:/admin.nflspot.com/admin/index.php?adsess=&app=core&module=login&do=login-complete' method='post'>

Comment: Fixed it in the conf file.  Simple, stupid mistake. Thanks for finding the answer that shoulda been obvious to me! :)
Comment: Apologies. Looks like LazyOne found the same thing as I was typing up my answer.
Comment: FYI, I'm jumping for joy.

Site Redirect, really odd


Prevent class A from creating an instance of class B

Question: Motivation
Say I have a class Logger that is used by numerous classes/projects to handle log messages.
Now, I'm implementing a new class MyProcessor that cannot use class Logger as is. It needs to internally change some Logger members for Logger to work as expected.
My approach
I generate a new class MyLogger that extends class Logger and add specific code in all the right places.
Now, class MyProcessor can create instances of class MyLogger and enjoy the right functionality
Problem
A new member joined my team and needs to add code to class MyProcessor. He is not aware of the restriction that class Logger cannot be used directly in class MyProcessor
Solution
Let's prevent that on compile time: Make sure class MyProcessor is never creating instances of class Logger.
Notes
I know there are other approaches that will workaround my issue (such as, making Logger an abstract class and each derived class implement a set of virtual functions).
However, I'm more interested in resolving this issue specifically rather than different approaches.
Comment: In your solution most likely you are going to violate Liskov substitution principle
Comment: @KarstenKoop `#define Logger do not use class Logger in the file` might be a *slightly* more elegant version of this.  However there are two nice, clean, solutions:  1.  Fix `Logger` so it can be used from `MyProcessor`.  2. Code reviews.
Comment: You could put `#define Logger asdf` at the beginning of MyProcessor.cpp, thus intentionally breaking compilation if `class Logger` was used. But this would hardly be a nice, clean solution. Personally I don't think there is one, and there probably shouldn't be.
Comment: I think an even easier approach is to do `#define Logger MyLogger` in `MyProcessor`. That way, everyone can use `Logger` (provided they both provide a similar creation process) but now the internals are hidden from whoever is using it
Comment: There is no generic way to exclude some class from using  your Logger, you can only achieve the opposite by 'friending' some definite set of classes and making vital Loggers methods private or protected
Comment: @NarekAtayan agreed.
Comment: How about using `using Logger = MyLogger;` inside `MyProcessor`? This way you can use the type in the header as well AND restrict it to the class.
Comment: Another possibility might be to make the constructors of both loggers private and create a friend factory class that must be used for creation. Templates might help here.
Comment: What does it mean, that "`MyProcessor` cannot use `Logger`"? Is it ok, to call some function (maybe of another translation unit) that will work on a `Logger`? Is construction / deletion forbidden, or also usage of `Logger`?
Comment: @m8mble I mean that `MyProcessor` cannot use `Logger` as is since `Logger` will not work properly (unwanted behavior) for the use case of `MyProcessor`. `MyLogger` makes little adjustments in `Logger` for it to work as `MyProcessor` expects. I know it is a bit abstract but my real use case is much to complicated to be explained here. So the example here is a simple reduction of the problem.
Comment: @idanshmu What do you consider as usage? Method calls on `Logger`? `Logger` construction / deletion? Passing a `Logger` around (to some other function)? Please specify.
Comment: @m8mble In my case, using public member functions
Answer: class Logger {};

class MyProcessor
{
private:
    // If you get a compilation error using this, consult the lead.
    class Logger { Logger() = delete; };

public:
    void foo() { Logger nah; }
};

auto main() -> int { MyProcessor(); }

This is not "can't with some modest effort", but "can't inadvertently".


Elfen lied OP- Lilium, Transcribed by TehIsher

Question:
There are dash lines below notes on the second and third measures do they do anything?
Answer: That's an indication the note must be held for the full duration of the note, not any shorter. Kind of an anti-stattaco.


Apache Ignores SSLRequire Directive

Question: I have setup Apache to serve Subversion data. The configuration looks like this,
<Location /svn>
 DAV svn
 SVNPath /path/to/svn
 AuthType Basic
 AuthName "My Project"
 AuthUserFile /etc/httpd/dav_svn.passwd
 Require valid-user
 SSLRequireSSL
 <LimitExcept GET PROPFIND OPTIONS REPORT>
   Require valid-user
 </LimitExcept>
</Location>

This works as expected.
However, I want to relax the SSL requirement,so that connections from localhost don't require it. I replaced the SSLRequireSSL directive with a SSLRequire directive.
But Apache seems to be completely ignoring the SSLRequire directive.
Both,
SSLRequire true

and
SSLRequire false

result in the same behaviour! They both allow non-SSL connections.
What am I missing?
(Apache version : 2.2.11)
Answer: I think you need: SSLOptions +StrictRequire
Comment: Thanks, but it still doesn't work! Upvoting, because it definitely seems to be on the right track.

Apache Ignores SSLRequire Directive


Different definitions of the canonical form of simple functions (issue with constant reals different from $0$)

Question: A simple function $\varphi$ is a finite sum of the form
$$\varphi (x) := \sum^{N}_{k = 1} r_k \mathbf{1}_{E_{k}} (x)$$
where $E_k$ is measurable for every $k \in \{1, \dots , N\}$ and $\{r_k\}^{N}_{k=1} \subseteq \mathbb{R}$, with $\mathbf{1}$ being the indicator (or characteristic) function.
Stein & Shakarchi (at page 50 of their book) define the canonical form of $\varphi$ as the unique decomposition as above, where the real numbers $r_k$ are distinct and non-zero and the sets $E_k$ are disjoint (and measurable), for every $k \in \{1, \dots , N\}$. Then, with respect to the relation between the canonical form as they define it and the Lebesgue integral, show in their Proposition 1.1 at page 51 that the limitation of focusing on the canonical form as they define it is apparent.
On the contrary, for example, Royden & Fitzpatrick do not ask the real numbers $r_k$ to be non-zero, for every $k \in \{1, \dots , N\}$
Now, personally I find the definition in Royden & Fitzpatrick more natural. Thus, I was wondering why  there is the need to impose the constant real numbers to be different from $0$ in Stein & Shakarchi in the very first place.
Any feedback would be most welcome!
Answer: It seems to me that the first definition adds the restriction that $r_k$ are non-zero to make the decomposition unique. If, say, $r_{N+1}$ is allowed to be $0$, one could add it to the sum or discard it, without changing the function, thus making the decomposition not unique.
Comment: Thanks a lot for the answer. Actually, I thought something along these lines: as long as we are explicit (and of course we are) on the domain $D$ of $\varphi$, if there is a measurable set $E_{n+1} \subseteq D$ where $\varphi$ takes value $r_{n+1} = 0$, then we can **dismiss** it from the representation in the canonical form, because it does not change anything (as a sum). However, I also felt – maybe wrongly – that this was not really hampering the uniqueness of the representation. Hence, my question.
Comment: Once more, thanks a lot for the answer and let's see if other takes on the issue are going to come up!
Answer: I think that this restriction it for convenience: if you endow the ambient space with some infinite measure, you just have to say that all the $E_k$ must have finite measure for $\varphi$ to be integrable.
Comment: Thus, if $r_k=0$, the finiteness of the measure of $E_k$ is not required for $\varphi$ to be integrable.
Comment: Thanks for the answer. However, I do not really see how the idea of infinite measure is related to ruling out the possibility that there exists a measurable set where the function takes value $0$.
Comment: If one $r_k$ may vanish, the condition for integrability is less nice: $\varphi$ is integrable if and only if the $E_k$ have finite measure for all $k$ such that $r_k \ne 0$.
Comment: But why? You don't need the additional condition *"$r_K \neq 0$"*, because even if we have a $k$ such that $r_k = 0$, that still does not play any role in the integral (as it should be – the function takes value $0$ there).
Comment: Thanks for the clarification (sorry for being late).


Execute command when tree item is selected in VS Code

Question: My VS Code extension has a Tree View. When one of the children tree item is clicked by user it should execute a command (show info message). I can't find out how to catch the click event and make a command. This is a provider of Tree View:
const vscode = require('vscode');

class TreeviewProvider {
  constructor(data) {
    this.data = data;
  }

  getTreeItem(element) {
    return element;
  }

  getChildren(element) {
    if(element) {
      return Promise.resolve(this.getData(element.label));
    }
    else {
      return Promise.resolve(this.getData());
    }
  }

  getData(value) {
    if(value) {
      // Load children items
      // Should I pass the command id?
      const command = 'myExtension.debugMessage';
      const data = this.data[value].map(element => {
        return new Data(element.label, vscode.TreeItemCollapsibleState.None, command);
      });
      return data;
    }
    else {
      // Load root items
      // ...
    }
  }
}

class Data extends vscode.TreeItem {
  constructor(label, collapsibleState, command = undefined) {
    super(label, collapsibleState);
    if(command) {
      // It should be a command to execute
      this.command = command;
    }
  }
}

module.exports = TreeviewProvider;

And this is how I register a Tree View in activation function:
const vscode = require('vscode');
const TreeviewProvider = require('./components/TreeviewProvider');

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
    const debugMessage = vscode.commands.registerCommand('myExtension.debugMessage', function () {
        // This is a command to execute
        const date = new Date();
        vscode.window.showInformationMessage('Debug called at ' + date.toLocaleString());
    });

    const treeviewProvider = new TreeviewProvider(getSomeData());
    const treeviewView = vscode.window.registerTreeDataProvider('treeview-view', treeviewProvider);

    context.subscriptions.push(treeviewView);
}

// ...

Answer: I have just realized that the command property in the class extending TreeItem should be a Command object, like it said in the docs:
https://code.visualstudio.com/api/references/vscode-api#TreeItem
So, it can be done this way:
class Data extends vscode.TreeItem {
  constructor(label, collapsibleState, commandId) {
    super(label, collapsibleState);
    const command = {
      'command': commandId // commandId is a string that contains the registered id ('myExtension.debugMessage')
    };
    this.command = command;
  }
}


How do I avoid segmentation fault?

Question: The code is self-explanatory, but it gives me segmentation fault, why? :\
#include <stdio.h>
int main(void)
{
    char *c = "Hella";
    *(c+4) = 'o';
    printf("%s\n",c);
}

Comment: You forgot to use your compiler warnings or to pay attention to them or to understand them.
Comment: You might want to look at http://stackoverflow.com/questions/2245664/string-literals-in-c
Answer:
How to avoid it?

Don't modify a string literal!
char *c = "Hella";

Declares a pointer c to a string literal "Hella" stored in implementation defined read only memory.
You are not allowed to modify this literal. An attempt to do so results in Undefined Behavior.
You are lucky that your program crashes, an Undefined Behavior does not always result in a crash but may cause your program to behave weirdly in any possible way.
What you need here is an array:
char c[] = "Hella";

Good Read:
What is the difference between char a[] = ?string?; and char *p = ?string?;?
Answer: Put your string into an array allocated onto the stack:
char c[] = "Hella";

Because as said, string literals are usually read-only.
Answer: the way you create c it points to a string literal. You can not modify it's contents. If you want to be able to do that use:
char c[6] = "Hella";
c[4] = o;

Or use a dynamically allocated char array.
Answer: You are trying to overwrite a literal.  Really your code should read:
const char *c = "Hella";

Which kinda explains what is going on.
To overwrite your own memory:
char c[] = "Hella";

is safer.
Answer: You can not modify strings that are defined in code. Use strdup if you want to modify them.
#include <stdio.h>
int main(void)
{
    char *c = strdup("Hella");
    *(c+4) = 'o';
    printf("%s\n",c);
    free(c);
}

Comment: @Geoffrey. It is not correct to edit the sense of a post. You can edit only the form. Language, format etc. You can propose the change in a comment though.
Comment: Yes, the change was correct, but according to rules we should use edit for the form only, not the content! Geoffrey should propose the content change by the means of a comment.
Comment: Huh really sorry for that Gangnus this should never happen again, I'll carry it out. Thanks!

How do I avoid segmentation fault?


Windows 2003 Web Edition & Remote Desktop

Question: I'm tackling a project with 3-4 developers, and I want them to work all on the same machine through Remote Desktop. Thus I'm currently looking for an economically priced dedicated server that will fit my needs.
My question is, whether the Web Edition of Windows 2003 server allows multiple users concurrently to log into the machine through remote desktop to work with the applications installed there?
On Wikipedia i read that remote desktop is available in this edition for "administration purposes".
Answer: No. Terminal services has two modes, application and administration. Administration mode allows 2 users concurrently out of the box, application mode will require terminal services licensing. This goes for any edition of Windows Server.
Comment: Thank you! so the smallest version that supports multiple users will be the standard edition? if there are not more than 2 users concurrently, web edition will work also or are there further limitations regarding remote desktop work?
Answer: All editions of Window Server 2003/2008 (with the exception of web edition) work the same and have the same capabilities in regards to RDP sessions. You can have 2 RDP sessions when the server does not have the TS (RDS) role installed and you can have as many RDP sessions as you have TS (RDS) licenses when the TS (RDS) role is installed.
With web edition you only get 2 RDP sessions for remote administration.


Android wear data layer PutDataMapRequest doesn't work

Question: I'm trying to implement android wear application. I guess I don't understand something, because my test project acts strangely. It's a very simple project - activity with two buttons ("Send map" and "Send message") on a mobile device and WearableListenerService on wear device, which creates notification, when data is received.
Now when I try to send data through Wearable.DataApi nothing happens on wearable - data is sent, but nothing is happening on wearable (wearable is coupled with mobile this whole time). I tried waiting 10-15 minutes, but still nothing. But if I then send data via MessageApi, message is delivered instantly, and also all my data items sent via DataApi are received at that moment.
When I try google examples that use DataApi(DataLayer or Quiz), data items are seems to be delivered almost instantly, but almost all of them use DataApi along with MessageApi.
Also, if I launch one of those examples after sending data item, all my sent items are delivered also.
So I guess my question is: is it bug in my code, that causes data items not to be delivered? Or is it supposed to work like this and data items are just accumulated on device, and actual exchange is happening, like, every hour or so, and sending message is the only way to trigger immediate delivery?
Here's my data item send code:
String data = String.valueOf(System.currentTimeMillis());
PutDataMapRequest pdmr = PutDataMapRequest.create("/wear_test/"+data);
pdmr.getDataMap().putString("1", data);

PutDataRequest pdr = pdmr.asPutDataRequest();

Wearable.DataApi.putDataItem(googleApiClient,pdr);

Here's listener service code:
public class ListenerService extends WearableListenerService {
    private static final String TAG = ListenerService.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "Service created");
    }

    @Override
    public void onDataChanged(DataEventBuffer dataEvents) {
        super.onDataChanged(dataEvents);
        Log.e(TAG, "onDataChanged(DataEventBuffer dataEvents) is called");

        for (DataEvent dataEvent : dataEvents) {
            Log.e(TAG, "Event type: "+dataEvent.getType()+", Uri:'"+dataEvent.getDataItem().getUri());
            if(dataEvent.getType()==DataEvent.TYPE_CHANGED && dataEvent.getDataItem().getUri().getPath().contains("/wear_test")){
                DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();
                String data = dataMap.getString("1");
                Log.e(TAG, "Data received: " + data);

                createNotification(data,505, "data map");
            }
        }
    }

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        super.onMessageReceived(messageEvent);
        if (messageEvent.getPath().contains("wear_test")){
            String messageStr = new String(messageEvent.getData(), Charset.forName("UTF-8"));
            Log.e(TAG, "Message received:"+messageStr);
            createNotification(messageStr,808, "message");
        }
    }

    private void createNotification(String data, int notificationCode, String suffix){
        Notification notification = new Notification.Builder(this)
                .setTicker(data)
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_light)
                .setContentText(data+"\n"+suffix)
                .setSubText(data+"\n"+suffix)
                .build();

        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                .notify(notificationCode, notification);
    }
}

Comment: Can you please post the code where you connect to the DataApi on the wearable?
Comment: @TofferJ Added listener service code. I don't actually connect to DataApi on wearable, just create notification.
Answer: I had the same problem. I solved it using PutDataRequest.setUrgent().
From the documentation:

DataItems will be delayed no longer than 30 minutes, subject to a connected peer, but are expected to arrive much sooner.
  Clients should only setUrgent() for DataItems which need to be delivered right away.
Comment: Thanks! That helped a lot.


SQL. The intricate JOIN between two tables

Question: I have 2 tables:users and subscribers. The relationship of the user to the subscriber is a many-to-many.

I know how to get all users:
SELECT * FROM users

And I also know how to get subscribers to a given user by his id (for example id=1):
SELECT * FROM users LEFT JOIN subscribers ON id = user_id WHERE user_id = 1

But I need these results are not separately but together.
That is, I want to create a query to get all users.
But in addition to their properties, result of the query must contain a property that shows each user is subscriber or not.
Something like this:

And of course I would like to avoid the use of subqueries. It would be great to use only a JOINs.If this situation it is possible.
Thanks in advance!
Comment: How does the subscriber table map to a true/false value?
Comment: Is this MS Access? Might be helpful to tag as such if that is the case.
Answer: You can do:
SELECT u.*,
        CASE WHEN s.user_id IS NULL THEN 'false' ELSE 'true' END as IsSubscriber
FROM users u
   LEFT JOIN subscribers s ON u.id = s.user_id

...since s.user_id will be made null by the left join when the user is not in the subscribers table.
Comment: Thanks but here is the query which I needed: SELECT u.*, CASE WHEN s.user_id IS NULL THEN 'false' ELSE 'true' END AS isSubscriber
FROM users u
LEFT JOIN subscribers s ON id = subscriber_id and s.user_id=1
Answer: i updated your query to result what u want.
SELECT u.id, u.firstName, u.lastname, WHEN s.user_id IS NULL 'false' else 'true' END as IsSubscriber.
FROM users u
LEFT JOIN subscribers s
   ON u.id = s.user_id
WHERE user_id = 1

Answer: SELECT users.id, users.firstname, users.lastname, COUNT(subscribers.user_id) != 0 AS isSubscriber
  FROM users
  LEFT JOIN subscribers ON users.id = subscribers.user_id
  GROUP BY users.id, users.firstname, users.lastname


Google Analytics Module not working

Question: Configuring Google Analytics Module, I mistakenly kept the example code during the first 2 configurations of the module: UA-673320-6.
Then I finally out the correct code:UA-30183564-3.
From looking at my website's page source, it appears all 3 configurations are in the header as javascript snippets?
I am not sure how to get Google Analytics setup so that it is linked to my website?

Answer: I would like to offer an alternative. I  have always had issues with putting my analytics into the analytics module.  I have experienced what you have experienced, plus I question why this code has to go into a module? The fewer modules you have the faster your site performs.
I always get the code from Google and then hard code it into the theme files. In drupal 7, this would go into your html.tpl.php just before the  tag, just as google instructs.  That is called for every single page, so no pages will ever go without it. Plus, it makes your code lighter and one less module to worry about. It has always been the best solution for me.
note: if you are using d6 it would have to go into each page.tpl.php template or its derivative if you have more than that one.  Hope that helps.
Answer: Have you tried clearing your cache? If that doesn't work, uninstall the module and reinstall it, making sure that when you configure it you set the correct Google Analytics ID on the first go...
I've never experienced this, but you might have stumbled across a bug. Make sure you're using the most up to date version of the module.

Google Analytics Module not working


Why is the variance of a binomial distribution not $n^2p(1-p)$?

Question: Using properties of variance, we know that $Var(aX)$ is $a^2Var(X)$.
A binomial distribution has n many Bernoulli trials, i.e. we can substitute $Var(X)$ with $Var(nB)$ (where $X$ is a binomial variable and $B$ a Bernoulli trial) which, using the property described above, gives us $n^2Var(B)$.
But, this would give us a result of $n^2p(1-p)$ rather than $np(1-p)$ which is the supposed variance of a binomial distribution.
Where is the mathematical error in the approach I have taken?
Comment: Taking the sum of $n$ independent Bernoulli trials is not the same as performing a single Bernoulli trial and then multiplying the result by $n$ - the latter approach only has 2 possible outcomes, $0$ and $n$.
Comment: ...and $n^2 p(1-p)$ *is the correct variance* for that case.
Answer: It might be worth examining the binomial as a sum of $n$ i.i.d. bernoulli trials.  Let $X_i$ be i.i.d. bernoulli draws.  $Y = \sum_i X_i$ is then a binomial random variable.  The variance of this is
$$ \operatorname{Var}(Y) = \operatorname{Var}(\sum_i X_i) = \sum_i \operatorname{Var}(X_i) $$
Where I have used the property that the variances add iff the the covariance is 0 (which is true by assumption).  For a given Bernoulli random variable $\operatorname{Var}(X_i) = p(1-p)$.  Since all the $X_i$ are identical,
$$ \operatorname{Var}(Y) = \sum_i p(1-p) = n p (1-p) $$
Answer: The problem with your solution is at this step. $Var(X) = Var(nB)$
Because $X \neq nB$
I mean yes, $X = B_1 + B_2 + ... +B_n$ because all the $B_i$'s are $0$ or $1$, and X is the number of $1$'s in n trails. But you can't call it $nB$ because all $B$'s don't have the same value. Some of them are $0$ and some are $1$.
Your idea is only true if $B_1 = B_2 = ... = B_n = B$.
But if you really want to express binomial distribution in terms of Bernoulli's trails, you can do it like this.
$$X = B_1 + B_2 + ... +B_n$$
$$Var(X) = Var(\sum_{i=1}^n{B_i})$$
You can bring the summation out because by definition of binomial distribution, each trail is independent of the other trails. So it's like they are all independent.
$$Var(X) = \sum_{i=1}^n{Var(B_i)}$$
$$Var(X) = \sum_{i=1}^n{pq}$$
Now this you can write as $npq$ because all the $pq$'s regardless of $i$ have the same value $p(1-p)$.
$$Var(X) = npq$$


How to prevent comment posting when it has specific words in it?

Question: I´ve searched for all Drupal 7 modules that try to give some SPAM protection, but haven´t found what I need, maybe I´ve overlooked something?
I need to prevent anonymous comment posting when comment has specific -configurable- spammy words. How may I do that?
Comment: check this http://drupal.stackexchange.com/questions/56392/how-to-stop-spam-in-comments
Comment: Thanks! HoneyPot (http://drupal.org/project/honeypot) did the trick! I didn´t want to use Mollom because I don´t want to use third party stuff whenever I can.
It´s not exactly what I wanted, but it does the job. Thanks!
Answer: You can try Spam module.
It runs filters on posted content, for example using regexps.
Another way is to write a Rule that examines posted comments and deny them if certain words are found, but unfortunately this module is only available for Drupal 6.
And also you can write a validate function to the comment form, examine the content on submission and use form_set_error if you detect those words. To do this just implemente the hook_form_alter (or the hook form alter with form id), add your valditation function:
<code>$form['#validate'][] = 'you_custom_validate_function';
</code>
Comment: Thanks for your reply! I haven´t thought on using Rules!
Sadly, Spam module is D6 only.
Comment: Oops, I didn't check the Spam module availability. Editing.
Answer: I think you're looking for Mollom built by the same gentleman who created Drupal.

Mollom is an "intelligent" content moderation web service. By
  monitoring content activity on all sites in the Mollom network, Mollom
  is in a unique position to determine if a post is potentially spam;
  not only based on the posted content, but also on the past activity
  and reputation of the poster. In short, Mollom handles incoming posts
  intelligently, in much the same way a human moderator decides what
  posts are acceptable. Therefore, Mollom enables you to allow anonymous
  users to post comments and other content on your site.
Comment: Mollom does not have a configurable list of spammy words.
Answer: You can try word filter module

For example, you can set the filter to find the word "work" and when found, change it to "play". You may toggle whether the filter applies to node titles as well as the body

It also has filtering for comments.


Reformat json data using Jquery

Question: I need to convert the following JSON data:
var response = {
   "data":    {
      "List":       [
                  {
            "Name": "Mary",
            "state": "AZ",
            "Matriculation": "complete",
            "Graduation": "complete",
            "Masters": "complete",
            "Phd": "notStarted"
         },
                  {
            "Name": "Stephanie",
            "state": "CT",
            "Matriculation": "complete",
            "Graduation": "complete",
            "Masters": "complete",
            "Phd": "notStarted"
         },
         {
            "Name": "John",
            "state": "CT",
            "Matriculation": "complete",
            "Graduation": "planning",
            "Masters": "notStarted",
            "Phd": "notStarted"
         }]
   }
}

into the following using jQuery:
[
   {
   "state":"AZ",
      "Matriculation":[
         {
            "Name":"Mary",
            "status":"complete"
         }
      ],
      "Graduation":[
         {
            "Name":"Mary",
            "status":"complete"
         }
      ],
      "Masters":[
         {
            "Name":"Mary",
            "status":"complete"
         }
      ],
      "Phd":[
         {
            "Name":"Mary",
            "status":"notStarted"
        }
      ]
   },
   {
      "state":"CT",
      "Matriculation":[
         {
            "Name":"Stephanie",
            "status":"complete"
         },
         {
            "Name":"John",
            "status":"complete"
         }
      ],
      "Graduation":[
         {
            "Name":"Stephanie",
            "status":"complete"
         },
         {
            "Name":"John",
            "status":"planning"
         }
      ],
      "Masters":[
         {
            "Name":"Stephanie",
            "status":"complete"
         },
         {
            "Name":"John",
            "status":"notStarted"
         }
      ],
      "Phd":[
         {
            "Name":"Stephanie",
            "status":"notStarted"
         },
         {
            "Name":"John",
            "status":"notStarted"
         }
      ]
   }
]

This is what I have tried so far with zero progress.
I tried to accomplish this for one state first.
This is the fiddle:
http://jsfiddle.net/sqgdyk6f/
Any guidance is appreciated.
I am new to JSON manipulation.
Thanks in advance!
Comment: Is this your homework?
Comment: To be correct, this isn't JSON manipulation. You are manipulating JavaScript objects that might've originated from JSON. Remember JSON just means JavaScript Object Notation.
Answer: First thing you should do is analyze your source format, and your destination format.

Your source format is just an array of objects of individual people.
Your destination format is an object that groups the people by state
and into certain categories.

Next, think about how you can get the source into this destination.
You're going to want to iterate over each individual person in the source, and try to add it to your array of states. Now, I'll say your destination format is a bit peculiar, but by writing a couple of helper functions, you can achieve that format.
Take a look at your destination format again. It's an array of objects. Part of each object in that array is a property called state that has a value for the state that object represents. You're going to want a function that can look through this array for a specific state, and return the existing object for you. If the state doesn't exist, it should add a new entry to the array for you and return that.
Since JSON just means JavaScript Object Notation, and you are actually working with JavaScript objects, you should create an object that models each entry of your destination array. I'm going to call these StateSummary.
function StateSummary(state) {
    this.state = state;
    this.Matriculation = [];
    this.Graduation = [];
    this.Masters = [];
    this.Phd = [];
}

Can you see how this object represents each entry in your destination array?
Now that you have an object that models each entry, we need a function that can check to see if an entry for a certain state already exists. If it exists, it will return that object. If it doesn't exist, it will add a new object to the array, and return this new object.
function addOrGetState(array, state) {
    for (var i = 0; i < array.length; i++) {
        var obj = array[i];

        if (obj.state === state)
            return obj;
    }

    //If the function got here, then it didn't find a matching state.
    var obj = new StateSummary(state);
    array.push(obj); //Add the new object to the array.
    return obj; //Return the new object.
}

So, now you can get an entry by state from your destination array, and you can create new entries.
Go ahead and create a function that will add a person to a StateSummary object.
function addPersonToStateSummary(person, stateSummary) {
    stateSummary.Matriculation.push({ Name: person.Name, status: person.Matriculation });
    stateSummary.Graduation.push({ Name: person.Name, status: person.Graduation});
    stateSummary.Masters.push({ Name: person.Name, status: person.Masters});
    stateSummary.Phd.push({ Name: person.Name, status: person.Phd});
}

The last piece is iterating over the source array, and massaging that data into your destination array.
var sourceArray = response.data.List; //You provided this.
var destinationArray = []; //Allocate a new array to put stuff in.

for (var i = 0; i < sourceArray.length; i++) {
    var person = sourceArray[i]; //Each entry of the source array represents a person.

    var stateSummary = addOrGetState(destinationArray, person.state);

    addPersonToStateSummary(person, stateSummary);
}

This should give you what you are looking for. I hope this breakdown teaches you how to think about the problem in an analytical way, breaking its steps down first, and then solving them with code.
Here is a demo:

var response = {
  "data": {
    "List": [{
      "Name": "Mary",
      "state": "AZ",
      "Matriculation": "complete",
      "Graduation": "complete",
      "Masters": "complete",
      "Phd": "notStarted"
    }, {
      "Name": "Stephanie",
      "state": "CT",
      "Matriculation": "complete",
      "Graduation": "complete",
      "Masters": "complete",
      "Phd": "notStarted"
    }, {
      "Name": "John",
      "state": "CT",
      "Matriculation": "complete",
      "Graduation": "planning",
      "Masters": "notStarted",
      "Phd": "notStarted"
    }]
  }
};

function StateSummary(state) {
  this.state = state;
  this.Matriculation = [];
  this.Graduation = [];
  this.Masters = [];
  this.Phd = [];
}

function addOrGetState(array, state) {
  for (var i = 0; i < array.length; i++) {
    var obj = array[i];

    if (obj.state === state)
      return obj;
  }

  //If the function got here, then it didn't find a matching state.
  var obj = new StateSummary(state);
  array.push(obj); //Add the new object to the array.
  return obj; //Return the new object.
}

function addPersonToStateSummary(person, stateSummary) {
  stateSummary.Matriculation.push({
    Name: person.Name,
    status: person.Matriculation
  });
  stateSummary.Graduation.push({
    Name: person.Name,
    status: person.Graduation
  });
  stateSummary.Masters.push({
    Name: person.Name,
    status: person.Masters
  });
  stateSummary.Phd.push({
    Name: person.Name,
    status: person.Phd
  });
}

var sourceArray = response.data.List; //You provided this.
var destinationArray = []; //Allocate a new array to put stuff in.

for (var i = 0; i < sourceArray.length; i++) {
  var person = sourceArray[i]; //Each entry of the source array represents a person.

  var stateSummary = addOrGetState(destinationArray, person.state);

  addPersonToStateSummary(person, stateSummary);
}

document.getElementById('result').innerHTML = JSON.stringify(destinationArray);

Comment: I have been working with Javascript for quite some years now and I still do not know how to create a properly structured  and optimized code. When I start something, I try for a long time and get it working first and then I think of cleaning the code. Your explanation is very nice. Now I understand how good coders think while coding. Thanks for taking so much time to not just solve my issue but to make sure I understand it correctly!
Comment: @user1405855 glad it helped! Comments like this mean much more than up votes to me! I'll come back and add some jquery explanation once I get home.

Reformat json data using Jquery


Remover a: do xml gerado pelo meu web service

Question: Quando gero o XML em um web service rest, aparece assim:
<getCnpjParceiroResponse xmlns="http://tempuri.org/">
    <getCnpjParceiroResult
        xmlns:a="http://schemas.datacontract.org/2004/07/V99SuporteTecnicoContracts"
        xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        SAO VICENTE

        11951604000130

        PIRACICABA

        0
        0
        0001-01-01T00:00:00
        0001-01-01T00:00:00

        AV. CRISTOVAO COLOMBO

        0
        0
        0
        0
        false
        0
        0

        0
        CONVENIENCIA RADIAL NORTE SUL LTDA EPP

    </getCnpjParceiroResult>
</getCnpjParceiroResponse>

Comment: Agora vi @brasofilo. Desculpe. Eu usei uma ferramenta para endentar o código e ela introduziu uma declaração XML. Não tinha percebido. De qualquer forma isto não interfere no problema em questão.
Comment: Nota ao editor: @helderdarocha, não devemos *nunca* adicionar ou remover nada ao código original postado numa pergunta pois isso pode consertar o erro ou introduzir outros problemas. Acertar a indentação e remover linhas em branco é ok.
Comment: @brasofilo Não foi introduzido ou removido nada do código original. Ele foi apenas endentado. A única coisa acrescentada foi um tag, [tag:xml-namespaces], que é relevante para a questão.
Comment: O [original](http://pt.stackoverflow.com/revisions/16900/1) não tinha a tag de abertura ``. Se o arquivo está sendo gerado sem isso, é um outro problema...
Answer: se quiser um jeito prático e rápido,
use o método Replace da classe String ou StringBuilder (mais rápido):
string xml = new StringBuilder(xmlContent);
xml.Replace("<a:", "<");
xml.Replace("</:a", "</");
xmlContent = xml.ToString();

mas aconselho você a ler o xml por uma classe especializada XmlReader ou parecida, (explicação aqui: http://msdn.microsoft.com/en-us/library/vstudio/system.xml.xmlreader.read)
e apenas substituir os nomes para evitar problemas com o "corpo" do arquivo.
Comment: Se for fazer isto teria que também remover o sufixo da declaração `xmlns:a`, caso contrário os elementos perderão sua associação com o namespace e não poderão ser validados.
Answer: O prefixo a: antes desses elementos declara que eles pertencem a um namespace. Isto não faz parte do nome do elemento. Você não pode simplesmente removê-los sem fazer alterações em outras partes do arquivo ou seu documento poderá ficar inválido.
Se você realmente precisar remover os prefixos, você terá que alterar também a declaração xmlns:a que está em <getCnpjParceiroResult>. Essa declaração associa todos os elementos descendentes que têm prefixo a pertencem ao namespace "http://schemas.datacontract.org/2004/07/V99SuporteTecnicoContracts". Como não há elementos sem o prefixo a dentre os descendentes de <getCnpjParceiroResult>, você pode estabelecer esse namespace como o default, o que permite que elementos sejam declarados sem prefixo.
Portanto, para que seu documento continue válido e não tenha os prefixos a o namespace deve ser declarado usando xmlns (sem sufixo):
<getCnpjParceiroResponse xmlns="http://tempuri.org/">
    <getCnpjParceiroResult
        xmlns="http://schemas.datacontract.org/2004/07/V99SuporteTecnicoContracts"
        xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <Bairro>SAO VICENTE</Bairro>
        <CEP i:nil="true"/>
        <CNPJ>11951604000130</CNPJ>
        <CaminhoLogo/>
        <Celular i:nil="true"/>
        ...
        <Telefone i:nil="true"/>
        <TokenAuthentication i:nil="true"/>
    </getCnpjParceiroResult>
</getCnpjParceiroResponse>

Quanto à geração do XML, você precisa descobrir como configurar isto no software que o gera. Deve haver algum mapa ou registro onde você possa associar prefixos com namespaces, ou escolher preferências. De qualquer forma, não existe nenhuma diferença em termos funcionais para tags com prefixo ou sem, a menos que você esteja usando tecnologias que não suportem namespaces. Os dois XMLs, o seu com prefixo a, o que postei acima sem o prefixo, ou ainda um outro declarando um prefixo diferente (ex: <datacontract:cnpj>) serão equivalentes e igualmente válidos se a associação for para o mesmo namespace.
Comment: helderdarocha, bom dia. Eu tenho essa informação após o documento ser gerado. Há como antes da geração desse documento, eu fazer algo que impeça tag a? O problema que a empresa parceira que vai consumir esse web service, a programadora lá disse que essa tag aestá dando problemas. Poderia dizer que isso é problema dela e etc, mas gosto de aplanar os caminhos, então, se puder falitar do meu lado farei.
Comment: Eu não sei se é trivial com WCF. Eu encontrei [este artigo](http://vanacosmin.ro/Articles/Read/WCFEnvelopeNamespacePrefix). Se ficar muito complicado, você pode escrever um interceptador que arranque os prefixos `a:` e o sufixo do `xmlns:a` como foi proposto na outra resposta, já que não existe um namespace default previamente definido.
Answer: Resolvi assim:
BodyStyle = WebMessageBodyStyle.Bare
Antes estava assim:
BodyStyle = WebMessageBodyStyle.Wrapped


How to move the user account/Profile 2 information from the content region to a sidebar region

Question: On the "My Account" page i.e. /user, the account and Profile 2 information is by default residing in the content region. I would like to move everything to the right sidebar region. Any suggestions on how I can achieve this ?
I am using Bartik
Thanks in advance.
Answer: You can create a View (show Users) with display "block" and add User:ID as Context Filter. For the Context Filter set "When the filter value is NOT available" to "provide default value - User ID from URL". Add all user fields that you would like to output to your view. Created Views block will then be listed on you Blocks page (structure > blocks). Once the block is there, you can drag it into the sidebar region.
If you need to remove user profile fields that are rendering in content region by default or override them, you can do so by overriding "modules/user/user-profile.tpl.php" - copying it into your theme's template folder and replacing  the line that renders user profile - <?php print render($user_profile); ?> with the desired content.
Page Manager Existing Pages + Panels is another convenient method of changing the layout of user profile. This method will work in combination with existing layout regions.
Comment: I got up to contextual filter part, but after that I don't see any profile related fields in the "add fields" list. Any ideas?
Comment: edited the answer with more details -check it out
Comment: I only got the profile fields when I chose "show Profile", instead of "show Users". Is that how it is meant to be?
Comment: yes, If you created a view with contextual filter of User:ID it will only show fields for one user when the context filter is available - means, only when you are viewing single user profile.
Comment: I am now using "show Users" for the Views block. The User fields are showing fine, but the Profile fields are empty (I added the User: Profile relationship). I also made sure the profile fields were filled with values. How do I solve this?
Comment: make sure each profile2 field uses the corresponding User:Profile relationship in field settings
Comment: Turns out the Profile fields were empty because I left the profile types checkboxes unchecked on the User:Profile relationship config . page. Thanks for you help.


How the entropies of the random variables in conditional entropy affect its value?

Question: We know that the conditional entropy $H(Y|X)\to 0$ as $X$ determines the value of $Y$. Now, I have the intuition of that $H(Y|X)<H(Y|Z)$ if $H(X)<H(Z)$. With this, and from the first statement, I interpret that a random variable whose entropy is smaller ($X$) provides more knowledge on the variable ($Y$) than other variable whose entropy is larger ($Z$), assuming that $P(Y,X)\neq P(Y)P(X)$ and $P(Y,Z)\neq P(Y)P(Z)$. Is that correct? I'm not sure how to verify it, please help me.
As a preliminary research, I suspect that I need to analyze $P(Y,\cdot)/P(\cdot)$ in the definition of conditional entropy, but I'm not sure how to do it properly, in the case it makes sense.
Answer: No, this isn't true—your 'intuition' statement is incorrect. It assumes that the information that a variable provides about another is proportional to the amount of information in the variable itself. It could be that the higher-entropy variable is more related.

Let's demonstrate with an example.
Consider 5 independent random variables with the same entropy: $A$, $B$, $C$, $D$, and $E$, and a sixth $F$ with greater entropy. (Perhaps they all are uniform on the same support, except $F$ has a larger support.)
Now define $Y \triangleq (A, B, C)$, $X \triangleq (A, D, E)$, and $Z \triangleq (A, B, F)$. As the joint entropy of independent variables is their entropies' sum, $H(Y) = H(A) + H(B) + H(C)$. Similarly, $H(X) = H(A) + H(D) + H(E)$, and $H(Z) = H(A) + H(B) + H(E) > H(X)$.

A
B
C
D
E
F (bigger!)

Y
✓
✓
✓

X
✓

✓
✓

Z
✓
✓

✓

So far, we've shown your precondition $H(X) < H(Z)$ by the construction of our variables. Now what about the conditional entropy?
$$
\begin{align}
H(Y \mid X) &= H(B) + H(C) \\
H(Y \mid Z) &= \hphantom{H(B) + } H(C)
\end{align}
$$
Because we know $H(B) = H(C)$, this means that $Z$ reduced our uncertainty about $Y$ more than $X$ did! And it did this despite having larger entropy.

Note that $A$ wasn't strictly necessary here. If we cut it out of the example, then $X$ would still have smaller entropy than $Z$, but it would have no contribution to $Y$ at all. I think it's more general to keep it in.

Please, can you tell why it holds that (|)=()+()?

Sure thing!
It is always true for any $J$ and $K$ that $H(J, K) = H(J \mid K) + H(K)$. This is the chain rule for entropy, which mirrors the chain rule for probability. It says that knowledge of $K$ reduces our uncertainty about $(J, K)$ by the amount $H(K)$; the remaining uncertainty is $H(J \mid K)$.
In our case, we're curious about $H(Y \mid X)$. Let's figure it out from the joint entropy $H(Y, X)$ and the entropy of $X$, $H(X)$.
Fortunately, from here it's just algebra. On the third line, we rely on the fact that independent variables' entropies add.
$$
\begin{align}
H(Y, X) &= H(Y \mid X) + H(X) \\
H(A, B, C, D, E) &= H(Y \mid X) + H(A, D, E) \\
H(A) + H(B) + H(C) + H(D) + H(E) &= H(Y \mid X) + H(A) + H(D) + H(E) \\
H(B) + H(C) &= H(Y \mid X) \\
\end{align}
$$
If that seemed a bit long-winded, the intuitive way to think about it is this: If we know $X$, then we know that much about $Y$. The only missing information about $Y$ is in $B$ and $C$.
Comment: Happy to! I just updated the answer to include that information at the bottom.
Comment: Put simply, $Z$ should be more related to $Y$ than $X$ is. For anything beyond this toy example, finding a fitting $Z$ here may require domain knowledge. It's not about statistical properties of $Z$ by itself! ...This is a bit of circular reasoning, but the mutual information $I(Y, Z)$ should be greater than $I(Y, X)$.
Comment: Dear Arya McCarthy, Thanks for your reply. Please, can you tell why it holds that $H(Y|X)=H(B)+H(C)$?
Comment: Thank you very much @Arya McCarthy. Your explanation is very complete. Now, let me take advantage of your good knowledge of this matter to ask for your opinion. What statistical properties do you think that $Z$ should have to reach out to $H(Y|Z) < H(Y|X) $?


How do I use custom user forms?

Question: After creating separate user registration form in Structure > Display Modes > Form Mode and creating those forms in Configuration > People > Manage Forms, how do I use these forms? I want different roles on my site to use different registration forms to register different users.
Answer: There is no option for this in ui.
You have to define the display mode for the form in mymodule.routing.yml:
Example from user.routing.yml
user.admin_create:
  path: '/admin/people/create'
  defaults:
    _entity_form: 'user.register'
    _title: 'Add user'
  requirements:
    _permission: 'administer users'

In the line  _entity_form: 'user.register' the form is user and the form mode is register.
Then you can access the form with the path defined here and restrict the access through roles with requirements.
Edit (place the form on any page)
If you want to place the form on any page, you need the form as a block.
You can use this module:
https://www.drupal.org/project/entityform_block
But it does not have the option for arguments like form mode.
This experimental module can do this:
https://www.drupal.org/project/entity_forms_in_blocks

Interesting features that does not exists for now with the other modules : ability to choose the form mode as Drupal 8 allows to (in
  Drupal 8, you can create additional form modes).
Comment: In this case you don't need a path for the form, but you need the form as a block, see the edited answer.
Comment: You have to configure the visibility of each block in block layout.
Comment: I created the forms in display modes as I mentioned in the question already. I have not created any custom module. In drupal 7, we could render a form with `drupal_get_form` and I know we can use form builder to render any form on anypage. I am not sure the class i should pass in the arguments though.
Comment: Very great module - entity_forms_in_block. One problem still though, can it render different user registration forms for different pages?

How do I use custom user forms?


How to play sound file one by one on click event

Question: I have some mp3 format audio files. I want to play it on click event in JavaScript. I tried some code. But issue is that, when I click multiple link then all respective audio play together.
But I want play one by one. Means previous audio will stop and play current clicked audio.
JavaScript code is -
var audiofullpathdufault=audioPath;
var xNewaudiodefault = document.createElement("AUDIO");
if (xNewaudiodefault.canPlayType("audio/mpeg"))
{
    xNewaudiodefault.setAttribute("src",audiofullpathdufault);
}
else
{
    xNewaudiodefault.setAttribute("src",audiofullpathdufault);
}
xNewaudiodefault.setAttribute("controls", "controls");
xNewaudiodefault.pause();
xNewaudiodefault.play();

My audio output is - If click on more than one link then previous audio will stop or pause and current clicked audio will play.
Comment: add click listener and stop all audios on page before playing the selected one?
Comment: I have add pause() method. but its not working here. why?
Comment: Possible duplicate: [stop all videos when a new video is played](http://stackoverflow.com/questions/14890267/stop-all-videos-when-a-new-video-is-played)
Answer: you just need to declare a function called onclick which stops previous audio and plays new audio :
function playAudio (src) {
    if(window.audio) {
       audio.pause();
    }
    window.audio = new Audio (src);
    window.audio.play();
}

now all you need to do is to call it when you click on a link:
<tag onclick="playAudio('/link/to/audio.mp3')"> Click Me </tag>

notice I used window.audio to make it global so that we can stop previous playing audio