How to use vector drawables with View besides ImageView with srcCompat?

Question: app:srcCompat with ImageView allows for backward compatible use of vector drawables. But how can you use them with other Views besides ImageView? For example, the TextView attributes like android:drawableLeft.
Also using the vector drawable as an android:icon with MenuItem caused a crash with the following exception:
Fatal Exception: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
   at android.view.LayoutInflater.createView(LayoutInflater.java:626)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
   at android.support.v7.view.menu.MenuItemImpl.setActionView(MenuItemImpl.java:621)
   at android.support.v7.view.menu.MenuItemImpl.setActionView(MenuItemImpl.java:40)
   at android.support.v4.view.MenuItemCompat.setActionView(MenuItemCompat.java:310)
   at android.support.v7.view.SupportMenuInflater$MenuState.setItem(SupportMenuInflater.java:465)
   at android.support.v7.view.SupportMenuInflater$MenuState.addItem(SupportMenuInflater.java:479)
   at android.support.v7.view.SupportMenuInflater.parseMenu(SupportMenuInflater.java:196)
   at android.support.v7.view.SupportMenuInflater.inflate(SupportMenuInflater.java:118)
   at com.example.niceapp.context.main.MainActivity.onCreateOptionsMenu(MainActivity.java:101)
   at android.app.Activity.onCreatePanelMenu(Activity.java:2578)

With Support Library 23.2.0, how can this issue be addressed?
Answer: Update 2: They have added an option to enable it again in Support Library 23.4.0:

For AppCompat users, we've added an opt-in API to re-enable support Vector Drawables from resources (the behavior found in 23.2) via AppCompatDelegate.setCompatVectorFromResourcesEnabled() - keep in mind that this still can cause issues with memory usage and problems updating Configuration instances, hence why it is disabled by default.

Update:
This no longer works starting from version 23.3.0

For AppCompat users, we've decided to remove the functionality which
  let you use vector drawables from resources on pre-Lollipop devices
  due to issues found in the implementation in version 23.2.0/23.2.1
  [https://code.google.com/p/android/issues/detail?id=205236, https://code.google.com/p/android/issues/detail?id=204708]. Using app:srcCompat
  and setImageResource() continues to work.

From Android Developers Google+ post

Using AppCompat and app:srcCompat is the most foolproof method of integrating vector drawables into your app.

That quote is from the official blogpost for the release of version 23.2.0 of the Support Library.
The post also mentions the following:

You'll find directly referencing vector drawables outside of app:srcCompat will fail prior to Lollipop. However, AppCompat does support loading vector drawables when they are referenced in another drawable container such as a StateListDrawable, InsetDrawable, LayerDrawable, LevelListDrawable, and RotateDrawable. By using this indirection, you can use vector drawables in cases such as TextView's android:drawableLeft attribute, which wouldn't normally be able to support vector drawables.

This translates to the steps below:
Step 1:
Create or import a vector resource which you require for the app. For example, one can create a vector drawable for the search icon and name it ic_action_search_vector.xml
Step 2:
Create another proxy drawable resource for the vector drawable previously created. Say, for the previous ic_action_search_vector.xml, ic_action_search.xml can be created as a simple StateListDrawable which could contain the lines below:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_action_search_vector"/>
</selector>

This step can be skipped if you have referenced the vector drawable from another drawable resource which you will use with your View.
Step 3:
Use the drawable resource (here, ic_action_search.xml) that refers to the vector drawable (ic_action_search_vector.xml) instead of the vector drawable directly. For a menu, it would look like:
<item android:id="@+id/search"
        android:title="@string/search"
        android:icon="@drawable/ic_action_search"
        app:showAsAction="always"/>

This is the solution to that problem!
Comment: Hi, we can do this by programmatically for AppCompat version 23.3.0, see my answer please.
Answer: For AppCompat version 23.3.0 where no work solution via selector XML (razzledazzle's accepted answer) we can do this by programmatically:
activity_main.xml
<android.support.v7.widget.AppCompatImageButton
    android:id="@+id/btnEnter"
    />

MainActivity.java
AppCompatImageButton image = (AppCompatImageButton) findViewById(R.id.btnEnter);
if (image != null) {
    VectorDrawableCompat vcAccept = VectorDrawableCompat.create(getResources(), R.drawable.vc_accept, getTheme());
    VectorDrawableCompat vcAcceptWhite = VectorDrawableCompat.create(getResources(), R.drawable.vc_accept_white, getTheme());

    StateListDrawable stateList = new StateListDrawable();
    stateList.addState(new int[]{android.R.attr.state_focused, -android.R.attr.state_pressed}, vcAccept);
    stateList.addState(new int[]{android.R.attr.state_focused, android.R.attr.state_pressed}, vcAcceptWhite);
    stateList.addState(new int[]{-android.R.attr.state_focused, android.R.attr.state_pressed}, vcAcceptWhite);
    stateList.addState(new int[]{}, vcAccept);

    image.setImageDrawable(stateList);
}

This code is equivalent for this selector xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/vc_accept" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/vc_accept_white" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/vc_accept_white" />
    <item android:drawable="@drawable/vc_accept" />
</selector>

UPDATE
If the vector drawable is not shown using API 23, you'll need to convert the VectorDrawable to a regular Drawable first. If you want to use setCompoundDrawablesWithIntrinsicBounds you'll need to do this, but for StateListDrawable I didn't need to.
Drawable icon;
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
    icon = VectorDrawableCompat.create(getResources(), R.drawable.vc_icon, getContext().getTheme());
} else {
    icon = getResources().getDrawable(R.drawable.vc_icon, getContext().getTheme());
}

Comment: Thanks!!! Setting the vector drawable with setImageResource did not work in my Adapter. Creating a VectorDrawableCompat of it and setting it as ImageDrawable worked perfectly!
Answer: Vector drawables can be used pre-Lollipop in other places than app:srcCompat, but it comes with a price.
I've made this diagram to help (valid for Support Library 23.4.0 to - at least - 25.1.0).
Answer: You can add Vector Drawable in TextView programmatically. Make use of VectorDrawableCompat inorder to add drawableLeft/ drawableRight /drawableTop/ drawableBottom/ drawableStart/ drawableEnd.
Steps:
i. If TextView is inside Activity:
TextView tvUserName= (TextView)findViewById(R.id.et_username_or_email);
VectorDrawableCompat drawableCompat=VectorDrawableCompat.create(getResources(), R.drawable.layer_list_ic_user, tvUserName.getContext().getTheme());
tvUserName.setCompoundDrawablesRelativeWithIntrinsicBounds(drawableCompat, null, null, null);

ii. If TextView is inside Fragment:
TextView tvUserName= (TextView )view.findViewById(R.id.et_username_or_email);
VectorDrawableCompat drawableCompat=VectorDrawableCompat.create(getActivity().getResources(), R.drawable.layer_list_ic_user, tvUserName.getContext().getTheme());
tvUserName.setCompoundDrawablesRelativeWithIntrinsicBounds(drawableCompat, null, null, null);

For more information on VectorDrawableCompat Refer this  link
Comment: this is working, thank you but theme is compulsory to add?
Comment: @RuchaBhatt Yes, it's compulsory.
Comment: yes, i checked it, but u can pass null so it's fine. :)
Comment: @RuchaBhatt Happy to help & if you are using custom text view then it's good practice to use theme.
Comment: Thanks but this solution requires API 17+ (Jelly Bean MR1)
Answer: Android 5.0 (API level 21) and higher provides vector drawable support. If your app has a minimum API level that is lower, Vector Asset Studio adds the vector drawable file to your project; also, at build time, Gradle creates PNG raster images at various resolutions. Gradle generates the PNG densities specified by the Domain Specific Language (DSL) generatedDensities property in a build.gradle file. To generate PNGs, the build system requires Android Plugin for Gradle 1.5.0 or higher.
This is not true if you include in your gradle
 vectorDrawables.useSupportLibrary = true
either set to false or remove the line completely and all your vectors will work as they were.  But for olders versions of android they will be able to rely on the converted PNG
Answer: Form android studio 3.0.0 android:src is not support vector image and below 21 my get exception. use app:srcCompat for vector image. Keep all vector image files inside the drawable folder.
android {
   defaultConfig {
     vectorDrawables.useSupportLibrary = true
    }
 }

And in application class define this:

@Override
public void onCreate() {
    super.onCreate();
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}

Now you can use your .xml file. Don't forget to user this link: xmlns:app="http://schemas.android.com/apk/res-auto"

<RelativeLayout
    android:id="@+id/counterValuePanel"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/ic_cart_notify"/>
</RelativeLayout>

Now you can use app:srcCompat="@drawable/ic_cart_notify" but if you try to use in android:background or android:drawableLeft then you got "Error inflating" exception. For that create a new wrapped drawable .xml file, ic_cart_notify is vector icon.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_cart_notify"/>
</layer-list>

Answer: Dadou is right. So if you would like use selector for view with VectorDrawables you need to add:
    static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(trfor);
}

to every Activity where you want to use VectorDrawables on devices with versions below Android 5.
Answer:
set vector drawable to side drawable in textview in android

AppCompatTextView now supports app:drawableLeftCompat, app:drawableTopCompat, app:drawableRightCompat, app:drawableBottomCompat, app:drawableStartCompat and app:drawableEndCompat compound drawables, supporting backported drawable types such as VectorDrawableCompat.
Include this in your gradle file
implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'

In your text view you can use
app:drawableLeftCompat
app:drawableStartCompat

Answer: I'm using new support library and all I have to do is:
compile 'com.android.support:appcompat-v7:25.1.1'

In Build.gradle file
 defaultConfig {

    vectorDrawables.useSupportLibrary = true
}

Now Where ever you are using like fragment, activity or adapter use this as the first line in your class
static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}

after that use like as we do before, something.xml
<ImageView
    android:id="@+id/ivMainNavigationIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Something.java
thumbIcon.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.ic_check_circle_black_24dp));

or if you have drawable id needed to be set dynamically
thumbIcon.setImageDrawable(ContextCompat.getDrawable(context,drawableID));


Possible values for infinum of polynomial with integer coefficients

Question: I'am trying to find all natural numbers $a\in\mathbb{N}$ such that there is polynomial with integer coefficients $P\in \mathbb{Z}[x]$ with
$$\inf_{x\in\mathbb{R}}\, P(x) = \sqrt{a}.$$
If $a=b^2$ for $b\in\mathbb{N}$ we obviously can take $P(x)=x^2 + b$, but what about $a$ that are not perfect squares? I have tried to find any but not succeed.
Comment: A near miss: $$\max_{x\in\mathbb{R}}{(-32a^5x^6+6a^2x^2)} = \sqrt{a}.$$
Comment: Note that if such a polynomial exists, then the infimum is in fact a minimum, and the value of $x\in\Bbb{R}$ for which $P(x)=\sqrt{a}$ is an algebraic number.
Comment: On a tangent, perhaps it is helpful to know that, for example
$$\min_{x\in\Bbb{R}}\big(27x^4+a\cdot4x\big)=-a\sqrt[3]{a}.$$
Similar identities exists for higher $n$-th roots, for all odd $n$.
Answer: The polynomial
$$P(x) = (2a)^8x^8-(2a)^5x^6-(2a)^5x^4+6a^2x^2+a^2$$
satisfies
$$\min_{x\in\mathbb{R}} P(x) = \sqrt{a}.$$
If there is a polynomial of lower degree with the same property, then it must have degree $6$ (see below), assuming $a$ is not a perfect square.
There is however the degree-$4$ polynomial
$$R(x) = -(2a)^4x^4+(2a)^2x^3+(2a)^3x^2-3ax-a^2$$
that satisfies
$$\max_{x\in\mathbb{R}} R(x) = \sqrt{a},$$
leading to the surprising conclusion that achieving a minimum of $\sqrt{a}$ requires a strictly higher degree than achieving a maximum of $\sqrt{a}$.

Note that any $P(x)$ satisfying the original requirements necessarily has even degree. To see why $P(x)$ cannot have degree $4$, let $\beta$ be one of the real algebraic numbers where $P(x)$ achieves its minimum of $\sqrt{a}$. Then $\sqrt{a} = P(\beta)$ is an element of the field $\mathbb{Q}(\beta)$. Moreover, if there is an automorphism $\sigma$ of $\mathbb{Q}(\beta)$ satisfying
$$\sigma(\sqrt{a}) = -\sqrt{a} \qquad \text{and} \qquad \sigma(\beta) \in \mathbb{R},$$
then
$$P(\sigma(\beta)) = \sigma(P(\beta)) = \sigma(\sqrt{a}) = -\sqrt{a},$$
meaning $\sqrt{a}$ is not actually the minimum of $P(x)$. (This is the step where the asymmetry between minimum and maximum becomes apparent.)
In summary, any automorphisms of $\mathbb{Q}(\beta)$ that send $\sqrt{a}$ to $-\sqrt{a}$ must send $\beta$ to a non-real number. In particular, $\beta \not \in \mathbb{Q}(\sqrt{a})$, so $\mathbb{Q}(\sqrt{a})$ is a proper subfield of $\mathbb{Q}(\beta)$. Since degrees of field extensions are multiplicative, this means that the degree of $\mathbb{Q}(\beta)/\mathbb{Q}$ is even and strictly greater than $2$; so $\beta$ has degree at least $4$. Finally, since $P'(\beta) = 0$, $P(x)$ must have degree greater than $4$.

Here's how I found $P(x)$:
The simplest $\beta$ that satisfies the above restrictions on $\mathbb{Q}(\beta)$ is $\beta = \sqrt[4]{a}$. I first constructed a polynomial $Q(x)$ with rational coefficients to have minimum $\sqrt{a}$ at $x=\pm\sqrt[4]{a}$. Here $Q(x)$ necessarily has the form
$$Q(x) = (x^4-a)q(x)+x^2$$
such that $q(x)$ has positive leading coefficient and $Q'(x)$ is divisible by $x^4-a$. This quickly leads to
$$Q(x) = (x^4-a)^2 -\frac{1}{2a}x^2(x^4-a) + x^2.$$
Finally, to get integer coefficients without affecting the minimum, we scale $Q(x)$ horizontally; $P(x) = Q(2ax)$ does the job.
Comment: Edited to expand that part a bit more.
Comment: Very useful! Can you please explain why $\beta \not \in \mathbb{Q}(\sqrt{a})$ implies that $\beta$ has degree at least $4$?


Firebase onChildChanged Listener is getting fired twice

Question: I am facing very weird issue with firebase, I have data in attached format in firebase and I am trying to fetch the data recreate whole recyclerview adapter list if any of child node for that conversation changed.
If I run it using debugger , it fired onChildChanged() only once but otherwise fire twice, Please help.
private void getConversations(){

    final DatabaseReference conversationRef = databaseReference.child("conversation").child(currentUser);

    // Get event fired when new child added
    conversationRef.orderByChild("time").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
            String ref= dataSnapshot.getKey();
            int position = userListRef.size();
            userListRef.add(position,ref);
            getDetailedConversations(position);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
                userListRef.clear();
                conversationListRef.clear();
                conversationAdapter.clear();
                //conversationAdapter.notifyDataSetChanged();
                Log.d(TAG, "new position: data changed+++++++++++++++++++++");
                conversationRef.removeEventListener(this);
                getConversations();

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {}

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}

        @Override
        public void onCancelled(DatabaseError databaseError) {}

    });
}

private void getDetailedConversations(final int position){

    DatabaseReference databaseReferenceAdapter = FirebaseDatabase.getInstance().getReference();
    final DatabaseReference conversationRef  = databaseReferenceAdapter.child("conversation").child(currentUser).child(userListRef.get(position));

    conversationRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d(TAG,"Single value event");
            final Conversation conversation = dataSnapshot.getValue(Conversation.class);
            conversation.setFirebaseToken(dataSnapshot.getKey());
            conversationListRef.add(conversation);
            conversationAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

LogCat :
11-07 22:56:01.127 15524-15577/io.ace.aceme E/Surface:
getSlotFromBufferLocked: unknown buffer: 0x9b9e2860
11-07 22:56:02.618 15524-15573/io.ace.aceme V/FA: Inactivity,
disconnecting from AppMeasurementService
11-07 22:56:05.566 15524-15524/io.ace.aceme D/MessagesActivity: new
position: data changed+++++++++++++++++++++
11-07 22:56:05.570 15524-15524/io.ace.aceme D/MessagesActivity:
Single value event
11-07 22:56:05.785 15524-15524/io.ace.aceme D/MessagesActivity: new
position: data changed+++++++++++++++++++++
11-07 22:56:05.785 15524-15524/io.ace.aceme D/MessagesActivity:
Single value event
11-07 22:56:05.786 15524-15524/io.ace.aceme D/MessagesActivity:
Single value event
11-07 22:56:06.134 15524-15524/io.ace.aceme D/MessagesActivity:
Single value event
11-07 22:56:06.134 15524-15524/io.ace.aceme D/MessagesActivity:
Single value event
11-07 22:56:06.137 15524-15524/io.ace.aceme D/MessagesActivity:
Single value event
11-07 22:56:07.393 15524-15573/io.ace.aceme V/FA: Activity paused,
time: 16426758
11-07 22:56:07.398 15524-15573/io.ace.aceme V/FA: Activity resumed,
time: 16426764

Firebase Database:
Database pic
Comment: onDataChange you are removing and adding listener again, it is not required.And also you are trying to combine order-by and child event listener, that is not advised use value event listner
Comment: @Shanmugam listener has to be removed otherwise it would attach more listensers on top of it, I have tried it earlier. it does not help.
Comment: Even more shocking is , when I am running it using debug mode , it called on once but I normal run it called 2 times on any child change.
Comment: what is your requirement?your Implementation is wrong...
Comment: my requirment is fetch all conversation of one user, In my code I am fetching the reference path first and then do SingleValue listener to get Conversation object. if you look at snapshot you can understand quickly.
Answer: Here is the updated query , no need to use orderBy
private void getConversations(){

final DatabaseReference conversationRef = databaseReference.child("conversation").child(currentUser);

// Get event fired when new child added
conversationRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
        String ref= dataSnapshot.getKey();
        int position = userListRef.size();
        userListRef.add(position,ref);
        getDetailedConversations(position);
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
            //Here no need to clear and reload
            //just find the user in list and update the corresponding object and call notifyDatasetChanged()

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {}

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}

    @Override
    public void onCancelled(DatabaseError databaseError) {}

});

}
Comment: Thanks for it ! but it does not resolve my purpose if I remove order by. I would not be able to sort conversation based on time whenever child node change.


For PCA, the best axis for the projection of the points is the one who has the minimal or the maximal inertia?

Question: I am learning statistics mainly from a book : Elements de statistique, from three author of the Brussels University. 5th Edition
On the PCA chapter, however, I need to read from other sources, especially to understand how to describe what the axis represents from individual and variable analysis. I then read the whole courses that can be found everywhere over the Internet. And I have a trouble.
My book wrotes :

La droite qui ajuste le mieux le nuage N* des individus est celle autour de laquelle l'inertie de N* est minimale.
  (The line that adjusts the best the cloud N* of individuals is the one around which the inertia of N* is minimal).

And the problem is : almost all other sources I can read are searching for the maximal inertia to find the best axes.
I can't figure my book could be wrong (on it's 5th edition such a bug would had been found), so what is it trying to explain to me ? And why do I find the contrary elsewhere ?
Comment: Although it is quite similar, I don't think this specific question has an answer in the linked post, where there is no mention of *inertia*.
Comment: There are many questions in SO dealing with PCA, its derivations and interpretations. For example, see https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues/6271#6271
Answer: In PCA, we choose the projection direction(s) that captures the most variance; this is well explained in the linked posts. In some sources, inertia is described as variance. So, the directions with most variance are the directions with most inertia. I can't review the definitions in the book to see if they're talking about the same concept or not since it's in French. However, from a physics perspective, if we think the data points as a cloud of mass and seek for an axis around which rotating the object is easiest, it's going to be the direction of the first PC. For a reference, check the moment of inertia of a rectangular prism/cuboid. The axis with least inertia will be the longest dimension.


The relationship between the norm of the gradient solution of Poisson's equation

Question: Question:
Consider the following two special Poisson equations:
$$\Delta u=-2 \quad \text{in} \quad L$$
$$u=0 \quad \text{on} \quad \partial L$$
and
$$\Delta u=-2 \quad \text{in} \quad W$$
$$u=0 \quad \text{on} \quad \partial W.$$
If $L\subseteq W$, can we get $||\nabla u_{L}(x)||\leqslant ||\nabla u_{W}(y)||$, where $x \in \partial L$, $y \in \partial W$ and $x,y $ are in the same direction?
I know almost nothing about partial differential equations, and I encountered this problem while working on other problems.
Comment: I believe that if this question is made a bit more precise, this is true and follows from the fact that a $u$ is convex iff its gradient is monotone, c.f. https://math.stackexchange.com/questions/1717542/a-function-is-convex-if-and-only-if-its-gradient-is-monotone#:~:text=Let%20a%20convex%20U%E2%8A%82,f%3AU%E2%86%92R%20differentiable.
Comment: Related: https://math.stackexchange.com/questions/4855598/the-relationship-between-the-norm-of-the-gradient-solution-of-poissons-equation/4856418?noredirect=1#comment10351990_4856418
Comment: I assume be $x,y$ having the same direction you mean $x/\vert x\vert =y /\vert y\vert$. This assumption is actually redundant since two points are always co-linear and your problem is invariant under translations, so you can always translate the origin onto this line
Answer: No.
Given $\Omega \subset \mathbb R^n$ open, bounded with $C^1$ boundary, define $\psi_\Omega :\overline \Omega\to\mathbb R$ to be the unique solution in $C^2(\Omega)\cap  C^0(\overline \Omega)$ satisfying $-\Delta \psi_\Omega = 1 $ in $\Omega$ and $\psi_\Omega=0$ on $\partial \Omega$.
Now, consider $L=B_{1/2}$ (the ball of radius $1/2$ centred at $0$) and $W= B_1 \cup B_R((2+R)e_1)$ where $e_1=(1,0,\dots,0)\in \mathbb R^n$ and $R>0$. Then, since $B_1$ and $B_R((2+R)e_1)$ are disjoint, \begin{align*}\psi_W (x) &= \begin{cases}
\psi_{B_1}(x), &\text{in } B_1 \\
\psi_{B_R((2+R)e_1)}(x), &\text{in } B_R((2+R)e_1)
\end{cases} \\
&=\frac1 {2n}\begin{cases}
1-\vert x \vert^2, &\text{in } B_1 \\
R^2-\vert x - (2+R)e_1\vert^2, &\text{in } B_R((2+R)e_1) .
\end{cases}
\end{align*} Then, for $x\in \overline{B_R((2+R)e_1)} $, $$\nabla \psi_W(x) =-\frac1n (x-(2+R)e_1) ,$$ so $$\vert \nabla \psi_W((2+2R)e_1) \vert^2 = \frac {R^2} {n^2}. $$ Similarly, we have that $$\vert \nabla \psi_L (1/2 e_1) \vert^2 =\frac 1 {4n^2}.$$ Thus, $L \subset W$, $1/2 e_1$ and $2(1+R)e_1$ point in the same direction, but for $0<R<1/2$, we have that $$\vert \nabla \psi_L (1/2 e_1) \vert^2 =\frac 1 {4n^2} > \frac{R^2}{n^2} = \vert \nabla \psi_W((2+2R)e_1) \vert^2.  $$

You might complain that this isn't really a satisfactory counter-example because $W$ isn't connected. However, from the previous example you should be able to construct a counter-example with $W$ connected. Indeed, let $\varepsilon>0$ and $W_\varepsilon$ be the union of $B_1$ and $B_R((2+R)e_1)$ (as above) with a 'neck' connecting the right hand side of$B_1$ to the left hand side of $B_R((2+R)e_1)$ in a smooth way and such that the neck is contained in a cylinder with cross-sectional radius $\varepsilon$. Then consider $\psi_{W_\varepsilon}$. Now, as $\varepsilon \to 0^+$, $\psi_{W_\varepsilon} \to \psi_W$ in $C^1$ provided that you are away from the neck i.e. outside some small ball that contains the join of the neck and the ball. (If you have to contrust this counter-example rigorously then you have to prove my previous statement, but there exists literature somewhere on this kind of thing). But now, by continuity, for $R$ as above and $\varepsilon$ sufficiently small, $$\vert \nabla \psi_L (1/2 e_1) \vert^2 > \vert \nabla \psi_W((2+2R)e_1) \vert^2+\varepsilon \geq \vert \nabla \psi_{W_\varepsilon}((2+2R)e_1)\vert^2.  $$


Is time.h clock() broken on my hardware?

Question: I try to measure the clock cyles needed to execute a piece of code on the TMS32064x+ DSP that comes with the OMAP ZOOM 3430 MDK. I look at the "Programmer's Guide" of the DSP chip and it says that the DSP supports the clock() function.
What I do is really simple, I just do
start = clock();
for (i=0;i<100;i++){
    /* do something here */
}
stop = clock();
total = stop - start;

and then put the values of "start","stop" and "total" to a previously allocated shared memory with the ARM processor. Then I simply print it to the screen at the ARM side.
The problem is, in my first executes, I always get the same "total" value, and then in my next runs I always get 0! The "start" and "stop" values go along with the "total" value.
The strangest thing is that they seem to follow a bit pattern! I put the output below:
# ./sampleapp
Total = 63744
Start clock() value = 0x000000f9
Stop  clock() value = 0x0000f9f9
# ./sampleapp
Total = 4177526784
Start clock() value = 0x00f9f9f9
Stop  clock() value = 0xf9f9f9f9
# ./sampleapp
Total clock cyles = 0
Start clock() value = 0xf9f9f9f9
Stop  clock() value = 0xf9f9f9f9

Apparantly, clock() is not functioning well, but I'm not sure if this is because of something I do wrong or because this type of thing is not supported with the hardware I have. Any ideas why this might be happening?
Comment: Have you tried *gettimeofday()*?
Comment: Are you absolutely certain that clock is returning these values? You might just be looking at a problem with accessing the shared memory?
Comment: To check this, I simply change one of the return values, say "start", to a predefined value or to the shared memory address' value and I get the correct thing on the screen.
Comment: Does TI have any examples?  I think with some of their other CODEC examples they were also calculating an elapsed time of execution.  I don't remember if they used the clock() api.  But it does seem to work in the decoder or encoder example code.
Comment: I didn't come across any CODEC examples that use the DSP as well. If you know one, I appreciate a reference or link.
Comment: is it possible to be a bug with the toolchain used?
Comment: It may be! I'll ask TI about this.
Comment: Is that exec() a "real", POSIX-style exec() call, or just notation? If it's an exec(), that will replace your process' image (assuming POSIX semantics), so the stop time will never be written.
Comment: I edited my post. With exec() I just wanted to imply there is a function called inside the loop; the function is actually irrelevant, and does only some math operations.
Comment: Yes I have thought of it, but the DSP doesn't support it. I can't include sys/time.h . But as a work around I measure the run time of DSP from CPU with gettimeofday() and it works. The only thing is I have to subtract the overhead from messsaging manually.
Comment: Do you have a link to the reference manual for the device you're using?
Answer: From reading the questions so far, I'd say the Original Poster has substantially more knowledge of this matter than the contributors so far, and that the suspicion that the clock() is broken (or not supported, and returns an undefined result) on the DSP seems quite likely.
Comment: I started to believe that this is the case too, so there is no need to leave this question as unanswered anymore. Thanks to you all.
Comment: How humble of you Can Bal, that you have started to agree to believe that you have substantially more knowledge than the contributors, and selected as the answer the one stating that one. nice :) I agree that clock() is broken too, however, on OMAP.
Comment: It seems you are not the only person having trouble with clock().  Perhaps the solutions provided here will be of help.  http://stackoverflow.com/questions/588307/c-obtaining-milliseconds-time-on-linux-clock-doesnt-seem-to-work-properly
Answer: Assuming the start and end variable are of type 'clock_t', and your shared memory assumes the same on the other end's interpretation of the numbers passed, then your problem is not with the call to clock, and your handleing of the difference between the start end end times.
I believe your problem is in the shared memory between the two.  Can you please post code to show how you're sharing memory between two separate processors?
Comment: I simply use the same method TI used through its dmmcopy sample.

MPU side sample:
http://gitorious.org/ti-dspbridge/userspace/blobs/master/source/samples/mpu/src/dmmcopy/dmmcopy.c

DSP sample:
http://gitorious.org/ti-dspbridge/userspace/trees/master/source/samples/dsp

But I don't think the problem is with the shared memory since I can pass hard-coded values from DSP to CPU correctly instead of the start stop and total variables.
Answer: Curiously, Why do you require a previously allocated shared memory. Why don't you try with a normal stack variable? Is there anything that I am missing?
Comment: Yes, you're missing the fact that the code shown runs on one processor, the DSP, while the code that displays the results runs on another, the main ARM CPU.
Answer: How are you printing it out? maybe the issue is actually with displaying the result?
on most platforms clock_t is a long long. If you're using printf with %d you might get variable results which is what you're seeing.
Comment: I printed out sizeof(clock_t) and it is 4. It is defined as unsigned int.
Comment: To persist on this vein, is your printing code proven good? Have you fed some values through the same kind of memory transfer / printout to check if they come accross correctly?
Answer: Maybe you need to initialize the clock first.
Comment: As far as I know clock() takes the reference point as the initial call of the executable. I don't know how to initialize/reset its value manually. How do you do that?
Comment: I've just reread the man pages, the standard gives no way to do such a thing.
Answer: Perhaps you could use some inline assembly to access the CPU's counter registers directly.
The TMS320C64x+ has a 64-bit timestamp register in TSCL, TSCH.  The counter is not enabled on reset, you must first write to the register to start the counter (maybe this is the problem with clock?).  Reading from the register is not quite trivial as each half must be read with a separate instruction (and you can get interrupts...).
Comment: I didn't know this was an old question.  This is what I get for not paying attention to timestamps!


What statistical test do I use to compare 2 running means?

Question: I have measured the learning rates of two neural network models, and now I have the average reward plotted against time, for both models. What statistical test can I use to compare the 2 lines to see if there is a significant difference or not?
The models are both the same, but are initialized differently to see whether the average reward against time changes.
Answer: More formally, you can use ANCOVA
Or a quick way would be to take the difference of the learning rates and then doing linear regression to see if the slope is statistically significant to be not 0 (T-test), Showed below:


Provide several download option for same image in Drupal 7

Question: Would anybody have any idea of how to create several download option of the same image in Durpal 7.
The sample website is: http://www.travesto.com/content/101jpg-anime-animated where several download option is enabled.
I would like to create a similar option for my birthday photos. I think may be views module is used here. BUt not sure. If anybody have any idea of doing this. plz help me....
Answer: Do you mean different resolutions? Simply, you have to upload them, and link the files.
Then there are the following modules:

DownloadFile
Download
Comment: Yes, I mean several resolution download link of each image. For example, a.jpg is the original image and I would like to provide download option of like 1024X800, 400X200 etc.
Comment: like i said the page u linked realised it simply with a lot of different files, u see it at the link destination
Comment: But there are several links of the same image which provides severarl resolution download option. Below the image, you would see...
Download different resolution

    1024x1024
    1024x768
    1152x864
    1280x1024
    1280x720
    1280x800
    1280x960
    1366x768
    1400x1050
    1440x900
    1600x1200
    1680x1050
    1920x1080
    1920x1200
    1920x1440
    320x240
    320x480
    480x272
    640x960
    800x600
    852x480
Comment: http://www.travesto.com/imagecachedl/1440x900/travesto-wallpaper-anime-animated-1279944698.jpg, the resolution is in the URL as Parameter, u can implement that with the menu hook look for wildcard
Comment: could you please explain a little detail?
Comment: u have to write an own module, which registers the menu_hook and implement the download yourself. Or you go through the Module like the 2 i linked and check for modules which over the resolution download
Answer: You can create a content type like 'gallery' and you can insert a 'image' image field then you create a set of media image preset.
For example 'small-download', 'medium-download', 'big-download'.
Now, in your theme, you overwrite
field--image--gallery.tpl.php
some code like this:
    <div class="<?php print $classes; ?>"<?php print $attributes; ?>>
       <?php if (!$label_hidden): ?>
          <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:

       <?php endif; ?>

      <div class="field-items"<?php print $content_attributes; ?>>
        <?php foreach ($items as $delta => $item): ?>

          <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>

              //here you have to find [with print_r($item)] where in the $item
              //is stored the image url and put it in $url

              $image = array(
                'style_name' => 'thumb',
                'path' => $url
                );

              theme_image_style($image);

              l('Download small', image_style_url('small-download', $url));
              l('Download medium', image_style_url('medium-download', $url));
              l('Download big', image_style_url('big-download', $url));

        <?php endforeach; ?>

Comment: is this possible to do this using tokens? or other way? for example, if i use panels and is it possible to add customize code like the code?
Comment: This is a field override.
If you print this field [in node or in a block views or in a panel pane..] this field will be displayed in this way: image + 3 link


Android AudioTrack write blocks for the whole period of playback

Question: I am using AudioTrack class to play a stream of raw sound data:
AudioTrack audioTrack;
int sampleRate = 11025;
int channelConfigIn = AudioFormat.CHANNEL_IN_MONO;
int channelConfigOut = AudioFormat.CHANNEL_OUT_STEREO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
.....
int bufferSize = AudioTrack.getMinBufferSize(sampleRate,channelConfigOut,audioFormat);
audioTrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL,sampleRate,channelConfigOut,audioFormat,bufferSize,AudioTrack.MODE_STREAM);
    audioTrack.play();

Then on a separate thread:
while(true)
{
    short [] buffer = new short[14500];
    //fill buffer with sound data
    long time = System.currentTimeMillis();
    audioTrack.write(buffer,0,14500);
    Log.i("time",(System.currentTimeMillis() - time) + "");
}

My problem is that the log always shows that the write method blocks for about 0.6 second, that is the same as the played sound length (14500 samples), moreover the phone is not responding during the playback, the main tread almost can not do anything anyone can help...
Comment: [this](http://pastebin.com/tz2Mvh5G) just works ok
Answer: You are using the blocking version of the write() method. You can use write(float[],int,int,int) instead, passing WRITE_NON_BLOCKING as the 4th parameter, but that would only write as much data as can fit in the play buffer. I generally prefer the approach you already have (dedicating a thread to writing). You should expect each call to block; after all, the play buffer can only fit so much data, and to make more space, sound must be played (which takes time). 14500 samples is ~1.3 seconds of sound at your chosen sample rate, so I'm guessing it takes you about .7 seconds to fill buffer each time.
I cannot tell, based on the code presented, why your UI thread is not responding.
Comment: Thank you for response, first the method you suggested needs apk 23, so I did not use it although I know it exists, second I did use `HandlerThread` to solve it, it seems the priority of the thread was the cause of it. Anyway it seems there is an accumulated latency that causes the playback to be late a little as time go on


When doing integration by parts/tabular integration and you do a u-sub can you only resub the variable at the end?

Question: I was just wondering if during tabular integration (DI method)/ibp you do a substitution during one of the steps can you carry the substitution until the end and only change the variable back at the end?
i.e. would this be valid:
$$\int_{0}^{1}\frac{ln(x)}{x^2+1}\,dx = \int_{-\infty}^{0}\frac{t e^t}{e^{2t}+1}\,dt\\
t=ln(x)\\e^t dt=dx$$
Let $$D = t,1,0$$ for the first 3 rows
$$
I\\
\int_{-\infty}^{0}\frac{e^t}{e^{2t}+1}\,dt\\z=e^t\\dz=e^tdt\\ \ \\
\int\frac{dz}{z^2+1}= \arctan(z)$$
Would it be valid at this point if we went and integrated wrt to z again?
i.e.
$$t\arctan(z)-\int{\arctan(z)}dz\\=t\arctan(e^t)-e^t\arctan(e^t)-\frac{1}{2}\ln(e^{2t}+1)\\=\ln(x)\arctan(x)+x\arctan(x)-\frac{1}{2}\ln(x^2+1)$$
or would you have to integrate it after you resubstitute the original variable like this:
$$t\arctan(e^t)-\int\arctan(e^t)dt$$
Answer: Broadly, yes, you can always use a substitution to evaluate an integral regardless of where that integral appears, but you need to be careful about preserving the relationships across the various substitutions.
If your substitution is such that $\int f(t) dt = \int g(z) dz$, there's nothing stopping you from evaluating $\int g(z) dz$ without going back to $t$ until you reach a point where you need to do so.
In fact, your last line would be incorrect - you cannot replace $z$ with $e^t$ inside an integral sign unless you also replace $dz$ with $\frac{dz}{dt} dt$, which would just give you an integral that you'd probably need to go back and substitute $z$ into again in order to solve.


symfony export html.twig to csv

Question: i'm trying to export a twig view into csv, but i'm stuck, can someone help me out with detailled solution ?
peace
/**
 *
 * @Route("/export", name="export_csv")
 */
public function exportAction() {

    $entity = new Invite();
    $form = $this->createForm(new ManifSearchType(), $entity);
    $request = $this->get('request');

    $em = $this->getDoctrine()->getManager();

    $view = $this->render('PrifProtocoleBundle:Invite:index.html.twig', array(
        'form' => $form->createView()));

    $handle = fopen('php://memory', 'r+');
    $header = array();

    fputcsv($handle, $view);

    rewind($handle);

    $content = stream_get_contents($handle);
    fclose($handle);

    return new Response($content, 200, array(
        'Content-Type' => 'application/force-download',
        'Content-Disposition' => 'attachment; filename="export.csv"'
    ));
}

error message:
Warning: fputcsv() expects parameter 2 to be array, object given in C:\wamp\www\protocole\src\Prif\ProtocoleBundle\Controller\InviteController.php line 56

Comment: is your `index.html.twig` actually html formatted?  If it is csv formatted, there is a better way to output a csv file.
Comment: hi, thanks for  the reply. i didn't explain my problem well, what i want actually is to export the html form that is displayed through index.html.twig into a csv file.
Answer: The thing is, you are not trying to convert just a twig to a CSV file. You are converting HTML to a CSV file. Now that seems like a strange conversion.
What you should do is have your twig generate the CSV content. Like this:
$response = $this->render('PrifProtocoleBundle:Invite:export.csv.twig',array('data' => $data));
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
return $response;

And your twig should render in the CSV format.
Comment: hi, thanks for  the reply. i didn't explain my problem well, what i want actually is to export the html form that is displayed through index.html.twig into a csv file, is it feasable?
Comment: In the code I gave you, the $data you pass would be $form->getData(). You should not render an HTML to convert to a CSV, that doesn't make sense. You have your data already. Create a CSV from there. When someone submits the form, you handle the request, check to see if the form is valid, then you render the CSV with the form's data. So you have an HTML twig to display the form, so the user enters the data. And once the submitted data is valid, you have a CSV twig to render the CSV that you want to export. You should have 2 twig files. Doesn't that make sense?
Comment: hi, thanks for this precision, i understand now. it works perfectly
Comment: hi, i have another question, i created a form with a select box containing 10 values. After $form->getData, i want to return first a response in a html table (result.html.twig) and then being able to export the csv file (export.csv.twig) by a link in this html file.  In my controller i did something like: $response1 that renders the html file, and $response2 that renders the csv file. but i only return $response1, so i'm stuck. do you think it's the right way to do this, or do you have a better solution? thanks
Comment: You should return your HTML response first, with the data you get, and with the link to export to CSV. In the link to generate the CSV, you could add the parameters (your 10 fields) to generate the CSV file. That would be a long link. If that is NOT acceptable for you, then you should have a way to cache the data (with APC for example). So when you render the HTML table with your 10 fields, you cache the data as well. And when you click on "export CSV", in your action, you fetch the data in the cache, and render the CSV from there. That's what I would do.
Comment: i'm still stuck on this, don't know much about APC... and how to add these parameters. i've posted a new question for this, so if you have some time...Thanks! : http://stackoverflow.com/questions/20813736/symfony-trying-to-export-a-csv-file-from-a-link
Answer: Try this:
fputcsv($handle, (array)$view);

Comment: hi, your solution works. it opens a file export.csv on excel. that's good. but the html form that i want is not in the file. Actually my index.html.twig renders a form at http://localhost/protocole/web/app_dev.php/protocole/invite/export and i want this html form to be in this csv file.  do you know how i can change my code to do this? thanks
Comment: If you need to get plain HTML content, try renderView instead of render.
Answer: Old question but I came here when I searching a way to save rendered csv view in a file.
With Symfony 3.3 (current version today 05/09/2017) a new filesystem method was added:
$fs->appendToFile('my.csv', $view);

Complete example could be:
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;

$fs = new Filesystem();

try {
    $fs->appendToFile('my.csv', $view);
} catch (IOExceptionInterface $e) {
    echo "An error occurred while adding contents ".$e->getPath();
}

I have not tested yet, but it should works.
Source doc :
https://symfony.com/doc/current/components/filesystem.html#appendtofile

symfony export html.twig to csv


Node edit form with entity reference - show more than just the title in the autocomplete box

Question: I have three content types: application, organization, and organization_note. Application has an entity reference to organization and organization has an entity reference to organization note.
The application edit page has an autocomplete field for organization. When a user selects an organization which has a note, I would like the display to be different somehow, ideally a reminder to check the organization's notes.
This question is very similar to this one (unanswered).
I'm at a loss here, and I don't really even know if this is possible. How would I go about doing this? (This is Drupal 7, by the way.)
Answer: You can do this by creating an entity reference view.
Firstly, create a new view that displays the content type 'organization'. Do not add a page, but rather add an 'Entity Reference' display.

Your view should now have a format of 'Entity Reference list'. Now add a relationship to organization_note, and then add the fields that you would like to see in the autocomplete list. When that is done click on settings in 'format', and select the field that you want to search on when typing in the autocomplete. This normally would be title. You can also rewrite the field values to your liking as you would probably need to for your use case, though I would leave title standard.
Now go back to the field settings for 'application', and edit the settings for the entity reference field to organization. In the 'Mode' for the 'Entity Selection' section, select 'Views: Filter by an entity reference view'. This will open a new select from which you select the view you created above.


How to solve this probability Venn diagram question

Question: The probability that a randomly selected pet owner does not own a dog is?
my work:
You add up the numbers outside the dog circle then divide by 100. so that would be 32/100=0.32
so the answer is A=0.32 because a random probability selected pet owner not picking a dog cannot pick in the dog circle so he has to pick outside of the circle which is why the answer is A=0.32
Comment: is my answer correct?
Comment: Not owning a dog, means either someone doesn't own any pet or they may own a cat only. So the answer should be $(32+35)/100=0.67$.
Comment: No.  $.32$ is the probability that a randomly selected pet owner owns neither a cat nor a dog.  Which is an entirely different question.
Answer: Hints: $P(B^c) = P(\Omega) - P(B).
P(A) = P(A \setminus B) + P(A \cap B)$


When following a lesson should I make it perfect before going to the next lession

Question: I am following the lessons from a finger-style blues book. I have completed practice lessons "A" "B" and currently at "C". When I was practicing "A" I could be able to play it perfectly most of the time. Say 8 times out of 10. Same for "B" and now when I am practicing "C" when I try to play "A" I can play it properly only for about 30% of time. Should I go back to "A" and practice it again to the perfection or continue with "C" and move on?
When I mean I cannot play "A" I mean I forget which note to play after what. My fingering is almost perfect, that is to say I hardly make mistake plucking right string with right finger or alternate base.
What is the general Idea you follow? Perfect something then move on or play it good enough and move on.
NOTE: "A" "B" and "C" are similar and its not necessarily the other chapters depend on any of them except thumb independence and proper fingering.
Comment: This question is related and might give further guidance: http://music.stackexchange.com/questions/6910/how-to-go-learn-through-a-book/
Answer: If you wait to truly master something before moving on, it will take literally forever to make much progress.  Once you've learned something fairly well, it's good to take the next step.  It's also good to come back to things again and again.  I've found that with most learning, it's a process of 2 steps forward one step back.  This let's you keep learning new things and keep improving the basics too.
In deciding whether something has been practiced enough, it really depends on what you're practicing it for.  Often times with my students, I will let them pass of piece of music even if it's got a bunch of problems, so long as they've learned the thing I wanted them to learn.  But, if you're practicing something that you will do in a performance, you need to ask yourself whether you'd be comfortable doing it in front of other people.
Comment: This answer is also good but I have to chose only one :) but I will follow this advice as well and move to the next lesson whenever I feel I am satisfied :)
Answer: Presumably you're doing this practice in order to learn the skills involved in the exercise.  If you move on and lose the skill, the whole endeavour was pointless.  Even an 80% reproduction rate is pretty low so I don't think you are getting good enough at the exercise before moving on.  Of course this depends on how absolute your definition of "perfect" is.
Once you've mastered something you should need to practice it more and more infrequently in order to maintain your skill.  You might go from every day to every other day, to once a week, to once a month, to once every other month over the course of a year.  If at any point you feel that you are going backwards, you ought to increase the frequency of your refresher practice and try not to decrease it as quickly next time.
Eventually your skills will be so ingrained that they are effectively permanent; as long as you keep up other forms of practice so that your muscles and brain are sharp you should be able to use one of these ingrained skills without even thinking about it.
Comment: The exact problem I am currently facing is changing from E to B7 chord shape quickly. I do practice the piece everyday but should I stop and perfect it or move to the next exercises (With some time for the older exercises as well) which does not involve B7 and eventually changing to B7 will come easier to me.
Comment: @Tanmoy Ah, I see.  That's not the simplest of chord changes so if you feel the need to start with something easier and work up to it then that could certainly be a good idea.


WPF: Adding an image to a ListBox ItemTemplate

Question: I am creating a WPF app with a list box that I am binding to project names. As a decorative element, I want to place a small icon next to each item in the list, similar to the way Outlook does in its Personal Folders list. For starters, I am going to use the same image for all items in the list.
Here is the markup that I've got so far (I'll move it to a resource dictionary after it's working):
<ListBox.Resources>
    <ImageBrush x:Key="ProjectIcon" ImageSource="Images/project.png" />
</ListBox.Resources>
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <Image Source="{StaticResource ProjectIcon}"/>
            <TextBlock Text="{Binding Path=Name}" />
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

I've got an error in the image resource, but I'm not sure how to fix it. Any suggestions? Thanks.
Answer: The Source property of an Image is of type ImageSource not ImageBrush. The following should work:
<ListBox.Resources>
    <BitmapImage x:Key="ProjectIcon" UriSource="Images/project.png" />
</ListBox.Resources>
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <Image Source="{StaticResource ProjectIcon}"/>
            <TextBlock Text="{Binding Path=Name}" />
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>


ASP.NET Identity - Find usuario por e-mail e senha

Question: Estou utilizando pela primeira vez o Asp.Net Identity, junto com o Entity Framework, e para criar um usuário, faço o seguinte código:
var identityUser = new IdentityUser
{
   UserName = viewModel.Nome.Replace(" ", "."),
   Email = viewModel.Email
};

IdentityResult resultado = userManager.Create(identityUser, viewModel.Senha);

Logo, o usuário é livre para inserir seu nome no primeiro campo viewModel.Nome e seu e-mail no segundo viewModel.Email. Para retornar esse usuário no momento de login, utilizo o seguinte código:
var usuario = userManager.Find(viewModel.Nome, viewModel.Senha);

Minha duvida é: É possível buscar o usuário por E-mail, e não por Nome? ou seja, no momento do Find trocar o viewModel.Nome por viewModel.Email?
Comment: Respondendo de forma simples, [sim](https://msdn.microsoft.com/en-us/library/mt151641(v=vs.108).aspx#M:Microsoft.AspNet.Identity.UserManager%602.FindByEmailAsync(System.String)). Ou então, se quiser, a versão [síncrona](https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.usermanagerextensions.findbyemail(v=vs.108).aspx#M:Microsoft.AspNet.Identity.UserManagerExtensions.FindByEmail%60%602(Microsoft.AspNet.Identity.UserManager%7B%60%600,%60%601%7D,System.String)).
Comment: @isaac usei uma abordagem com base no link que você passou, com algumas alterações. Obrigado.
Answer: Problema resolvido. Para tal, recuperei o usuário por e-mail, e logo após fiz o login utilizando seu name, da seguinte forma:
var retorno = userManager.FindByEmail(viewModel.Login);
var usuario = userManager.Find(retorno.UserName, viewModel.Senha);


Vim abbreviation using colon?

Question: I want to do some abbreviations that contain colons, but it doesn't work in vimrc:
ab t:u unsigned

I get a syntax error. I tried \: and \\:\ but it didn't work.
How can I do this?
Answer: This has to do with vim's keyword recognition. Maybe it is a bug or not. Inserting : to the list iskeyword will make the abbreviation of yours possible. But it can cause unexpected side effects navigating your C.
Other possibility is to check snipMate or other similar plugin to provide templates.

Vim abbreviation using colon?


Wordpress doesn't display PAGES link on Dashboard

Question: I have had this site since 2014 and have been updating regularly. All of a sudden, there is no link on the dashboard to access existing pages. They are there (viewable), but there appears to be no way to edit existing pages or to add new pages. Where did the expected link go, and how do I get it back?
Comment: Usually, if you are logged in and are *viewing*  a page, there's an "edit page" link in the black top (admin) bar - did that disappear too? (that would be at least a way to access page edit mode)
Answer: I would suggest re-uploading all the Wordpress core files. I suspect some file is missing or corrupt.
Make sure that all of your file permissions are correct (FTP/SSH).
It is a good idea to disable plugins one by one and switch to a default theme as well and see if the Pages menu item appears in your Wordpress administration. You can find the culprit this way.
PS. Backup the site prior to re-uploading the files.
Comment: How do I re-load the Wordpress core files? Also, why would my file permissions have changed without my knnowing it?
Comment: If your Wordpress install or server has been compromised, malicious files can change other files permissions. You can download the latest (or same) Wordpress version you have and re-upload all files, but the ones related to your theme/custom plugins. Also keep a backup of your wp-config.php fie.


Concatenate values of multiple xml elements into single element using xslt

Question: My source xml file has elements in this form:
<field name="Address1">Address1Value</field>
<field name="Address2">Address2Value</field>
<field name="Address3">Address3Value</field>

I need to merge these into a single element, thus:
<field name="Address">Address1Value\r\nAddress2Value\r\nAddress3Value</field>

I know how to get the value of the Address1 element (as below), I just can't figure out how to augment it with the other two. How can I do this?
<xsl:template match="field[@name = 'Address1']">
    <field>
        <xsl:attribute name="name">Address</xsl:attribute>
        <xsl:value-of select="concat(., 'how-do-I-get-the-values-of-Address2-and-Address-here3?')"/>
    </field>
</xsl:template>

Answer: You can make it a little more generic like this (given the parent of field elements is fields):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="fields">
    <field>
        <xsl:attribute name="name">Address</xsl:attribute>
        <xsl:apply-templates select="node()"/>
    </field>
</xsl:template>
<xsl:template match="field[starts-with(@name, 'Address')]">
    <xsl:value-of select="concat(.,'\r\n')"/></xsl:template>
</xsl:stylesheet>

Answer: I worked it out, like this:
<xsl:value-of select="concat(., ../field[@name = 'Address2'], ../field[@name = 'Address3'])"/>


How to implement per user caching when restricting display of comments by author

Question: I have threaded comments on a site where there are two roles, reviewers and administrators.
Comments are shown in a view block added to the node (in this case a webform). The view format is set to 'content' and it's using tag based caching.

Admins are allowed to see all comments
Reviewers can write comments and only seen their own, or replies to them

This is all ok and I've implemented it with hook_ENTITY_TYPE_view_alter (simplified example below).
The problem is caching - the view for one reviewer is being cached and shown when the other logs on.
Scenario:

Alice and Bob are reviewers
Alice leaves a comment on a node. Logs out.
Bob logs on. If the cache hasn't been cleared in the meantime, he'll see Alice's comments even though he shouldn't. (And then, were I then to clear the cache, his view would be correct, but should he logged off and Alice logs back in, she'll now see the view intended for Bob.)

Can I give each user their own cache,  or failing that, not cache the view at all? (setting caching of the view block to 'none' doesn't appear to change anything, would be useful to know why in answer.)
function mymodule_comment_view_alter(
    &$build,
    Drupal\Core\Entity\EntityInterface $entity,
    \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display ) {

    // ... some logic that deals with admins (omitted)

    $comment_uid    = $entity->getOwnerId();
    $parent_comment = $entity->getParentComment();

    if ( $comment_uid === $current_user->id() ) {
        // current user's own comment? Show it
    } elseif ( isset( $parent_comment ) &&
               $parent_comment->getOwnerId() == $current_user->id() ) {
        // a comment in  reply to current user's comment? Show it
    } else {
        // otherwise, don't show it
        $build['#access'] = false;
    }

    return;
}

Comment: I might be oversimplifying, but wouldn't you just need to add a cache context of `user`?
Comment: @Clive - you're not :) but I'd never heard that term before, I'll go away and read the [API](https://www.drupal.org/docs/8/api/cache-api/cache-contexts) now…
Comment: @Clive - thanks, I understand now. Sorry for not researching more thoroughly before asking.
Answer: As Clive said in the comments, all I needed was the following.
I won't mind if people down vote the question for being too stupid…
// was user.permissions, but that means there will only be a single
// cache shared by all reviewers, and we must cache according to authorship
$build['#cache']['contexts'] = ['user'];

Caveat: the view block cache setting also needs to be 'none'.
Drupal docs - cacheability of render arrays
Comment: This is really a caveat. Disabling Views caching for a comment block will impact performance considerably. Normally Views handles cache contexts correctly, but Views doesn't know about the code you've added to the entity view. So you can try to add a contextual filter for the user so that Views is aware this depends on the current user, even if you don't intend to use this filter because you have your own code.
Comment: I would've fallen in the same pit, I learned from this :)


Changing a differential expression into form $f ' (x, y, z)$

Question: I need to evaluate line integral of
$$(2xy-z) dx + (yz) dy + (x) dz$$
over any path from $(1,0,0)$ to $(2,1,4)$.
I thought of integrating once from $(1,0,0)$ to $(2,0,0)$ then to $(2,1,0)$ and lastly to $(2,1,4)$.
...but that wouldn't necessarily be valid for any path.
I think I need to convert the expression in the form $d(f(x, y, z))$
but I'm being unable to do so.
Comment: That is not a conservative field.  Are you sure the problem is asking for a path-independent solution, or could it be asking you to integrate over any path you so choose?
Comment: @anorton yes.
_F = (2xy−z)i+(yz)j+(x)k_
Evaluate _∫F.dr_ along any path from _(1,0,0)_ to _(2,1,4)_
Answer: Let $C$ be the path of integration, $\mathbf{F}(x,y,z)=(2xy−z,yz,x)$ the vector field, and $d\mathbf{r}=(dx,dy,dz)$ an infinitesimal displacement along $C$.
Choose $C$ to be the line segment from $(1,0,0)$ to $(2,1,4)$. A parametrization for the line is given by $\mathbf{r}(t)=(1,0,0)+t(1,1,4)=(t+1,t,4t)$ for $t \in [0,1]$.
Note that $\mathbf{F}(\mathbf{r}(t))=(2t^2-2t,4t^2,t+1)$ and $\mathbf{r}'(t)=(1,1,4)$. Now we can evaluate the line integral:
$$\int_C \mathbf{F} \cdot d\mathbf{r} = \int_{t=0}^{1} \mathbf{F}(\mathbf{r}(t)) \cdot \mathbf{r}'(t) \,dt = \int_{t=0}^{1} 6t^2+2t+4 \,dt = \left[2t^3+t^2+4t\right]_{t=0}^{1} = 7$$
However, it is to be noted that $\boldsymbol{\nabla}\times\mathbf{F}=(-y,-2,-2x)\ne\mathbf{0}$, so the integral depends on $C$.


Loading prefixed parquet files from s3 - Suspicious paths

Question: I have a set of prefixed (as per S3 performance recommendations) parquet files I want to load in spark (using Amazon EMR 5.11.1) but

the time taken to list the set of files matching the glob is much slower than non-prefixed files, can this be improved?
how can the following error be avoided?

 val df = spark.read.parquet("s3://bucket/????/analytics")

java.lang.AssertionError: assertion failed: Conflicting directory
     structures detected. Suspicious paths:?
        s3://bucket/4a73/analytics
        s3://bucket/8163/analytics

If provided paths are partition directories, please set "basePath" in the options of the data source to specify the root directory of the table. If there are multiple root directories, please load them separately and then union them.
  at scala.Predef$.assert(Predef.scala:170)
  at org.apache.spark.sql.execution.datasources.PartitioningUtils$.parsePartitions(PartitioningUtils.scala:132)
  at org.apache.spark.sql.execution.datasources.PartitioningUtils$.parsePartitions(PartitioningUtils.scala:97)
  at org.apache.spark.sql.execution.datasources.PartitioningAwareFileIndex.inferPartitioning(PartitioningAwareFileIndex.scala:153)
  at org.apache.spark.sql.execution.datasources.InMemoryFileIndex.partitionSpec(InMemoryFileIndex.scala:70)
  at org.apache.spark.sql.execution.datasources.PartitioningAwareFileIndex.partitionSchema(PartitioningAwareFileIndex.scala:50)
  at org.apache.spark.sql.execution.datasources.DataSource.getOrInferFileFormatSchema(DataSource.scala:134)
  at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:353)
  at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:178)
  at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:559)
  at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:543)
  ... 48 elided

Comment: I think it is recommended to use hash prefixes in S3 object keys if you are expecting loads over 100 queries/second. It would indeed be much easier to have single path from where to read all the parquet files, e.g. `s3://bucket/analytics`. If you aren't truly over 100 QPS, you may want to reconsider your directory structure, unless there is another requirement for it?
Answer: Instead of s3 you can use the s3a.
This may be work out for you.
1.You'll also need the hadoop-aws 2.7.1 JAR on the classpath.
This JAR contains the
class org.apache.hadoop.fs.s3a.S3AFileSystem.

2.In spark.properties you can  some settings  like this:
spark.hadoop.fs.s3a.access.key=ACCESSKEY
spark.hadoop.fs.s3a.secret.key=SECRETKEY

Comment: On Amazon EMR s3:// is the binding to Amazon's own (closed source) connector. I believe its the only one whay support.
Comment: This might help with the performance, although I suspect not with the error message above.


Bootstrap form alignment

Question: So well, I am having a bit of a problem with the form alignment. I tried it on 2 different files, one that gave the correct alignment and one that did not(which is the view of codeigniter). Please help. Thanks in advance :)
The file in the view of CI with its screenshot is below

<?php $tab = (isset($_GET['tab'])) ? $_GET['tab'] : 'add-user'; ?>

                          <li class="<?php echo ($tab == 'add-user') ? 'active' : ''; ?>"><a href="<?php echo site_url('/home/add_user?tab=add-user'); ?>"> Add User

                          <li class="<?php echo ($tab == 'update-user') ? 'active' : ''; ?>"><a href="<?php echo site_url('/home/add_user?tab=update-user'); ?>">Update User

                          <li class="<?php echo ($tab == 'delete-user') ? 'active' : ''; ?>"><a href="<?php echo site_url('/home/add_user?tab=update-user'); ?>">Delete User

                          <li class="<?php echo ($tab == 'view-user') ? 'active' : ''; ?>"><a href="<?php echo site_url('/home/add_user?tab=update-user'); ?>">View Users

                          <li class="<?php echo ($tab == 'generate-account') ? 'active' : ''; ?>"><a href="<?php echo site_url('/home/add_user?tab=generate-account'); ?>">Generate User Account

                      <div id="add-user" class="tab-pane <?php echo ($tab == 'add-user') ? 'active fade in' : ''; ?>">
                            <?php $this->load->library('form_validation');
                            echo validation_errors(); ?>
                            <?php echo form_open('crud_user/add_form');?>

                            <fieldset>
                              <legend>ADD</legend>
                                  <form class="form-horizontal" ame="add_user_form" form="add_form">
                                  <fieldset>

                                  <legend>Add User</legend>

                                      Employee ID

                                            <input type="text" name="emp_id" id="emp_id" placeholder="Employee ID" class="form-control input-md">

                                      First Name

                                          <input type="text" name="firstname" id="firstname" placeholder="First Name" class="form-control input-md">

                                      Select Basic

                                          <select id="selectbasic" name="selectbasic" class="form-control">
                                              <option value="1">Option one</option>
                                              <option value="2">Option two</option>
                                            </select>

                                </fieldset>
                             </form>

                    <div id="update-user" class="tab-pane <?php echo ($tab == 'update-user') ? 'active fade in' : ''; ?>">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis maximus ex.

                 <div id="generate-account" class="tab-pane <?php echo ($tab == 'generate-account') ? 'active fade in' : ''; ?>">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis maximus ex.

Alignment messed
The snippet from the test file with its screenshot is below

           Add User

                          <form class="form-horizontal">
                          <fieldset>

                             <legend>Add User</legend>

                                  Employee ID

                                        <input type="text" name="emp_id" id="emp_id" placeholder="Employee ID" class="form-control input-md">

                                  First Name

                                      <input type="text" name="firstname" id="firstname" placeholder="First Name" class="form-control input-md">

                                  Select Basic

                                      <select id="selectbasic" name="selectbasic" class="form-control">
                                          <option value="1">Option one</option>
                                          <option value="2">Option two</option>
                                        </select>

       </fieldset>
     </form>

Bootstrap form with proper alignment
Comment: Not really A codeigniter issue more bootstrap, css
Comment: @wolfgang1983 Yes I agree and I have hence removed codeigniter from the question title as well as the tag. Please do suggest if you have a solution to this. :)
Answer: Try adding the class 'row' to each
 .  IIRC from bootstrap the col classes work better in a row container.
Comment: Yes @James, you're right about that. I had tried this out and it is the perfect way to go about it. I was just not kind of sure why it behaved differently in both the cases. Thanks for the reply by the way. :)
Comment: No worries. I think (but not sure) that the col classes need to be in a row element in order to 'work' correctly.

Bootstrap form alignment


Swift IBDesignables and character spacing (kerning)

Question: I can successfully implement a variation on the following code (/function) via viewDidLoad(), however, I would like to integrate it into an IBDesignable, as is set out below.
@IBDesignable
class kernedLabel: UILabel {

  @IBInspectable var spacing: CGFloat = 10.4

  override func draw(_ rect: CGRect) {
    changeSpacing()
  }

  func changeSpacing(){
    let stringValue=text ?? ""
    let attrString = NSMutableAttributedString(string: stringValue)
    attrString.addAttribute(NSAttributedStringKey.kern, value: spacing, range: NSMakeRange(0, attrString.length))
    self.attributedText=attrString
  }
}

I am almost certain that the reason for failure stems from calling the function within
override func draw(_ rect: CGRect) {}

However, having unsuccessfully spent a number of hours searching for alternatives I am hoping someone is able to offer advice, or a push in the right direction.
Comment: What is the question or problem?
Comment: @Willeke when implemented as set out above it has no effect, I'm hoping for some hints/advice on how to better approach/fix the task.
Answer: I think the correct way is to setup the kern when the spacing/text is changed no matter from where(storyboard or code). The draw method will not execute if you change something from storyboard so you will not see any change. Below is the proper way to achieve your goal.
@IBDesignable
class KernedLabel: UILabel {

    @IBInspectable public var spacing: CGFloat = 0.0 {
        didSet {
            applyKerning()
        }
    }

    override var text: String? {
        didSet {
            applyKerning()
        }
    }

    private func applyKerning() {
        let stringValue = self.text ?? ""
        let attrString = NSMutableAttributedString(string: stringValue)
        attrString.addAttribute(NSAttributedStringKey.kern, value: spacing, range: NSMakeRange(0, attrString.length))
        self.attributedText = attrString
    }
}


How To Authenticate In Symfony2 Using Two Different Tables

Question: I have two tables in this project of mine. One table is for the site admin which stores all the admin users details, and the other table stores all the login data for clients to the site.
At the moment, I can log in using the admin details fine. However, I am now trying to login with the client details and it doesn't seem to be working. So far, when a user clicks on a link it will go to /clientarea/login. This page loads up fine. But when I try to log in I get an error.
The error I am getting is this:

Unable to find the controller for path "/clientarea/login_check". Maybe you forgot to add the matching route in your routing configuration?

In my security.yml file, I have the following code: (By the way, I'm using plaintext for development only, it will be changed when it goes live):
providers:
    admin_db:
        entity: { class: Shout\AdminBundle\Entity\User, property: username }
    client_db:
        entity: { class: Shout\AdminBundle\Entity\Userclients, property: username }

encoders:
    Shout\AdminBundle\Entity\User:
        algorithm: plaintext
    Shout\AdminBundle\Entity\Userclients:
        algorithm: plaintext

firewalls:
    secured_area:
        pattern: ^/
        anonymous: ~
        provider: admin_db
        form_login:
            check_path: /login_check
            login_path: /login
        logout:
            path:   /logout
            target: /index
    client_area:
        pattern: ^/
        anonymous: ~
        provider: client_db
        form_login:
            check_path: /clientarea/login_check
            login_path: /clientarea/login
        logout:
            path:   /clientarea/logout
            target: /index

access_control:
    - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/clientarea/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/clientarea, roles: ROLE_USER }

In my routing.yml I have this code:
login:
    pattern:   /login
    defaults:  { _controller: ShoutAdminBundle:Security:login }

    login_check:
        pattern:   /login_check

    logout:
        pattern:   /logout

    clientlogin:
        pattern:   /clientarea/login
        defaults:  { _controller: ShoutAdminBundle:Security:clientlogin }

    clientlogin_check:
        pattern:   /clientarea/login_check

    clientlogout:
        pattern:   /clientarea/logout

Here is the code in the controller. The code is identical for the login and clientlogin functions, the only thing that is different is the twig file they point to:
$request = $this->getRequest();
$session = $request->getSession();

// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
    $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
    $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
}

return $this->render('ShoutAdminBundle:Security:clientlogin.html.twig', array(
    // last username entered by the user
    'last_username' => $session->get(SecurityContext::LAST_USERNAME),
    'error'         => $error,
));

The action path of the Client Login form points to clientlogin_check.
What am I doing wrong?
Answer: I've managed to get it working, but in a very basic way. I don't have time due to a deadline to make the login pages pretty looking.
But here is the code:
    client_area:
        pattern: ^/clientarea
        anonymous: ~
        provider: client_db
        http_basic:
            realm: "Secured Client Area"

Basically, you can have users from more than one table. However, I have still been unable to make it work using a proper login form. But the basic HTTP login box works just as well for what I'm doing.


How do I stop IE6 clipping an element positioned outside its parent via negative margins?

Question: I have an element positioned outisde its parent via negative margins, like this:

...

Element

In Internet Explorer 6, the part of .element positioned outside of its parent element is clipped, i.e. invisible, hidden, cut off. How do I fix this?
Answer: Assign position: relative; to .element, like this:

...

Element

This is only necessary if the parent element hasLayout (which is too big a can of worms to get into here).
Comment: Awesome i've been struggling with this issue for days!!! finally got a fix that works :)
Comment: Interesting. I've had this problem several times before and indeed spent hours trying various changes in the CSS to no avail. This seems to do the trick.
Answer:

Comment: That doesn't seem to fix the issue. I think `height: 1%` should force hasLayout on `.parent` anyway; you shouldn't need `zoom: 1` as well.
Answer: This happens with negative margins combined with floats in IE6.
If you can, get rid of the float:

.element {
   float: none:
   zoom: 1;
}


Does the equality $\partial^\alpha(x^\alpha)(0)=\alpha!$ hold?

Question: Do we have $\partial^\alpha(x^\beta)(0)=\alpha!=\beta!$ if $\alpha=\beta$ and $0$ else?
I tried to proof it on induction, can include my attempts if needed, but they seem to have failed anyway...
Comment: @charlotte Yes, where $\alpha$ is a vector in ${\bf N}^n$ and our ambient space is ${\bf R}^n$.
Comment: By $\partial ^\alpha$, you mean the $\alpha$-th derivative, right?
Comment: @Cameron yes, this gave me the idea to the result, but then I tried to prove it by double induction on $\alpha,\beta$ (fix $\alpha,\beta$ and assume it holds for all $\alpha',\beta'$ with either $|\beta'|<|\beta|$ or $|\beta'|=|\beta|$ and $|\alpha'|<|\alpha|$ but as I wrote above, I couldn't get through...
Answer: This is correct. The easiest way to do it is to separate the partial derivatives accordingly. Write $x = (x_1,\ldots,x_n)$ and $\alpha = (\alpha_1,\ldots, \alpha_n)$, then $\partial^{\alpha} = \partial_{x_1}^{\alpha_1}\cdots\partial_{x_n}^{\alpha_n}$. From this it isn't hard to see that you need only to consider the one-dimensional case since $x^{\alpha} = x_1^{\alpha_1}\cdots x_n^{\alpha_n}$ and the partial derivatives commute. If you are unsure, note that
$$\partial^{\alpha} x^{\beta} = (\partial_{x_1}^{\alpha_1}\cdots \partial_{x_n}^{\alpha_n})(x_1^{\beta_1}\cdots x_n^{\beta_n}) = (\partial_{x_1}^{\alpha_1}(x_1^{\beta_1}))\cdots (\partial_{x_n}^{\alpha_n}(x_n^{\beta_n})).$$
Reducing ourselves to computing $\partial_{x_i}^{\alpha_i}(x_i^{\beta_i})$ greatly simplifies the problem at hand. Computing this, we have
$$\partial_{x_i}^{\alpha_i}(x_i^{\beta_i}) = \begin{cases} \dfrac{\beta_i!}{(\beta_i-\alpha_i)!}x^{\beta_i-\alpha_i} & \beta_i \ge \alpha_i \\ 0 & \beta_i < \alpha_i \end{cases}. $$
Taking $\beta_i = \alpha_i$, we get that $\partial_{x_i}^{\alpha_i}(x_i^{\beta_i})(0) = \alpha_i! = \beta_i!$ if $\alpha_i=\beta_i$ and $0$ otherwise. By definition, $\alpha! = \alpha_1!\cdots\alpha_n!$ so the result follows.
Comment: Very quick and elegant, thanks a lot!
Comment: No problem! Glad to help.


visual studio post-build script error calling gacutil

Question: I'm on vista, with VS2005 running as admin.  Both vs2005 and vs2008 are installed.  If I explicitly use the path to gacutil, it works, but not if I only call gacutil like this:
<code>if NOT $(ConfigurationName) == Release gacutil /f /i "$(TargetPath)"
</code>
I would just update the post-build script, but I've been asked to leave it alone.  It's a project for a sister company.  The path to gacutil is in Visual Studio environment variables, so it should be able to find it.  (Tools -> Options -> Projects and Solutions -> VC++ Directories)
Is there some way to tweak visual studio or windows environment variable to get the above post-build script to work?  I need to it to build, because it's a dependency of a project I need to code.
TIA, -j
Comment: How are you using the build? Are you using msbuild or calling devenv from the command line or are you building this right in the IDE?
Answer: As you suggest, tweaking the Windows PATH environment variable should get things working.
append the directory that contains GACUTIL to the end of the PATH. For example, using the location on my computer, append (without the quotes) ";C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin" to the existing value of the PATH system environment variable.
Restart Visual Studio to pick up the new value.
Dave


GCD of {0} in integral domains

Question: Quoting Hungerford's Algebra:

A nonzero element $a$ of a commutative ring $R$ is said to divide an element $b \in R$ (notation: $a \mid b$) if there exists $x \in R$ such that $ax = b$.
Let $X$ be a nonempty subset of a commutative ring $R$. An element $d \in R$ is a greatest common divisor of $X$ provided:

$d \mid a$ for all $a \in X$;
$c \mid a$ for all $a \in X$ $\implies$ $c \mid d$.

In particular, the greatest common divisor (from now on I use "gcd") of any nonempty subset of a commutative ring $R$ must be a nonzero element of $R$ (else, writing $d \mid a$ would make no sense). Now what's the gcd of $\{0\}$ in an integral domain? Condition 1 is satisfied by every element $d \in R$. In fact, given $d \in R$, we have that $d0 = 0$ for all $d \in R$, hence $d \mid 0$ by definition. What can we deduce from condition 2?
Answer: Since every element $c \in R$ satisfies the condition $\forall a \in X:c\vert a $, condition 2 tells us that $d \in R$ needs to be an element such that $\forall c \in R: c \vert d$. There exists only one such element in $R$.
 Also, the first statement after the definition is false. In fact, it is precisely what answers your question.
According to the definition of Hungerford, a GCD of a subset is indeed defined to be non-zero since a divisor is defined to be non-zero. That given, it is sensible to simply define the GCD of $\{0\}$ as $0$. Note, however, that the definition varies among authors as is also mentioned here.
Comment: The first statement after the definition is false. Why? By definition the gcd divides every element of $X$, thus by the previous definition the gcd must be a nonzero element. Where am I wrong?
Comment: @Lele99_DD The nonempty subset $\{0\}$ is precisely the only exception for that statement. In that case $d \vert a$ i.e. $0 \vert 0$ makes sense since $1 \cdot 0 = 0$.
Comment: So the solution is that the definition provided by Hungerford works for every nonempty subset $X \neq \{0\}$, whereas we define the greatest common divisor of $\{0\}$ to be $0$? Just a matter of definitions?
Comment: @Lele99_DD No,no, it's not a matter of definition. The GCD of $\{0\}$ is not defined to be $0$ - there is a proof for it: 1. $\forall a \in X: 0 \vert a$ since $0 \vert 0$ since there exists a $c \in R$ such that $c\cdot 0 = 0$ for examples $c = 1$. 2. for any $c \in R$ s.t. $c \vert 0$ (which is true for any $c \in R$) we have $c \vert 0$ since $0 \cdot c = 0$. Hence $0$ is the GCD of $\{0\}$.
Comment: Following Hungerford's definition of divisibility, writing $0 \mid a$ makes no sense because "a nonzero element $a$ of a commutative ring $R$ is said to divide". I guess what you're trying to say is true only if we use different definitions and I'd prefer to stick with Hungerford's.
Comment: @Lele99_DD Ah yes, I didn't catch, my mistake. Yes, if Hungerfords definition is used, then one has to define $0$ to be the GCD of $\{0\}$.

GCD of {0} in integral domains


Como passar variáveis "invisíveis" de uma página para outra usando um link no Django?

Question: Imagine que eu tenha o seguinte código no urls.py;
url(r'^relatorio', views.relatorioView, name='relatorio'), url(r'^relatorio/grafico', views.graph, name='grafico'),
Na página relatório eu tenho uma tabela com nomes e códigos de itens.
Como eu posso fazer um link que redirecione para a página do gráfico daquele determinado item sem deixar o código explícito na url?
Answer: Você pode fazer um POST, e enviar os dados para a outra view. Ela faz a query set e retorna uma resposta, mas como você enviou por POST, os identificadores não vão aparecer na url. Mas você tem que estar preparado para um solicitação get, na mesma view, nessa caso, você pode redirecionar o usuário para outra parte do site.
Isso você pode fazer com funcition views assim(isso está nessa documentação):
    if request.method == 'GET':
        do_something()
    elif request.method == 'POST':
       do_something_else()

Com classes, você usaria os métodos apropriados para cada tipo de requisição.
Para pegar o valor passado pro POST, você pode fazer:
request.POST['chave-do-valor']

Use um form, para enviar os dados, você deve especificar o enctype. Para o código acima funcionar.
<form action="/view-url" method="post" enctype="multipart/form-data">


Arranging angle measurements in ascending order

Question: Arrange the following assortment of angle measures in ascending order; 210°, 350°, 2π, 5.3 radians, 90°, 1.7 radians, π/3 , 1 radian, 55°, π.
I only just started learning about angle measurements and so I'm struggling with this question. How would I correctly place them in ascending order? Any help is appreciated.
Comment: If you know that there are $2\pi$ radians for $360^{\circ}$, then how many radians in $1^\circ$?  How do you compare measures that are in different units?
Comment: To point you in a similar direction, which is longer, $2$ inches, or $5$ centimetres?  $0.97$ miles, or $1450$ metres?
Comment: What do you know about the constant of proportionality between degrees and radians?
Comment: I was taught that 2π radians = 360°, π radians = 180°, and 1 radian = 57.295.. = 60°.
Answer: Four angles are in degrees: 210,350,90,55. Three are in radians: 5.3,1.7,1. Another three are also in radians but expressed in terms of $\pi$.
So you need to convert them all to some common unit, say radians. Thus multiply each of the degree values by $\pi/180$ and use $\pi=3.1416$ to convert the multiples of $\pi$. Then you should be able to see the correct order.
Comment: @Savannah Yes! Well done.
Comment: Would the answer be 2π, 350°, 5.3 radians, 210°, π, 1.7 radians, 90°,π/3 , 1 radian, 55° ?


Continuous function, not on reals: each value twice?

Question: The non-existence of continuous functions on $\mathbb{R}$ which attain each value in their range exactly twice has been raised numerous times, yet I cannot find (either here or elsewhere) analogous theorems for $\mathbb{R}^n$ or other metric/topological spaces.
All I can observe is that on $\mathbb{C}-\{0\}$, a counterexample would be $f(z)=z^2$, but I do not know what to say if the origin is added back.
Comment: I think you can show that if $f:X\to X$ is surjective, continuous and $f^{-1}(x)$ is finite for each $x$ then $f$ is a covering map. If that's the case then the answer for $\mathbb{C}$ is positive (i.e. there is no counterexample) because it is simply connected. And being simply connected would be the property you are looking for.
Comment: @freakish You would need a local homeomorphism assumption which is not necessarily a consequence of those you listed here, if I'm not mistaken.
Answer: Assume that you have a map $\mathbb{R}^n\to Y$ for some topological space $Y$, such that $|f^{-1}(y)|=2$ for all $y\in Y$.
I'll consider the particular case where you make the additional assumption:
The map $f$ is "nice" in the sense that for all $y\in Y$, the two elements of $f^{-1}(y)$ are distant by more than some absolute constant $\varepsilon> 0$.
Then, consider $x\in \mathbb{R}^n$ and the restriction of $f$ to the open ball $B(x,\frac{\varepsilon}{2})$. Since bounded closed subsets of $\mathbb{R}^n$ are compact, this restriction is a closed map. It is also continuous and bijective onto its range, therefore it is a homeomorphism onto its range. It follows that $f$ is a covering map.
Now since $\mathbb{R}^n$ is simply connected, $f$ is a universal cover of $Y$, and since the fiber has two elements, it follows that $$\pi_1(Y)\simeq \mathbb{Z}_2$$
So there you are, under a pretty reasonable restriction on $f$, you see that the target space needs to have a very particular topology - it can't be $\mathbb{R}^n$ itself for instance.


Intuition behind derivatives of linear forms

Question: In my machine learning course, we're kicking off by revising some concepts from linear algebra and calculus. The instructor has introduced the notion of linear forms, i.e. a function $$f:\mathbb{R}^p \rightarrow \mathbb{R}^n, f(\underline{s})=A \underline{s} $$
where $\underline{s}$ is a $p \text{ x } 1$ vector and $A$ is a $n \text{ x } p$ matrix of real numbers.
The instructor has said that $$\frac{\partial f}{\partial s}=A $$
I am having trouble wrapping my head around this concept, but am willing to take it on faith. I give an example to better illustrate my lack of understanding.
Consider $$A=\begin{pmatrix}
1 & 2\\
2 & 1
\end{pmatrix},\underline{s}=\begin{pmatrix}
s_1\\
s_2
\end{pmatrix} $$
Then here $$f(\underline{s})=\begin{pmatrix}
s_1+2s_2\\
2s_1+s_2
\end{pmatrix} $$
From here, how do we obtain that $$\frac{\partial f}{\partial s}= \begin{pmatrix}
1 & 2\\
2 & 1
\end{pmatrix} $$
I.e. what steps do we follow to go from our $2$ x $1$ vector to our $2$ x $2$ matrix?
Comment: The intuition for derivatives/differentials of some function $f$ in general is that they are the "best" linear approximation of $f$. When $f$ itself is linear, then it is its own best linear approximation. In the case of maps between vector spaces, the differential is represented by the Jacobian (at points where the function is differentiable).
Comment: I've also had difficulty wrapping my head around this. I prefer calculating directional derivatives. Consider any smooth function $f: \mathbb{R}^p \rightarrow \mathbb{R}^n$. Given any vector $v$, the directional derivative of $f$ at $s$ in the direction $v$ is $$D_vf(s) = \left.\frac{d}{dt}\right|_{t=0} f(s(t)), $$ which is a vector. This is a linear function of $v$ and therefore there is a matrix $M$ (depending on $f$ and $s$) such that $$D_vf(s) = Mv.$$ The matrix $M$ is what your professor is calling $$\frac{\partial f}{\partial s}$$
Comment: Don't take it on faith. Just compute the derivatives and see for yourself that what you get is that.
Answer: The derivative is a linear approximation of a function. Using the notation of your question (which I consider not too appropriate, but it will do), this means that in a given point $s_0$ there is a linear map (denoted by $\frac{\partial f(s_0)}{\partial s}$) such that
$$f( s_0 + h)= f(s_0) + \frac{\partial f(s_0)}{\partial s}h + g(|h|)$$
where $g$ is a function which is decreasing fast to $0$ in the sense that even $g(|h|)/|h|$ converges to $0$ if $h$ does. This $g$ ensures that there is at most one map $\frac{\partial f}{\partial s}$ with that property and that that choice is, in a very precise sense, the optimal linear approximation of $f$.
The term $\frac{\partial f(s_0)}{\partial s}h $ is meant to mean applying the linear map $\frac{\partial f(s_0)}{\partial s} $ (which you can think of as a matrix) to the vector $h$.
Now if you take $f(s) = As$ for some matrix $A$ (i.e. $s\mapsto As$ is linear), this reduces to
$$ A(s_0 + h) = As_0 + Ah = As_0 + \frac{\partial f(s_0)}{\partial s}h + g(|h|)$$
This is, obviously, fulfilled, with $g\equiv 0$, if you choose $\frac{\partial f(s_0)}{\partial s}=A$, and this just means that the best linear approximation of a linear map is that same linear map.
Answer: If we have a linear function $f:\mathbb R^2\to \mathbb R^2$, we can represent the function by a matrix $$\begin{pmatrix}a&b\\c&d\end{pmatrix}$$ and write $$f(x_1,x_2)=\begin{pmatrix}a&b\\c&d\end{pmatrix}\begin{pmatrix}x_1\\x_2\end{pmatrix}=\begin{pmatrix}ax_1+bx_2\\cx_1+dx_2\end{pmatrix}=\begin{pmatrix}y_1\\y_2\end{pmatrix}$$ which gives us two coordinate functions $$y_1=ax_1+bx_2\\y_2=cx_1+dx_2$$
To differentiate a function like $f$ we form the matrix consisting of the gradient of each coordinate function in its corresponding row. This gives $$Df=\begin{pmatrix}\frac{\partial y_1}{\partial x_1}&\frac{\partial y_1}{\partial x_2}\\\frac{\partial y_2}{\partial x_1}&\frac{\partial y_2}{\partial x_2}\end{pmatrix}=\begin{pmatrix}a&b\\c&d\end{pmatrix}$$