text:
Q: Asserting that a parent component exists in angular unit test I have a top level component AppComponent and in it's template property it renders the <child> element on the page. (<child> is another Angular component).
Do I need to tell the unit test to ignore the <child> element or declare it in some way for the test?
I'm not actually trying to test <child> in this test file, I will create a separate unit test file to validate it's functionality.
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ChildComponent } from './child.component';

@NgModule({
  bootstrap: [AppComponent],
  declarations: [AppComponent, ChildComponent],
  imports: [BrowserModule]
})
export class AppModule { }

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app',
  template: '<child></child>'
})
export class AppComponent { }

child.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: './child.component.html'
})
export class ChildComponent { }

app.component.spec.ts
import { async, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { ChildComponent } from './child.component';

describe('App', (() => {
  beforeEach(async() => {
    TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] }).compileComponents();
  }));
  it('should work', () => {
    let fixture = TestBed.createComponent(AppComponent);
    // assert app.component exists
  });
});

When I run the unit test, I'm getting this error:
Error: This test module uses the component ChildComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test. in /tmp/karma-typescript-bundle-3142O76A6m7KjQOD.js (line 3929)

A: The error indicates that other units (ChildComponent) are involved in test. This error is caused by the fact that ChildComponent uses templateUrl, and such components may need to call compileComponents to compile them.
Since AppComponent has template and not templateUrl, this makes a test synchronous and makes async helper unnecessary, also eliminates the need to use compileComponents.
As explained in the guide,

The TestBed.compileComponents method asynchronously compiles all the components configured in the testing module. In this example, the BannerComponent is the only component to compile. When compileComponents completes, the external templates and css files have been "inlined" and TestBed.createComponent can create new instances of BannerComponent synchronously.

Unit test presumes that only one unit is tested, while other units are ignored, stubbed or mocked. This allows to keep a test isolated.
Since undeclared components will result in error, they have to be stubbed:
  beforeEach(() => {
    @Component({ selector: 'child', template: '' })
    class DummyChildComponent {}

    TestBed.configureTestingModule({ declarations: [AppComponent, DummyChildComponent] });
  });

An alternative to dummy component is CUSTOM_ELEMENTS_SCHEMA or NO_ERRORS_SCHEMA, which aren't suitable in tests because any possible error output may be valuable. And custom schema is more heavy-weight solution.

A: You need to add the ChildComponent to your module:
  beforeEach(() => {
    TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] });
  });


text:
Q: MVVMCross Nested Recyclerview Out of Memory Issue I have tried to create nested recyclerview in combination with the mvvmcross-framework which actually worked quite easily, but now I'm getting out of memory exceptions.
Scenario
I have a list of around 3000 entries with complex and long names, which are divided by 8 categories. The user can select the entries via a checkbox to assign them to a task later on.
Even if it might sound like there are too many entries, it is actually quite easily to navigate through them, if the user has some background knowledge, so I would rather not change it at this point.
Code
First the simplified data models for the categories and the entries (channels):
    public class ChannelCategory
{
    public ChannelCategory(String sName)
    {
        Name = sName;
        Channels = new List<Channel>();
    }

    public string Name { get; set; }
    public List<Channel> Channels { get; set; }
}

    public class Channel
{
    public string Name { get; protected set;
    public bool Selected { get; set; }

    public Channel(String sName)
    {
        Name = sName;
        Selected = false;
    }
}

And then the axml files which are just getting mapped by MVVMCross:
fragment_channels.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:iconifiedByDefault="false"
        local:MvxBind="Query SearchString" />
    <MvxRecyclerView
        android:id="@+id/lvChannelList"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="vertical"
        android:cacheColorHint="#00000000"
        android:choiceMode="singleChoice"
        local:MvxItemTemplate="@layout/listitem_channelcategory"
        local:MvxBind="ItemsSource Categories" />
</LinearLayout>

listitem_channelcategory.axml
 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/roundborder">
    <CheckBox
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:layout_gravity="center_horizontal"
        android:layout_marginRight="5dp"
        android:padding="10dp"
        android:textColor="@color/black"
        android:textStyle="bold"
        local:MvxBind="Text (Name+Channels.Count)" />
  <MvxRecyclerView
      android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:cacheColorHint="#00000000"
        android:choiceMode="singleChoice"
        local:MvxItemTemplate="@layout/listitem_channel"
        local:MvxBind="ItemsSource Channels" />
</LinearLayout>

listitem_channel.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/roundborder">
    <CheckBox
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:layout_gravity="center_horizontal"
        android:layout_marginRight="5dp"
        android:padding="10dp"
        android:textColor="@color/black"
        local:MvxBind="Text Name; Checked Selected" />
</LinearLayout>

Issue
So basically I have a ViewModel, which is assigned to a view (fragment_channels) displays a list of categories (listitem_categories), where each categorie displays a list of channels (listitem_channels). Everything handled with the MVVMCross-Framework. It works fine, until I scroll scroll down to another categorie, then it just freezes for a while and after a few times it crashes with an out of memory exception. Atm I can delay it by giving the inner recyclerviews a fixed size.
Does anyone have an idea what I could change or what am I doing wrong? Maybe I shouldn't just a nested recyclerview, but the handling to this point was really easy and intuitive.
MVVMCross Android Support Version and Co is 4.1.5, Xamarin Android Support Library is 23.3.0
StackTrace
04-22 12:17:23.207 I/MonoDroid( 7556): UNHANDLED EXCEPTION:
04-22 12:17:23.217 I/MonoDroid( 7556): Java.Lang.OutOfMemoryError: Failed to allocate a 36876 byte allocation with 14092 free bytes and 13KB until OOM
04-22 12:17:23.227 I/MonoDroid( 7556):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3053/a94a03b5/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
04-22 12:17:23.227 I/MonoDroid( 7556):   at Android.Runtime.JNIEnv.CallObjectMethod (IntPtr jobject, IntPtr jmethod, Android.Runtime.JValue* parms) [0x00064] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:195
04-22 12:17:23.227 I/MonoDroid( 7556):   at Android.Views.LayoutInflater+IFactory2Invoker.OnCreateView (Android.Views.View parent, System.String name, Android.Content.Context context, IAttributeSet attrs) [0x0008c] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/platforms/android-23/src/generated/Android.Views.LayoutInflater.cs:185
04-22 12:17:23.227 I/MonoDroid( 7556):   at MvvmCross.Binding.Droid.Views.MvxLayoutInflater+DelegateFactory2.OnCreateView (Android.Views.View parent, System.String name, Android.Content.Context context, IAttributeSet attrs) [0x00020] in <filename unknown>:0
04-22 12:17:23.227 I/MonoDroid( 7556):   at MvvmCross.Binding.Droid.Binders.MvxLayoutInflaterCompat+FactoryWrapper2.OnCreateView (Android.Views.View parent, System.String name, Android.Content.Context context, IAttributeSet attrs) [0x00000] in <filename unknown>:0
04-22 12:17:23.227 I/MonoDroid( 7556):   at Android.Views.LayoutInflater+IFactory2Invoker.n_OnCreateView_Landroid_view_View_Ljava_lang_String_Landroid_content_Context_Landroid_util_AttributeSet_ (IntPtr jnienv, IntPtr native__this, IntPtr native_parent, IntPtr native_name, IntPtr native_context, IntPtr native_attrs) [0x0002c] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/platforms/android-23/src/generated/Android.Views.LayoutInflater.cs:169
04-22 12:17:23.227 I/MonoDroid( 7556):   at (wrapper dynamic-method) System.Object:bafdfe11-a146-4499-92d6-ece4428264a4 (intptr,intptr,intptr,intptr,intptr,intptr)
04-22 12:17:23.237 I/MonoDroid( 7556):   --- End of managed exception stack trace ---
04-22 12:17:23.237 I/MonoDroid( 7556): java.lang.OutOfMemoryError: Failed to allocate a 36876 byte allocation with 14092 free bytes and 13KB until OOM
04-22 12:17:23.237 I/MonoDroid( 7556):  at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:726)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:547)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:575)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:605)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.drawable.BitmapDrawable.updateStateFromTypedArray(BitmapDrawable.java:759)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.drawable.BitmapDrawable.inflate(BitmapDrawable.java:726)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1150)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.drawable.AnimatedStateListDrawable.parseItem(AnimatedStateListDrawable.java:493)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.drawable.AnimatedStateListDrawable.inflate(AnimatedStateListDrawable.java:396)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1150)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.graphics.drawable.Drawable.createFromXml(Drawable.java:1063)
04-22 12:17:23.237 I/MonoDroid( 7556):  at android.content.res.Resources.loadDrawableForCookie(Resources.java:3719)
04-22 12:17:23.247 I/MonoDroid( 7556):  at android.content.res.Resources.loadDrawable(Resources.java:3603)
04-22 12:17:23.247 I/MonoDroid( 7556):  at android.content.res.TypedArray.getDrawable(TypedArray.java:762)
04-22 12:17:23.247 I/MonoDroid( 7556):  at android.widget.CompoundButton.<init>(CompoundButton.java:89)
04-22 12:17:23.247 I/MonoDroid( 7556):  at android.widget.CheckBox.<init>(CheckBox.java:72)
04-22 12:17:23.247 I/MonoDroid( 7556):  at android.widget.CheckBox.<init>(CheckBox.java:68)
04-22 12:17:23.247 I/MonoDroid( 7556):  at android.support.v7.widget.AppCompatCheckBox.<init>(AppCompatCheckBox.java:58)
04-22 12:17:23.247 I/MonoDroid( 7556):  at android.support.v7.widget.AppCompatCheckBox.<init>(AppCompatCheckBox.java:54)
04-22 12:17:23.247 I/MonoDroid( 7556):  at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:117)
04-22 12:17:23.247 I/MonoDroid( 7556):  at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:972)
04-22 12:17:23.247 I/MonoDroid( 7556):  at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:1030)
04-22 12:17:23.257 I/MonoDroid( 7556):  at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
04-22 12:17:23.257 I/MonoDroid( 7556):  at md59292f1b7dcad9ff99bb047144087b6e8.MvxLayoutInflaterCompat_FactoryWrapper2.n_onCreateView(Native Method)
04-22 12:17:23.257 I/MonoDroid( 7556):  at md59292f1b7dcad9ff99bb047144087b6e8.MvxLayoutInflaterCompat_FactoryWrapper2.onCreateView(MvxLayoutInflaterCompat_FactoryWrapper2.java:31)
04-22 12:17:23.257 I/MonoDroid( 7556):  at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:181)
04-22 12:17:23.257 I/MonoDroid( 7556):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:732)
04-22 12:17:23.257 I/MonoDroid( 7556):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
04-22 12:17:23.257 I/MonoDroid( 7556):  at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
04-22 12:17:23.267 I/MonoDroid( 7556):  at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
04-22 12:17:23.267 I/MonoDroid( 7556):  at md53ffd798107a36773482afea9a9f07756.MvxRecyclerAdapter.n_onCreateViewHolder(Native Method)
04-22 12:17:23.267 I/MonoDroid( 7556):  at md53ffd798107a36773482afea9a9f07756.MvxRecyclerAdapter.onCreateViewHolder(MvxRecyclerAdapter.java:49)
04-22 12:17:23.267 I/MonoDroid( 7556):  at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5482)
04-22 12:17:23.267 I/MonoDroid( 7556):  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4707)
04-22 12:17:23.267 I/MonoDroid( 7556):  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617)
04-22 12:17:23.267 I/MonoDroid( 7556):  at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1994)
04-22 12:17:23.267 I/MonoDroid( 7556):  at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1390)
04-22 12:17:23.267 I/MonoDroid( 7556):  at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1353)
04-22 12:17:23.267 I/MonoDroid( 7556):  at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574)
04-22 12:17:23.267 I/MonoDroid( 7556):  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2625)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.view.View.measure(View.java:18596)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.view.View.measure(View.java:18596)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:7487)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1416)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1353)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1180)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.support.v7.widget.LinearLayoutManager.scrollVerticallyBy(LinearLayoutManager.java:1031)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.support.v7.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:4061)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
04-22 12:17:23.277 I/MonoDroid( 7556):  at android.view.Choreographer.doCallbacks(Choreographer.java:590)
04-22 12:17:23.287 I/MonoDroid( 7556):  at android.view.Choreographer.doFrame(Choreographer.java:559)
04-22 12:17:23.287 I/MonoDroid( 7556):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
04-22 12:17:23.287 I/MonoDroid( 7556):  at android.os.Handler.handleCallback(Handler.java:739)
04-22 12:17:23.287 I/MonoDroid( 7556):  at android.os.Handler.dispatchMessage(Handler.java:95)
04-22 12:17:23.287 I/MonoDroid( 7556):  at android.os.Looper.loop(Looper.java:145)
04-22 12:17:23.287 I/MonoDroid( 7556):  at android.app.ActivityThread.main(ActivityThread.java:5944)
04-22 12:17:23.287 I/MonoDroid( 7556):  at java.lang.reflect.Method.invoke(Native Method)
04-22 12:17:23.287 I/MonoDroid( 7556):  at java.lang.reflect.Method.invoke(Method.java:372)
04-22 12:17:23.287 I/MonoDroid( 7556):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
04-22 12:17:23.287 I/MonoDroid( 7556):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)

TraceView

It doesn't seem to be connected with WRAP_CONTENT, it just seems to appear a lot quicker that way. So might be an issue with the RecyclerView itself or maybe MVVMCross, but I'm really not sure atm. Will try to isolate the issue later on.
It seems not directly related to the RecyclerView, because it happens with the ListView aswell, though I don't know how much those two are related since I'm kind of new to Android. So I guess it is either an Android/Monodroid Issue or MVVMCross.

A: I used the solution "MvxItemTemplateSelector" which recently got added by "thefex" to MVVMCross, though it kinda means i have to flatten my data structure by hand (Categories and Channels to one layer).
https://github.com/MvvmCross/MvvmCross-AndroidSupport/pull/200
Thanks for this feature! Just wish the other way would work aswell, but maybe i can try to solve it when i got more time to spare.
Greetings Cyriac

A: The problem is that when nesting a ListView or RecyclerView, it can't measure the height of the nested View.
Hence, it will attempt to layout every view in the nested RecyclerView. This means, if that nested item has a lot of items, then your app will run into severe issues.
You should really avoid nesting such types of views unless you provide more information for the Android system to possibly know how to measure the children.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows: Enable/Disable Lock Screen Password With Shortcut On Windows 10, personal machine, at home, I'm looking for a way to create a shortcut, that uses a PS script or external program, that I can use to quickly change the behavior of the machine when the display turns off.
I've the machine set to turn off the display after 5 minutes of inactivity and it requires a password when I move the mouse or tap any key. Is there a way to create a desktop shortcut that will disable this password prompt / go straight into the desktop and another to enable it again?
Thank you.

A: *

*Make two .reg files for the key HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon to export the DWORD value ScreenSaverGracePeriod in two different states -- your normal grace period, in seconds (e.g., 60) and a far longer one, e.g., 3600. Create two keyboard shortcuts to the .reg files. Disadvantages:

*

*An extra click is needed in UAC to allow changes to the Registry.

*On some machines, very long grace periods are not honored.

*You can also do this with a PowerShell script, below, from StackOverflow
Function Set-OnResumeDisplayLogon {
  Param ([Int32]$value)
  [Int32]$nullVar = 0
  $systemParamInfo::SystemParametersInfo(119, $value, [REF]$nullVar, 2) }

Call it by Set-OnResumeDisplayLogon(x), where x=0 to stop password requirement, and 1 to enable it. Again, UAC may be a nuisance.


text:
Q: Derivative of projection's norm squared with respect to a matrix Background: Let $M^{n\times k}(\mathbb{R})$ denote the $n\times k$ matrices with real entries. For any smooth function $f: M^{n\times k}(\mathbb{R}) \to \mathbb{R}$, define the derivative $\frac{\partial f}{\partial A}$ by $$\left(\frac{\partial f}{\partial A}\right)_{i,j}:= \frac{\partial f}{\partial a_{ij}},$$
where $a_{i,j}$ is the entry of $A$ at the $i$-th row and $j$-th column. For any smooth curve $c:(-\epsilon,\epsilon)\to M^{n\times k}(\mathbb{R})$ with $c(0) = A, \dot c(0) = v$, $\frac{\partial f}{\partial A}$ satisfies:
$$\frac{d}{dt}|_{t=0}f(c(t)) = \text{trace}\left(v^T \frac{\partial f}{\partial A}\right).$$
Question: Let $f: M^{n\times k}(\mathbb{R}) \to \mathbb{R}$ be defined by $$f(A):= \|(I - A(A^TA)^{-1}A^T) z\|^2,$$
where $z \in \mathbb{R}^n$ is a fixed vector and $\|\cdot\|$ denotes the Euclidean norm.
I would like to compute $\frac{\partial f}{\partial A}$, at least at any $A$ which is full rank. Are there any tricks that can simplify this process, or is the easiest thing simply to compute each $\frac{\partial f}{\partial a_{i,j}}$ by "brute force"?
My attempt at a simpler solution:
Let $c:(-\epsilon,\epsilon)\to M^{n\times k}(\mathbb{R})$ be a smooth curve with $c(0) = A, \dot c(0) = v$. I will assume that $A$ is full rank.
By the chain and product rules, we have $$\frac{d}{dt}|_{t=0}f(c(t)) = 2 z^T(I-A(A^TA)^{-1}A)\left[-v (A^TA)^{-1}A^T + A(A^TA)^{-1}(v^TA + A^Tv)(A^TA)^{-1}A^T - A(A^TA)^{-1}v^T\right]z, $$
where I have used the fact that for any smooth curve $b:(-\epsilon,\epsilon)\to GL(n,\mathbb{R})$, $\frac{d}{dt}|_{t=0}b^{-1}(t) = -b^{-1}(0)\dot b(0) b^{-1}(0)$.
To simplify notation, let $A^\dagger:= (A^T A)^{-1} A^T$ denote the Moore-Penrose pseudoinverse of $A$ and let $\Pi_{A_\perp}:= I - AA^\dagger$ be the orthogonal projection onto the orthogonal complement of the range of $A$.
Substitution of this new notation yields:
$$\frac{d}{dt}|_{t=0}f(c(t)) = 2 z^T\Pi_{A_\perp}\left[-v A^\dagger + (A^\dagger)^T(v^TA + A^Tv)A^\dagger - (A^\dagger)^T v^T\right]z. $$
Now, the kernel of $A^\dagger$ is equal to the orthogonal complement to the range of $A$, so the range of $(A^\dagger)^T$ is equal to the range of $A$. It follows that $\Pi_{A_\perp} (A^\dagger)^T = 0$. Thus we now have a simpler expression:
$$\frac{d}{dt}|_{t=0}f(c(t)) = -2 z^T\Pi_{A_\perp}v A^\dagger z = -2\text{trace}\left(z^T(A^\dagger)^Tv^T\Pi_{A_\perp}z\right) = -2\text{trace}\left(v^T \Pi_{A_{\perp}}zz^T(A^\dagger)^T\right).$$
Since $v \in M^{n\times k}(\mathbb{R})$ was arbitrary, it follows that
$$\frac{\partial f}{\partial A}(A) = -2 \Pi_{A_\perp} zz^T(A^\dagger)^T.$$

A: You can pretty much do what @frank suggested, but without the need for the pseudoinverse.
Let
$$\eqalign{
 B &= A^TA \cr
 M &= I - AB^{-1}A^T \cr
}$$
both of which are symmetric. Notice that $A^TM=0$, which will be useful later.
Now we can express the function, differential, and gradient as
$$\eqalign{
 f &= Mz:Mz \cr\cr
df &= 2\,Mz:dM\,z \cr
   &= -2\,Mzz^T:\big(dA\,B^{-1}A^T + A\,dB^{-1}A^T + AB^{-1}dA^T\big) \cr
   &= -\big(2\,Mzz^TAB^{-1}:dA\big) - \big(2\,A^TMzz^TA:dB^{-1}\big) - \big(2\,B^{-1}A^TMzz^TA:dA^T\big) \cr
   &= -2\,Mzz^TAB^{-1}:dA \,\,- (0) - (0) \cr\cr
\frac{\partial f}{\partial A}  &= -2\,Mzz^TAB^{-1} \cr
   &= 2\,\Big(A(A^TA)^{-1}A^T-I\Big)zz^TA(A^TA)^{-1} \cr\cr
}$$

A: For convenience, define a new variable and its differential (borrowing a result from Harville's "Matrix Algebra From a Statistician's Perspective")
$$\eqalign{
 M &= I-AA^\dagger \cr
dM &= -d(AA^\dagger) \cr
   &= -M\,dA\,A^\dagger - (A^\dagger)^T\,dA^T\,M^T \cr
   &= -2\,{\rm sym}(M\,dA\,A^\dagger) \cr
}$$
Then write the function in terms of the Frobenius (:) Inner Product and find its differential
$$\eqalign{
 f &= Mz:Mz \cr
df &= 2\,Mz:dM\,z \cr
   &= 2\,Mzz^T:dM \cr
   &= -2\,Mzz^T:2\,{\rm sym}(M\,dA\,A^\dagger) \cr
   &= -2\,(2\,{\rm sym}(Mzz^T)):M\,dA\,A^\dagger \cr
   &= -2\,(Mzz^T+zz^TM^T):M\,dA\,A^\dagger \cr
   &= -2\,M^T(Mzz^T+zz^TM^T)(A^\dagger)^T:dA \cr
}$$
Since $df=\big(\frac{\partial f}{\partial A}:dA\big),\,$ the gradient must be
$$\eqalign{
 \frac{\partial f}{\partial A} &= -2\,M^T(Mzz^T+zz^TM^T)(A^\dagger)^T \cr
}$$
Since $M$ is an orthoprojector, we know several additional facts
$$\eqalign{
M^2 &= M \cr
M^T &= M \cr
M(A^\dagger)^T &= 0 \cr
MA &= 0 \cr
}$$
which can be used to simplify the result to
$$\eqalign{
 \frac{\partial f}{\partial A} &= -2\,Mzz^T(A^\dagger)^T \cr
}$$

A: That follows is a geometrical proof. Let $y=\Pi_{A_\perp} z$; then $y=z-AA^\dagger z$ where $AA^\dagger z$ is the orthogonal projection of $z$ on $im(A)$. Since $f(A)=y^Ty$, $Df_A(H)=2y^TDy(H)=2y^TD(z-AA^\dagger z)H=-2y^TD(AA^\dagger z)H=-2y^T(HA^\dagger z+AD(A^\dagger z)H)$ and finally
$Df_A(H)=-2y^THA^\dagger z=-2tr(H^Tyz^T(A^\dagger)^T)$.
Thus the gradient of $f$ is $\nabla (f)(A)=-2y(A^\dagger z)^T$. Since $A$ is one to one, $x=A^\dagger z$ is the unique $x$ s.t. the orthogonal decomposition $z=y+Ax$ stands. Thus $\nabla (f)(A)=-2yx^T$.
EDIT. Let $H$ be a small matrix and $f(A+H)=\tilde{y}$; we assume that $y\not= 0$.
Then $||\tilde{y}||^2-||y||^2\approx -2y^THx$, that implies: $||\tilde{y}||-||y||\approx \dfrac{-y^THx}{||y||}$.


text:
Q: WSO2 API Manager "Unexpected EOF in prolog" Exception I am new to WSO2API Manager and here's the issue:

*

*I tried to start the server few days ago and it started successfully

*But when I tried to start it this morning (without any modifications to server configuration), it throws out an exception as follows:
WARN - MultiXMLConfigurationBuilder Proxy configuration cannot be built from : WorkflowCallbackService.xml - Continue in fail-safe mode org.apache.axiom.om.OMException: com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prolog

*Removing all files (including original and server generated files)under repository/deployment/server and paste new copies of the original five folders(axis2modules etc) would solve the problem.
Anyone knows how to fix this by in other ways? Apparently it's not a good choice to remove those files when facing this error.


text:
Q: how read xml file from res folder I want to load data from an XML file and assign that data to variables in my Android app.
After doing some research on the various XML parsers available to Android, I figure the best parser method to use would be SAX.
I've read through a bunch of posts about reading XML from Android however I can't find one that uses a local file in the 'res' folder.
All the tutorials I've found are loading the XML file via a URL.
Is there a way to load the XML from the res folder?
Thanks

A: Put the xml into /res/raw folder. It looks like openRawResource opens resources from that folder only. You can also try getResources().getXml(com.MYCLass.R.xml.programs); which will return you instance of XML parser.

A: Use :
 InputStream is=getResources().openRawResource(R.raw.my_xml);

to get an input stream to your XML, and then use XMLPullParser to parse the file :
 XmlPullParser xpp=XmlPullParserFactory.newInstance().newPullParser();
 xpp.setInput(is,"your-encoding");

A: You could look at my past question regarding the same issue: How to use DOM to read XML within Android applications correctly?
From my experience I've copied the xml file into the res/raw folder and was able to read it correctly there using res.openRawResource(R.raw.the_id). You can load it from the res/layout folder but some of the information when you parse it may be in binary, which wouldn't be ideal.

A: you cant use a xml file in raw folder. because this error occurred : "Expected resource of type raw."
but u can easily place this xml file in assets folder and use it with :
 is = getAssets().open("myFedd.xml") ;


text:
Q: AEM::Dispatcher issue I have configured dispatcher on my local on AEM and now trying the URL http://www.mywebapp.com (this entry is made in hosts file too). Here is the error that I am getting
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] Found farm website for www.mywebapp.com
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] checking [/]
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] request URL has no extension: /
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] cache-action for [/]: NONE
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] Filter rejects: GET / HTTP/1.1
[Tue Mar 10 12:25:43 2015] [I] [7268(496)] "GET /" - - 1ms

Here is the dispatcher.any file. I am not sure what filter is exactly blocking the request:
# Each farm configures a set of load balanced renders (i.e. remote servers)
/farms
  {
  # First farm entry
  /website
    {
    # Request headers that should be forwarded to the remote server.
    /clientheaders
      {
      # Forward all request headers that are end-to-end. If you want
      # to forward a specific set of headers, you'll have to list
      # them here.
      "*"
      }

    # Hostname globbing for farm selection (virtual domain addressing)
    /virtualhosts
      {
      # Entries will be compared against the "Host" request header
      # and an optional request URL prefix.
      #
      # Examples:
      #
      #   www.company.com
      #   intranet.*
      #   myhost:8888/mysite
      "*"
      }

    # The load will be balanced among these render instances
    /renders
      {
      /rend01
        {
        # Hostname or IP of the render
        /hostname "127.0.0.1"
        # Port of the render
        /port "4503"
        # Connect timeout in milliseconds, 0 to wait indefinitely
        # /timeout "0"
        }
      }

    # The filter section defines the requests that should be handled by the dispatcher.
    # The globs will be compared against the request line, e.g. "GET /index.html HTTP/1.1".
    /filter
      {
      # Deny everything first and then allow specific entries
      /0001 { /type "deny"  /glob "*" }

      # Open consoles
#     /0011 { /type "allow" /glob "* /admin/*"  }  # allow servlet engine admin
#     /0012 { /type "allow" /glob "* /crx/*"    }  # allow content repository
#     /0013 { /type "allow" /glob "* /system/*" }  # allow OSGi console

      # Allow non-public content directories
#     /0021 { /type "allow" /glob "* /apps/*"   }  # allow apps access
#     /0022 { /type "allow" /glob "* /bin/*"    }
      /0023 { /type "allow" /glob "* /content*" }  # disable this rule to allow mapped content only

#     /0024 { /type "allow" /glob "* /libs/*"   }
#     /0025 { /type "deny"  /glob "* /libs/shindig/proxy*" } # if you enable /libs close access to proxy

#     /0026 { /type "allow" /glob "* /home/*"   }
#     /0027 { /type "allow" /glob "* /tmp/*"    }
#     /0028 { /type "allow" /glob "* /var/*"    }

      # Enable specific mime types in non-public content directories
      /0041 { /type "allow" /glob "* *.css *"   }  # enable css
      /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
      /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
      /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
      /0045 { /type "allow" /glob "* *.png *"   }  # enable png
      /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
      /0047 { /type "allow" /glob "* *.html *"   }  # enable flash

      # Enable features
      /0061 { /type "allow" /glob "POST /content/[.]*.form.html" }  # allow POSTs to form selectors under content
      /0062 { /type "allow" /glob "* /libs/cq/personalization/*"  }  # enable personalization

      # Deny content grabbing
      /0081 { /type "deny"  /glob "GET *.infinity.json*" }
      /0082 { /type "deny"  /glob "GET *.tidy.json*"     }
      /0083 { /type "deny"  /glob "GET *.sysview.xml*"   }
      /0084 { /type "deny"  /glob "GET *.docview.json*"  }
      /0085 { /type "deny"  /glob "GET *.docview.xml*"  }

      /0086 { /type "deny"  /glob "GET *.*[0-9].json*" }
#     /0087 { /type "allow" /glob "GET *.1.json*" }          # allow one-level json requests

      # Deny query
      /0090 { /type "deny"  /glob "* *.query.json*" }
      }

    # The cache section regulates what responses will be cached and where.
    /cache
      {
      # The docroot must be equal to the document root of the webserver. The
      # dispatcher will store files relative to this directory and subsequent
      # requests may be "declined" by the dispatcher, allowing the webserver
      # to deliver them just like static files.
      /docroot "C:/Apache2.2/htdocs"

      # Sets the level upto which files named ".stat" will be created in the
      # document root of the webserver. When an activation request for some
      # page is received, only files within the same subtree are affected
      # by the invalidation.
      /statfileslevel "3"

      # Flag indicating whether to cache responses to requests that contain
      # authorization information.
      /allowAuthorized "1"

      # Flag indicating whether the dispatcher should serve stale content if
      # no remote server is available.
      #/serveStaleOnError "0"

      # The rules section defines what responses should be cached based on
      # the requested URL. Please note that only the following requests can
      # lead to cacheable responses:
      #
      # - HTTP method is GET
      # - URL has an extension
      # - Request has no query string
      # - Request has no "Authorization" header (unless allowAuthorized is 1)
      /rules
        {
        /0000
          {
          # the globbing pattern to be compared against the url
          # example: *             -> everything
          #        : /foo/bar.*    -> only the /foo/bar documents
          #        : /foo/bar/*    -> all pages below /foo/bar
          #        : /foo/bar[./]* -> all pages below and /foo/bar itself
          #        : *.html        -> all .html files
          /glob "*"
          /type "allow"
          }
        }

      # The invalidate section defines the pages that are "invalidated" after
      # any activation. Please note that the activated page itself and all
      # related documents are flushed on an modification. For example: if the
      # page /foo/bar is activated, all /foo/bar.* files are removed from the
      # cache.
      /invalidate
        {
        /0000
          {
          /glob "*"
          /type "deny"
          }
        /0001
          {
          # Consider all HTML files stale after an activation.
          /glob "*.html"
          /type "allow"
          }
        }

      # The allowedClients section restricts the client IP addresses that are
      # allowed to issue activation requests.
      /allowedClients
        {
        # Uncomment the following to restrict activation requests to originate
        # from "localhost" only.
        #
        #/0000
        #  {
        #  /glob "*"
        #  /type "deny"
        #  }
        #/0001
        #  {
        #  /glob "127.0.0.1"
        #  /type "allow"
        #  }
        }
      }

    # The statistics sections dictates how the load should be balanced among the
    # renders according to the media-type.
    /statistics
      {
      /categories
        {
        /html
          {
          /glob "*.html"
          }
        /others
          {
          /glob "*"
          }
        }
      }
    }
  }

A: you should have mod_rewrite redirecting your "GET /" request to "GET /content/mywebapp/en.html" (among other rules).
"GET /" can't be cached, because it doesn't have any extension, and you probably want your home page to be cached.

A: You have two options, either setup apache to redirect / to your homepage (/content/myapp/home.html or the equivalent)
OR you can use resource resolver factory settings to rewrite the url.
For the simple version, use resource resolver mappings.  See this post for more details:
http://www.aemmastery.com/2015/03/15/aem-osgi-service-dive-resource-resolver-factory/

A: You may need a vhost file similar to the following:
<VirtualHost *:80>
    ServerName www.mywebapp.com
    DocumentRoot /var/www/html
    ErrorDocument 404 /content/mywebapp/en/404.html
    ErrorDocument 500 /content/mywebapp/en/500.html

    RewriteEngine On
    RewriteLog "logs/rewrite-www-mywebapp-com.log"
    RewriteLogLevel 1

    RewriteRule ^/en.html$ / [R=301,L]
    RewriteRule ^/$ /content/mywebapp/en.html [PT]

    RewriteCond %{REQUEST_URI} !^/etc(.*) [NC]
    RewriteCond %{REQUEST_URI} !^/libs(.*) [NC]
    RewriteCond %{REQUEST_URI} !^/content(.*) [NC]
    RewriteCond %{REQUEST_URI} !^/system(.*) [NC]
    RewriteCond %{REQUEST_URI} !^/dam(.*) [NC]
    RewriteCond %{REQUEST_URI} !^/services(.*) [NC]
    RewriteRule ^/(.*) /content/mywebapp/$1 [PT]

    <Directory "/var/www/html">
        <IfModule disp_apache2.c>
            SetHandler dispatcher-handler
            ModMimeUsePathInfo On
        </IfModule>

            Options FollowSymLinks
            AllowOverride AuthConfig
            Order allow,deny
            Allow from all
    </Directory>
</VirtualHost>

So, if you go to www.mywebapp.com, file /var/www/html/content/mywebapp/en.html is created and cached.
If you go to www.mywebbapp.com/en/foo/bar.html,
file /var/www/html/content/mywebapp/en/foo/bar.html is created and cached.
Customize the above file to meet your own needs.
You may also need to configure /etc/mapping to fit your URL rewriting needs. Refer to this page for more information:
https://docs.adobe.com/docs/en/aem/6-2/deploy/configuring/resource-mapping.html

A: Here is an example we did for one of the taining sites

 # first farm entry (label is not important, just for your convenience)
  /cookbook
    {
    # client headers which should be passed through to the render instances
    # (feature supported since dispatcher build 2.6.3.5222)
    /clientheaders
      {
      "referer"
      "user-agent"
      "authorization"
      "from"
      "content-type"
      "content-length"
      "accept-charset"
      "accept-encoding"
      "accept-language"
      "accept"
      "host"
      "if-match"
      "if-none-match"
      "if-range"
      "if-unmodified-since"
      "max-forwards"
      "proxy-authorization"
      "proxy-connection"
      "range"
      "cookie"
      "cq-action"
      "cq-handle"
      "handle"
      "action"
      "cqstats"
      "depth"
      "translate"
      "expires"
      "date"
      "dav"
      "ms-author-via"
      "if"
      "lock-token"
      "x-expected-entity-length"
      "destination"
      }
    # hostname globbing for farm selection (virtual domain addressing)
    /virtualhosts
      {
      # entries will be compared against the 'host' request header.
      # example: www.company.com
      # example: intranet.*
      "*"
      }
    # the load will be balanced among these render instances
    /renders
      {
      /publish1
        {
        # hostname or IP of the render
        /hostname "localhost"
        # port of the render
        /port "4503"
        # connect timeout in milliseconds, 0 to wait indefinitely
        /timeout "0"
        }
      }
    # only handle the requests in the following acl. default is 'none'
    # the glob pattern is matched against the first request line
    /filter
      {
      # deny everything and allow specific entries
      /0001 { /type "deny"  /glob "*" }

      # open consoles
 #    /0012 { /type "allow" /glob "* /crx/*"    }  # allow content repository
 #    /0013 { /type "allow" /glob "* /system/*" }  # allow OSGi console

      # allow non-public content directories
 #    /0021 { /type "allow" /glob "* /apps/*"   }  # allow apps access
      /0022 { /type "allow" /glob "* /bin/*"    }
      /0023 { /type "allow" /glob "* /content*" }  # disable this rule to allow mapped content only

 #    /0024 { /type "allow" /glob "* /libs/*"   }
 #    /0025 { /type "deny"  /glob "* /libs/shindig/proxy*" } # if you enable /libs close access to proxy

 #    /0026 { /type "allow" /glob "* /home/*"   }
 #    /0027 { /type "allow" /glob "* /tmp/*"    }
 #    /0028 { /type "allow" /glob "* /var/*"    }

      # enable specific mime types in non-public content directories
      /0041 { /type "allow" /glob "* *.css *"   }  # enable css
      /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
      /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
      /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
      /0045 { /type "allow" /glob "* *.png *"   }  # enable png
      /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
      /0047 { /type "allow" /glob "* *.svg *"   }  # enable SVG
      /0048 { /type "allow" /glob "* *.woff *"  }  # enable woff
      /0049 { /type "allow" /glob "* *.ttf *"   }  # enable ttf
      /0050 { /type "allow" /glob "* *.eot *"   }  # enable eot
      /0051 { /type "allow" /glob "* *.jpg *"   }  # enable jpg

      /0052 { /type "allow" /glob "* /services/*" } # enable servlet services

      # enable features
      /0061 { /type "allow" /glob "POST /content/[.]*.form.html" }  # allow POSTs to form selectors under content
      /0062 { /type "allow" /glob "* /libs/cq/personalization/*" }  # enable personalization

      # deny content grabbing
      /0081 { /type "deny"  /glob "GET *.infinity.json*" }
      /0082 { /type "deny"  /glob "GET *.tidy.json*"     }
      /0083 { /type "deny"  /glob "GET *.sysview.xml*"   }
      /0084 { /type "deny"  /glob "GET *.docview.json*"  }
      /0085 { /type "deny"  /glob "GET *.docview.xml*"   }
      /0086 { /type "deny"  /glob "GET *.*[0-9].json*"   }
      /0087 { /type "deny"  /glob "GET *.feed.xml*"      }
 #    /0088 { /type "allow" /glob "GET *.1.json*"        }  # allow one-level json requests
      /0089 { /type "allow" /glob "GET /etc/clientcontext/.*/*.json*.*" }

      # deny query
      /0090 { /type "deny"  /glob "* *.query.json*" }
      }

    # allow propagation of replication posts (should seldomly be used)
    /propagateSyndPost "0"

    # the cache is used to store requests from the renders for faster delivery
    # for a second time.
    /cache
      {
      # the cacheroot must be equal to the document root of the webserver
      /docroot "/var/www/html/content/cookbook"

      # sets the level upto which files named ".stat" will be created in the
      # document root of the webserver. when an activation request for some
      # handle is received, only files within the same subtree are affected
      # by the invalidation.
      /statfileslevel "0"
      # caches also authorized data
      /allowAuthorized "1"

      # the rules define, which pages should be cached. please note that
      # - only GET requests are cached
      # - only requests with an extension are cached
      # - only requests without query parameters ( ? ) are cached
      # - only unauthorized pages are cached unless allowUnauthorized is set to 1
      /rules
        {
        /0000
          {
          # the globbing pattern to be compared against the url
          # example: *       -> everything
          #     : /foo/bar.*    -> only the /foo/bar documents
          #     : /foo/bar/*    -> all pages below /foo/bar
          #     : /foo/bar[./]* -> all pages below and /foo/bar itself
          #     : *.html        -> all .html files
          /glob "*"
          /type "allow"
          }
        }
      # the invalidate section defines those pages which are 'invalidated' after
      # any activation. please note that, the activated page itself and all
      # related documents are flushed on an modification. for example: if the
      # page /foo/bar is activated, all /foo/bar.* files are removed from the
      # cache.
      /invalidate
        {
        /0000
          {
          /glob "*"
          /type "deny"
          }
        /0001
          {
          /glob "*.html"
          /type "allow"
          }
        }
      }
    # the statistics define, how the load should be balanced among the renders
    # according to the media-type.
    /statistics
      {
      /categories
        {
        /html
          {
          /glob "*.html"
          }
        /others
          {
          /glob "*"
          }
        }
      }
    }

A: By default you are not allowing anything using this filter.
# Deny everything first and then allow specific entries
/0001 { /type "deny"  /glob "*" }

Hence / is not allowed. If you want to allow access to root you need to specifically allow it by adding the line
/0024 { /type "allow" /glob "* /*" }

A: Your dispatcher config looks fine. To verify whether dispatcher is working or not, you can simply enter the following url to see if page is showing up, then check the cache folder.

http://localhost:{port if you are not using 80 on apache)/content/{sitenode}

Assume everything above-mentioned is working when use the localhost, it must be the configuration issue in your apache config file.
Check the following settings carefully defined in your dispatcher module section

*

*DispatcherDeclineRoot (This defines whether to decline requests to the root "/")

*DispatcherUseProcessedURL (This defines whether to use pre-processed URLs for all further processing by Dispatcher)

p.s. If you make it working, don't forget to share some details here. :)

A: You need to use mod_rewrite Apache Module in order to redirect your request from '/' to '/content/'/en.html'
http://httpd.apache.org/docs/current/mod/mod_rewrite.html
This official documentation provides good read regarding how to write rewrite rules.
apart from this, because / doesn't have any extension, it says that this request can't be cached.
I believe you won't need to do anything else apart from redirection mentioned, because en.html has '.html' as it's extension and /0047 { /type "allow" /glob "* *.html *"   } is already mentioned in the Filter section

A: There are two ways we can resolve it.
1, In filter section add the below rule.
  /0001 { /type "allow"  /glob "*" }
2, normally in real time projects we have content under /content/xyz.html, for this kind of scenario we add below rules.
`/0001 { /type "deny"  /glob "*" }`
`/0001 { /type "allow"  /glob "/content/*" }`

Add a rewrite rule which any thing after URL redirect to /content/xyz.html.
RewriteRule ^/(.*) /content/mywebapp/$1 [R=301, L]
keep adding deny and allow rules as per the project requirements.


text:
Q: How to fix Google Cloud Messaging Registration error:PHONE_REGISTRATION_ERROR? I encountered a strange problem - I am using GCM with my application for a month but now its has stopped working on my nexus 4 (running Lollipop 5.0.1, stock Android).Everytime I try to get a registration id from Google server it returns me Error :PHONE_REGISTRATION_ERROR .I know this error is for devices that runs android version 2.2 and below as they do not support GCM but why is it happening for my device although it was working few days back.
<permission
    android:name="diver.volo.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="diver.volo.permission.C2D_MESSAGE" />

    <receiver
        android:name="diver.volo.components.GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="diver.volo" />
        </intent-filter>
    </receiver>


text:
Q: How to repeat the table column header in each page I'm using FPDF to create a PDF file which the data is getting pulled from a MySQL database. And the table is getting created with two main column headers "User Name" and "Total Time Spent".
<?php
/**
 * Created by PhpStorm.
 * User: SiNUX
 * Date: 8/3/2017
 * Time: 2:44 PM
 */

require('../Libraries/fpdf/fpdf.php');
include_once ('../iConnect/handShake.php');

class h4PDF extends FPDF{
    function Header(){
        $this->Image('../../images/logo.png', 10,6,30);
        $this->SetFont('Arial', 'B', 12);
        $this->Cell(80);
        $this->Cell(50, 10, 'Total Spent Time', 0, 0,'C');
        $this->Ln(10);
    }
}

$getTot = "SELECT userlogin.uName, SEC_TO_TIME(SUM(TIME_TO_SEC(timeSpent))) AS totTime FROM usertimetrack
           LEFT JOIN userlogin ON usertimetrack.usrId = userlogin.uId WHERE jDate = :jdate GROUP BY usrId";
$getTotQuery = $dbConnect -> prepare($getTot);
$getTotQuery -> bindParam('jdate', $_REQUEST["date"]);
$getTotQuery -> execute();

$pdf = new h4PDF();
$pdf->AddPage();

$pdf->SetFont('Arial','', 14);
$pdf->SetFillColor(255,0,0);
$pdf->SetTextColor(255);
$pdf->SetDrawColor(128,0,0);
$pdf->SetLineWidth(.3);
$pdf->SetFont('','B');

$pdf->SetX(70);
$pdf->Cell(40,6,'User Name',1,0,'C',1);
$pdf->SetX(105);
$pdf->SetX(110);
$pdf->Cell(42,6,'Total Spent Time',1,0,'C',1);
$pdf->Ln();

$pdf->SetFillColor(224,235,255);
$pdf->SetTextColor(0);
$pdf->SetFont('');

$fill = false;
while ($getTotRow = $getTotQuery -> fetch(PDO::FETCH_ASSOC)){
    $uName = $getTotRow["uName"];
    $totTime = $getTotRow["totTime"];

    $pdf->SetX(70);
    $pdf->Cell(40,6,$uName,'LR',0,'C',$fill);
    $pdf->SetX(105);
    $pdf->SetX(110);
    $pdf->Cell(42,6,$totTime ,'LR',0,'C',$fill);
    $pdf->Ln();
    $fill = !$fill;
}
$pdf->SetX(70);
$pdf->Cell(82,0,'','T');

$pdf->Output();

With the current code I can create the table but this code only prints the header of the table columns on the first page only actually at the beginning of the table and the rest will be filled with data which continues till the data ends. I wish to repeat these 2 header on each page at the beginning of the table on each page.
I tried to do something like this script but ended up creating an infinity loop.
I think I do have to do a manual data amount for the page, then turn off the auto page break, then check for the max data and then print the header if the table has reached it's max data amount. But I don't know how to plug that in to this code.
Can some one please show me how to do this, I'm posting this after many attempts which failed or ended up me breaking the entire script.
**UPDATE:**Thanks to kastriotcunaku I managed to solve my problem now my new code is as follows,
<?php
/**
 * Created by PhpStorm.
 * User: SiNUX
 * Date: 8/3/2017
 * Time: 2:44 PM
 */

require('../Libraries/fpdf/fpdf.php');
include_once ('../iConnect/handShake.php');

class h4PDF extends FPDF{
    function Header(){
        $this->Image('../../images/logo.png', 10,6,30);
        $this->SetFont('Arial', 'B', 12);
        $this->Cell(80);
        $this->Cell(50, 10, 'Total Spent Time', 0, 0,'C');
        $this->Ln(10);

        $this->SetFont('Arial','', 14);
        $this->SetFillColor(255,0,0);
        $this->SetTextColor(255);
        $this->SetDrawColor(128,0,0);
        $this->SetX(74);
        $this->Cell(40,6,'User Name',1,0,'C',1);
        $this->SetX(109);
        $this->SetX(114);
        $this->Cell(42,6,'Total Spent Time',1,0,'C',1);
        $this->Ln();
    }
}

$getTot = "SELECT userlogin.uName, SEC_TO_TIME(SUM(TIME_TO_SEC(timeSpent))) AS totTime FROM usertimetrack
           LEFT JOIN userlogin ON usertimetrack.usrId = userlogin.uId WHERE jDate = :jdate GROUP BY usrId";
$getTotQuery = $dbConnect -> prepare($getTot);
$getTotQuery -> bindParam('jdate', $_REQUEST["date"]);
$getTotQuery -> execute();

$pdf = new h4PDF();
$pdf->AddPage();

$pdf->SetFont('Arial','', 14);
$pdf->SetFillColor(255,0,0);
$pdf->SetTextColor(255);
$pdf->SetDrawColor(128,0,0);
$pdf->SetLineWidth(.1);
$pdf->SetFont('','B');

$pdf->SetFillColor(224,235,255);
$pdf->SetTextColor(0);
$pdf->SetFont('');

$fill = false;
while ($getTotRow = $getTotQuery -> fetch(PDO::FETCH_ASSOC)){
    $uName = $getTotRow["jDate"];
    $totTime = $getTotRow["timeSpent"];

    $pdf->SetX(74);
    $pdf->Cell(40,6,$uName,'1',0,'C',$fill);
    $pdf->SetX(109);
    $pdf->SetX(114);
    $pdf->Cell(42,6,$totTime ,'1',0,'C',$fill);
    $pdf->Ln();
    $fill = !$fill;
}

$pdf->Output();

I removed the last line which was to be drawn after the while loop stops which actually was just leaving the end of the table with out a last line so I removed that and enable the borders of the cells and set the line width to 0.1 which made my table look much better.

A: You need to specify table header inside function Header(), before $pdf->AddPage();
Try something like this:

<?php

class h4PDF extends FPDF{
    function Header(){
        $this->Image('../../images/logo.png', 10,6,30);
        $this->SetFont('Arial', 'B', 12);
        $this->Cell(80);
        $this->Cell(50, 10, 'Total Spent Time', 0, 0,'C');
        $this->Ln(10);

        $this->SetX(70);
        $this->Cell(40,6,'User Name',1,0,'C',1);
        $this->SetX(105);
        $this->SetX(110);
        $this->Cell(42,6,'Total Spent Time',1,0,'C',1);
        $this->Ln();
    }
}

?>


text:
Q: Long mac address back to byte array I have a method that takes a mac address from a string and converts it to a byte array. Then I have another method take that byte array and convert it to a long. As Follows
final long address = ((long)addr[5] & 0xff)
    + (((long)addr[4] & 0xff) << 8)
    + (((long)addr[3] & 0xff) << 16)
    + (((long)addr[2] & 0xff) << 24)
    + (((long)addr[1] & 0xff) << 32)
    + (((long)addr[0] & 0xff) << 40);

However I cannot figure out how to convert this long back into a byte array for storage.
I have tried
/* long l = mac in long format address | mac addresses only take 6 bytes */
buffer[currentOffset++] = (byte)l;
buffer[currentOffset++] = (byte)(l >> 8);
buffer[currentOffset++] = (byte)(l >> 16);
buffer[currentOffset++] = (byte)(l >> 24);
buffer[currentOffset++] = (byte)(l >> 32);
buffer[currentOffset++] = (byte)(l >> 40);

It does not convert back correctly though.

A: You are assigning in reverse order.
buffer[currentOffset++] = (byte) (l >> 40);
buffer[currentOffset++] = (byte) (l >> 32);
buffer[currentOffset++] = (byte) (l >> 24);
buffer[currentOffset++] = (byte) (l >> 16);
buffer[currentOffset++] = (byte) (l >> 8);
buffer[currentOffset++] = (byte) l;

A: In google Guava terms its just a one liner :
Longs.toByteArray(getMacAddress())


text:
Q: How to assign a value to an pointer-pointer passed in call by reference? I want to achieve something similar to what these guys do here:
- (NSUInteger)countForFetchRequest:(NSFetchRequest *)request error:(NSError **)error

like you can see, you pass an NSError pointer and that nice method will assign a real NSError object to your pointer in case there is an error. So the cool thing about this is, that the method returns an NSUInteger but can ALSO return an NSError, without having to mess around with ugly and fat arrays or dictionaries.
So how could I assign an object to the passed-in error pointer?

A: It's easy. This Apple guide shows how you might implement a method that returns an NSError object. But to make a long story very, very short:
- (NSUInteger)countForFetchRequest:(NSFetchRequest *)request error:(NSError **)error
{
    //Do stuff, including make MyCustomErrorDomain and errCode and eDict.
    if (error != NULL) { // check to avoid crash if **error is not provided
        *error = [[[NSError alloc] initWithDomain:MyCustomErrorDomain code:errCode userInfo:eDict] autorelease];
    }
    //Do some more stuff.
}

Note the asterisk. :)


text:
Q: Floating polyhedra with fair equilibria
Is there a homogeneous convex polyhedron
  which floats so that some subset (perhaps all) of its faces
  is distinguished as "up" (above the water line)
  in stable equilibrium, each face with equal probability,
  and there are no other stable orientations?

This question was prompted by the recent
MO question on fair polyhedral dice.
My thought is that one might shake a container of liquid and
await the floating polyhedron to stabilize.
Perhaps permitting inhomogeneous polyhedron interiors would
make this more feasible?
I have been unsuccessful in finding much information on floating
polyhedra, perhaps because this is such a bad idea. :-)
I know about the center of boyancy
and the metacenter and
the conditions for stability.
And
I know of Ulam's "Floating Body Problem" from the Scottish Book,
apparently still unsolved
(mentioned in Unsolved Problems in Geometry
by Croft, Falconer, Guy).
None of what I found is shedding much light.
Any pointers would be appreciated!
Edit.
Thanks Igor, sleepless, Douglas for your comments,
and apologies for not being clear!
Let me attempt a sharper question.
Let the density of the polyhedron $P$ be half that of water,
$\rho=\frac{1}{2}$.
I seek a $P$ that has $k>1$ distinct stable floating orientations.
So $P$ is unlike a sphere, which is stable in any orientation
(Ulam's question is: Is the sphere the only such convex body?).
And $P$ is unlike a boat-hull shape that is designed to have a unique stable
orientation, i.e., is monostatic.
In each of $P$'s stable orientations, some face's normal vector $n_i$
is vertical, perpendicular to the water level, pointing up.
So if you look down from above, you see that face $F_i$.
That is the basic question.
Now some embellishments:

*

*
It is not essential that $\rho=\frac{1}{2}$ exactly.
Let's say,
$\rho \in [\frac{1}{4},\frac{3}{4}]$.

*
It is not essential that each of the normal vectors $n_i$
be exactly vertical.
It just needs to be clear which face is "up."
Let's say that $n_i$ should make an angle of $\le \delta$ with
the vertical $(0,0,1)$, and no other face normal $n_j$
makes an angle of $\le 3 \delta$ with the vertical.

*
Ideally,
if $P$ is placed in the water at an arbitrary orientation,
it should stabilize into one of its $k$ stable positions
with equal probability.
So the total solid angle of orientations that lead to each
of the $k$ distinct stable positions should be $4 \pi / k$.

Were these conditions satisfied, one could place $P$ in a glass cylinder half full of
liquid, shake it, wait, and look down through the cylinder top to see the numbered up-face.

A: Quick thought: make a four-sided pyramid of ice, square base of edge length $x$ and have the height be less than $x$.  This type of ice-cube or pyramidal ice-berg has the majority of its buoyancy at the square face, thus the subset of size $1$ of {flat square base} is more likely to be the "face up" face in a container.  This could probably be tested better with a plastic homogeneous pyramid rather than with an ice-cube pyramid which would melt during the experiment and change the results over time.
There's probably a decent ratio $a$ such that if the height of the pyramid is less than $ax$ that the pyramidal-square base is significantly biased to be the "face up" floating face.

A: Added below: discussion and illustrations for equilibria of floating objects
**Further additions: Plots of potential energy for floating square and cube **
For the 2-dimensional shape below with 4 long spikes and density .5,   it seems clear that the only stable equilibrium is with one spike pointing straight down and another pointing straight up. Two spikes will float to the sides, with their centerlines at the water level.
A slight tilt shifts the center of buoyancy (= mean of points below the waterline) toward the side, and provides a strong righting force.

(This plot is the locus $|x|^.3 + |y|^.3 = 1$)
This example is easily modified to be a 12-gon in the shape of a cross, with 4 short faces that want to point straight up.
Here's a corresponding 3-dimensional shape, which should float with one of the spikes pointing up:

Begin additional discussion
For any centrally symmetric object of density .5 floating in water, the plane of the surface of the water passes through the center of mass of the object, since then the volume of water displaced is exactly half the volume of the object.  In that case, the potential energy of the object in a given configuration is proportional to depth of the center of mass of the underwater portion of the object: it's as if the underwater portion has negative weight.
To get better intuition for how this works, I tried rotating different shapes using Mathematica, plotting the underwater portion, its center of mass, and watching how the depth of the center of mass (in an amplified view) fluctuated with angle.  The red dots in
the pictures below are the centers of mass of the underwater portion.  The black dot on
to the left side of the object is at a height that magnifies the height of the underwater center; the higher it is, the more stable the object.  (In the live examples, the sliders will adjust the angle, and you can add or remove vertices by clicking).

It's probably easier to get a good intuition by looking at the relationship of the underwater center of mass (negative weight) versus the above water center of mass (positive weight).
When they are not aligned vertically, then they exert a torque; this torque amounts to the gradient of the potential function. Below, for example, is a square at a skew angle, with the underwater center marked in red, pushing upward, and the abovewater center marked in green pushing downward. This torque rotates the floating square toward a diagonal position where it has a stable equilibrium.
alt text http://dl.dropbox.com/u/5390048/RightingTorque.jpg
For a two-dimensional square (or a long 3-dimensional object with square cross-section), the stable equilibria are when a diagonal of the square is horizontal.  Similarly, a hexagon is stable when a diagonal (going from a vertex to its opposite vertex) is horizontal, and otherwise unstable.  For polygons with an odd number of vertices, the equilibria are when one face is pointing straight down.
Based on these, I'm confident that an octahedron truncated just slightly will float in equilibrium with the truncated faces pointing upward, because an octahedron with floating with one of its diagonal vertical has a lot of its underwater mass relatively close to the surface.  With somewhat less confidence, I think the truncated cube would behave similarly.
It should be straightforward (although tedious to set up) to compute the equilibria in this way for any polyhedron.
Further additions: Plots of potential energy
Here is the plot of potential energy for a floating square of buoyancy .5, as a function of angle.  (Units for the vertical scale are arbitrary). The bottoms of valleys are the stable equilibria, at odd multiples of $\pi/4$, when the square is floating with a corner up:

Here is a similar plot for the cube, when the cube is rotated until the
vector $(x,y,1)$ is vertical.  The full graph would have domain $S^2$, tiled by 6 copies of this unit, one for each face of the cube.
From the graph you can see that there is a local maximum when any face is horizontal (the top of the mountain), a saddle point when an edge is horizontal and the diagonal of a face is vertical (the saddle points are the midpoints of the bounding edges in this plot), and a minimum when a diagonal of the cube is vertical (the corners in the plot).  Notice how low the mountain passes are between adjacent minima.  This indicates when a main diagonal is vertical, rotation any of the three lines perpendicular to any face at its midpoint takes relatively little energy, far less than is required to rotate the cube so that a face is horizontal.  (Note: this energy function is highly dependent on the density of the cube, so it is hard to draw a conclusion about a floating ice cube or a floating wooden block).

Computation is underway for the potential energy for a floating dodecahedron, showing the potential energy when the vector $(x,y,1)$ is rotated vertically, where $(0,0,1)$ is the normal to a face. The image may change as the computation of potential energy is improved.
alt text http://dl.dropbox.com/u/5390048/Dodecahedron.jpg
alt text http://dl.dropbox.com/u/5390048/DodecaFloatEnergy.jpg


text:
Q: Importing parts of luis in json I am working on a production app using luis.
I have 2 luis instance containing a preproduction and a production version.
When I develop a new functionnality, I add my intents and uterence in preproduction first.
I found a button for downloading the json of intents and Entities.
Now I would like to import this json or part of it in my production but I can't find it...
Did someone here succeded doing it.

A: Go to Manage > Versions and use Import version button:

Before importing, make sure that you modified your LUIS json to match the following:

*

*versionId should be changed to be the right value you want in your production side

*name field must also match the production project name

Then you will have this version imported you will be able to train it, and publish it once you're ready.
Quick reminder: this imported JSON does not contain any changes that you could have made in Production version, it's only like a backup / restore from what you have in Pre-Production

A: There are different ways you can approach it. If you are importing the model from another app entirely, just go to Manage->Versions and then select Import Version. You cannot import if the versionId (Version Name) if the same as one as you have already (you can rename versionId in the json file if needed).
Alternatively; if the preproduction version is in the same app; just publish to the Production slot. Then, you can clone that to be the next preproduction for further modification and development.
As @Mandar pointed out; it will help if you clarify what you mean by "can't find it".


text:
Q: Socket.io architecture/configuration to connect to the closest server when available We have Global Accelerator setup in Amazon to route requests to the closest host from some multiple nodes.
How does socket.io play out in this case? If let's say a user connected, and the socket client is connected to host A, but then host B which is closer, becomes available, is there some way for the socket requests to be routed through this closest server?
The typical scenario would be that if for some reason host B is overloaded and the Accelerator just routes the socket client to use host A at the time, but now the user is stuck on the distant server until he refreshes.
Thanks


text:
Q: Django - This is field is required error I am new to Django and trying to save some data from the form to the model. I want to insert into two models which have a foreign key constraint relationship (namely Idea and IdeaUpvotes) i.e. from a html template to a view.
My submit code is:
def submitNewIdea(request):
    #get the context from the request
    context = RequestContext(request)

    print(context)

    #A HTTP POST?
    if request.method == 'POST':
        form = submitNewIdeaForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new Idea to the Idea model

            print(request.POST.get("IdeaCategory"))
            print(request.POST.get("IdeaSubCategory"))

            i = Idea(   idea_heading = form["idea_heading"].value()
                        ,idea_description = form["idea_description"].value()
                        ,idea_created_by = form["idea_created_by"].value()
                        ,idea_votes = form["idea_votes"].value()
                        ,idea_category = request.POST.get("IdeaCategory") #value from dropdown
                        ,idea_sub_category = request.POST.get("IdeaSubCategory")  #value from dropdown
                     )

            i.save()
            # get the just saved id

            print(Idea.objects.get(pk = i.id))

            iu = IdeaUpvotes(idea_id = Idea.objects.get(pk = i.id)
                            ,upvoted_by = form["upvoted_by"].value()
                            ,upvoted_date = timezone.now() )

            iu.save()
            form.save(commit = True)
            # Now call the index() view.
            # The user will be shown the homepage.
            return index(request)
        else:
            # The supplied form contained errors - just print them to the terminal.
            print (form.errors)
    else:
        # If the request was not a POST, display the form to enter details.
        form = submitNewIdeaForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render(request,'Ideas/Index.html',{'form' :form})

form.py --->
class submitNewIdeaForm(forms.ModelForm):
idea_heading = forms.CharField(label = "idea_heading",max_length =1000,help_text= "Please enter the idea heading.")
idea_description= forms.CharField(label = "idea_description",max_length =1000,help_text= "Please enter the idea description.",widget=forms.Textarea)
idea_created_by=forms.CharField(max_length =200, widget = forms.HiddenInput(), initial='wattamw')
idea_votes = forms.IntegerField(widget=forms.HiddenInput(), initial=1)
upvoted_by=forms.CharField(max_length =200, widget = forms.HiddenInput(), initial='abcde')

"""
#commented code

#idea_category_name = forms.CharField(label = "idea_category_name",max_length =250,help_text= "Please select an Idea Category.")
#idea_sub_category = forms.CharField(label = "idea_sub_category",max_length =250,help_text= "Please select an Idea Sub Category.")

idea_category_name = forms.ModelChoiceField(
                    queryset = IdeaCategory.objects.all(),
                    widget=autocomplete.ModelSelect2(url='category-autocomplete'))

idea_sub_category = forms.ModelChoiceField(
                    queryset = IdeaSubCategory.objects.all(),
                    widget = autocomplete.ModelSelect2(
                        url='subcategory-autocomplete',
                        forward = (forward.Field('idea_category_name','id'),)))
"""

class Meta:
    model = Idea
    fields = ('idea_heading','idea_description','idea_created_by','idea_votes','idea_category_name','idea_sub_category')

class Meta:
    model = IdeaUpvotes
    fields = ('upvoted_by',)

def __init__(self,*args,**kwargs):
    super(submitNewIdeaForm,self).__init__(*args,**kwargs)
    self.fields['idea_category_name'] = forms.ModelChoiceField(
                                        queryset = IdeaCategory.objects.all(),
                                        widget=autocomplete.ModelSelect2(url='category-autocomplete'))
    self.fields['idea_sub_category'] = forms.ModelChoiceField(
                                    queryset = IdeaSubCategory.objects.all(),
                                    widget = autocomplete.ModelSelect2(
                                    url='subcategory-autocomplete',
                                    forward = (forward.Field('idea_category_name','id'),)))

I am able to print the values and see that they are passed,but I still get the following error :
Error Description
I have removed any foreign key references to the table, the fields are simple character fields.
Please help me out.
Thanks.

A: In the first place, your form validation is failing. It seems to me that your form template may be wrong.
The second thing is that you don't use Django forms properly. All you need to do to achieve the functionality you are looking for is to use ModelForm and let the form's save method to create the object for you. All you need to do is:

*

*Associate your SubmitNewIdeaForm with the Idea model:
    # forms.py
    class SubmitNewIdeaForm(ModelForm):
        class Meta:
        model = Idea
        fields = (
            'idea_heading',
            'idea_description',
            'idea_created_by',
            'idea_votes',
            'idea_category',
            'idea_sub_category'
        )

*Render the form
#form_template.html
<form action="{% url 'your_url' %}" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

*Finally jsut check if the form is valid and call form.save() like so:
def submitNewIdea(request):
    if form.is_valid():
        form.save()

That's it! I hope that I helped you.
Cheers!

A:  Finished = models.IntegerField('Finished percentage', error_messages={'required':''})

Worked for me.


text:
Q: Need Help Yielding a Coroutine I'm running a coroutine where a GameObject's children's material.shaders are being manipulated. I just can't seem to figure out for the life of me how to make the coroutine wait until all of the materials are at the desired blend level, before going on to the next step. Everything's working just fine, I just need the coroutine not to continue past line 28 until all the materials are ChangedToWhite. Any thoughts?
public GameObject changeInto;

private bool coroutineStarted = false;
private Renderer[] renderersArray;
private List<Material> materialsList = new List<Material>();
private GameObject newForm;

void Start(){
    renderersArray = this.gameObject.GetComponentsInChildren<Renderer>();
}
void Update(){
    if(!coroutineStarted){
        coroutineStarted = true;
        StartCoroutine(Change());
    }
}

private IEnumerator Change(){
    foreach(Renderer renderer in renderersArray){
        for(int i = 0; i < renderer.materials.Length; i++){
            if(renderer.materials[i].shader.name == "Toon/Basic Blender"){
                materialsList.Add(renderer.materials[i]);
            }
        }
    }
    foreach(Material material in materialsList){
        StartCoroutine(ChangeToWhite(material));
    }
    animation.Play("Evolution");
    newForm = Instantiate(changeInto, this.transform.position, this.transform.rotation) as GameObject;
    yield return null;
}

private IEnumerator ChangeToWhite(Material mat){
    float counter = mat.GetFloat("_Blend");
    while(counter != 1f){
        float increase = mat.GetFloat("_Blend") + 0.01f;
        mat.SetFloat("_Blend", increase);
        counter += increase;
        yield return null;
    }
}

A: this part:
 foreach(Material material in materialsList){
        StartCoroutine(ChangeToWhite(material));
    }

has to contain the wait time of the change to white routine. In your case, it would be variable because you are not using Time.deltaTime which is HIGHLY encouraged by the way.
EDIT: here is the code you may want to use
foreach(Material material in materialsList){
        StartCoroutine(ChangeToWhite(material));
        yield return new WaitForSeconds(1);
    }

    private IEnumerator ChangeToWhite(Material mat){
    float counter = mat.GetFloat("_Blend");
    while(counter != 1f){ //the 1 here is the time to wait
        float increase = mat.GetFloat("_Blend") + Time.deltaTime;
        mat.SetFloat("_Blend", increase);
        counter += increase;
        yield return null;
    }
}


text:
Q: Interactions (MIMO systems) Page
According to the page above, an LTI MIMO system could be affected by many interactions.
I have two questions about this page:

*

*Is it described the system using differential equations (as well as it would be done with a spring-mass system)?

*Why does it say that the MIMO system is described by differential equations if the set of equations (8.11) is in the complex variable 's'? I guess here it was applied a Laplace transformation.

A: Yes the system is described with differential equations, i.e:
$$
\begin{align}
\dot{x} &= A x + B u \\
y &= C x + D u
\end{align}
$$
MIMO for the LTI system just mean that $B$ has $\geq 2$ columns (multiple inputs) and $C$ has $\geq 2$ rows (multiple outputs). And yes the 8.11 equation is the Laplace transformation.
For example:
$$
A = \begin{pmatrix}
0&0&1 \\0&-1&0 \\-5&-10&-15
\end{pmatrix},B = \begin{pmatrix}0 & 0 \\ 1 & 0 \\ 0 & 1 \end{pmatrix},C =\begin{pmatrix}1&0&0\\0&1&0\\0&0&1  \end{pmatrix},D=\begin{pmatrix}0&0\\0&0\\0&0\end{pmatrix}
$$
Laplace transform:
$$
\begin{pmatrix} y_1(s)\\y_2(s)\\y_3(s) \end{pmatrix} = \begin{pmatrix}\frac{-10}{s^3 + 16 s^2 + 20 s + 5} & \frac{1}{s^2 + 15 s + 5} \\
\frac{1}{s + 1}  & 0  \\
\frac{-10s}{s^3 + 16 s^2 + 20 s + 5} & \frac{s}{s^2 + 15 s + 5} \end{pmatrix} \begin{pmatrix} u_1(s) \\ u_2(s) \end{pmatrix}
$$
You can see that $u_1$ influences all outputs but $u_2$ influences only $y_1$ and $y_3$ but not $y_2$.


text:
Q: Admob Error only happening for one app I have implemented admob banners into many iOS apps, and never had this problem. Now, using the same sdk version, same code, and a variety of IDs that currently work in other app projects, this one project gives the following output and does not display a banner:
To get test ads on this device, call: request.testDevices = @[ GAD_SIMULATOR_ID ];

Why does it only happen in this Xcode project and how can I fix it? I'm not looking to find out how to enable testing mode. I want to get it to work just like all my other apps without testing mode.
Thanks!

A: It always displays that message. It i letting you know that if you want test ads to set the testing id. If you are not getting a banner then something else is occurring. Perhaps you have no ad fill or have misconfigured the ad.


text:
Q: How to use extjs Carousel for tab items I have 3 items in tabs and want to show dots navigation like extjs Carousel. Here is my code
Modified the code using layout card indicator. So indicator works for card same card content and indicator functionality required for tabs as I had added tabs in toolbar. Any Guidance please..
below is the code
Ext.define('MyPage.view.search.CardIndicator', {
    extend: 'Ext.Container',
    xtype: 'layout-card-indicator',
    controller: 'layout-card-indicator',

    requires: [
        'Ext.layout.Card',
        'Ext.tab.Panel'
    ],

    height: 300,
    layout: 'fit',
    width: 400,

    viewModel: {
        data: {
            tapMode: 'direction'
        }
    },

    items: [{
        xtype: 'panel',
        reference: 'panel',
        shadow: 'true',
        bodyPadding: 15,

        layout: {
            type: 'card',
            // The controller inserts this indicator in our bbar
            // and we publish the active index and card count
            // so we can easily disable Next/Prev buttons.
            indicator: {
                reference: 'indicator',
                bind: {
                    tapMode: '{tapMode}'
                },
                publishes: [
                    'activeIndex',
                    'count'
                ]
            }
        },

        items: [{
            title:'abc',
            html: '
Welcome to the Demo Wizard!

Step 1 of 3

Please click the "Next" button to continue...
'
        }, {
            title:'abc',
            html: '
Step 2 of 3

Almost there.  Please click the "Next" button to continue...
'
        }, {
            title:'abc',
            html: '
Congratulations!

Step 3 of 3 - Complete
'
        }],

        bbar: {
            reference: 'bbar',
            items: [
            {
                text: '« Previous',
                handler: 'onPrevious',
                bind: {
                    disabled: '{!indicator.activeIndex}'
                }
            },
            // the indicator is inserted here
            {
                text: 'Next »',
                handler: 'onNext',
                bind: {
                    disabled: '{indicator.activeIndex == indicator.count - 1}'
                }
            }
            ]
        }
    },
    {
        xtype: 'toolbar',
        docked: 'top',
        ui: 'transparent',
        padding: '5 8',
        layout: 'hbox',

        defaults: {
            shadow: 'true',
            ui: 'action'
        },

        items: [{
            xtype: 'tabpanel',
            // bind: '{tapMode}',

            tabBar: {
        docked: 'top',
        scrollable: 'horizontal',
        height:'44px',
        cls:'tabbuttons',
    },

    items: [
    {
        title: 'Tab 1'
    }, {
        title: 'Tab 2'
    }, {
        title: 'Tab 3'
    }
    ],
        }]
    }
    ]
});

Controller
Ext.define('MyPage.view.search.CardIndicatorController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.layout-card-indicator',

    init: function (tabspanel, value, oldValue) {
        var bbar = this.lookup('bbar');
        var card = this.lookup('panel').getLayout();

        // Lazily create the Indicator (wired to the card layout)
        var indicator = card.getIndicator();

        // Render it into our bottom toolbar (bbar)
        bbar.insert(1, indicator);
        var tabs = tabspanel.config.items;

        console.log(tabs);

    },

    onNext: function () {
        var card = this.lookup('panel').getLayout();

        card.next();
    },

    onPrevious: function () {
        var card = this.lookup('panel').getLayout();

        card.previous();
    }
});

A: Fix this using card index and tab index change methods.
sharing my answer it will help you to create a view for tab with bottom indicator
// on card change
cardindexchange: function(panel, value, oldValue) {
    var activeCard = Ext.getCmp('cards').getActiveItem();
    activeIndex = Ext.getCmp('cards').indexOf(activeCard);
    Ext.getCmp('tabs').setActiveItem(activeIndex);

},


text:
Q: Different result while training in CPU and GPU for Google BERT I was running few examples exploring the pytorch version of Google's new pre-trained model called the Google BERT. I ran the example in both CPU as well as GPU machines. I run the following code for sentence pair classification using the MRPC data as given in the readme
python run_classifier.py \
  --task_name MRPC \
  --do_train \
  --do_eval \
  --do_lower_case \
  --data_dir $GLUE_DIR/MRPC/ \
  --bert_model bert-base-uncased \
  --max_seq_length 128 \
  --train_batch_size 32 \
  --learning_rate 2e-5 \
  --num_train_epochs 3.0 \
  --output_dir /tmp/mrpc_output/
I get the following results.
In the CPU machine:
12/06/2018 02:01:20 - INFO - __main__ -   label: 0 (id = 0)
12/06/2018 02:01:21 - INFO - __main__ -   ***** Running evaluation *****
12/06/2018 02:01:21 - INFO - __main__ -     Num examples = 408
12/06/2018 02:01:21 - INFO - __main__ -     Batch size = 8
12/06/2018 02:04:24 - INFO - __main__ -   ***** Eval results *****
12/06/2018 02:04:24 - INFO - __main__ -     eval_accuracy = 0.8259803921568627
12/06/2018 02:04:24 - INFO - __main__ -     eval_loss = 0.40949390638692706
12/06/2018 02:04:24 - INFO - __main__ -     global_step = 345
12/06/2018 02:04:24 - INFO - __main__ -     loss = 0.22680548837651376

In the GPU machine:
12/06/2018 04:43:55 - INFO - __main__ -   label: 0 (id = 0)
12/06/2018 04:43:55 - INFO - __main__ -   ***** Running evaluation *****
12/06/2018 04:43:55 - INFO - __main__ -     Num examples = 408
12/06/2018 04:43:55 - INFO - __main__ -     Batch size = 8
12/06/2018 04:44:49 - INFO - __main__ -   ***** Eval results *****
12/06/2018 04:44:49 - INFO - __main__ -     eval_accuracy = 0.678921568627451
12/06/2018 04:44:49 - INFO - __main__ -     eval_loss = 0.5874785494570639
12/06/2018 04:44:49 - INFO - __main__ -     global_step = 345
12/06/2018 04:44:49 - INFO - __main__ -     loss = 0.5948529090570367

Why are the results coming different? And also there is a very significant difference.


text:
Q: Statistic Mode on continuous data I have a discussion with a co-worker, he insist on try to get the mode of a dataset with continuous data, with numbers that go from 0 to 3000, I say that the result are irrelevant because the repeated values will be too lower compared to the total of the data.
Can you point me to some literature that proves or disproves my point?
and what percentage of the total data can be acepted as a valid mode?
Thanks.

A: Suppose you have 1000 observations from a gamma distribution with shape 5 and rate 0.01. The following
random sample is chosen using R.
set.seed(2020)
x = rgamma(1000, 5, .01)
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  66.37  339.38  463.70  499.28  619.42 1636.80

Because this is an (unrounded) sample from a continuous
distribution all 1000 observations are different, and
the sample can have no mode.
However, the continuous distribution of the population
has a mode. Sometimes the population mode is approximated by looking at a histogram of the data, and using some
kind of interpolation to say where in the tallest bar
the population mode may lie. (The assessment of the mode
depends on the choice of histogram bins used. Sometimes the tallest bar of a histogram, if there is one, is called its modal bar.)
As @heropup suggests, a better way of finding the shape (hence mode) of the population distribution is to use a kernel density estimator (KDE).
The figure below shows a histogram of the 1000 observations. The actual population density for
$\mathsf{Gamma}(5, 0.01)$ is shown as a black curve.
(We are able to plot this curve because this is a
simulation in which we know the exact population
distribution.)
If the population distribution is unknown, then a KDE
often does a better job of estimating the mode of the
population. A KDE of the sample is shown as a dotted red line in the figure.
hist(x, prob=T, br=20, col="skyblue2",
     ylim=c(0,.002), main="1000 Obs. from GAMMA(5, .01)")
 curve(dgamma(x, 5, .01), add=T)
 lines(density(x), col="red", lwd=2, lty="dotted")

Notes: (1) By differentiating this gamma density function, one can find that the mode of its distribution (unique maximum of its density function) is at $400.$
(2) The following R code shows that the maximum of the KDE is at $374.5.$
mean(density(x)$x[density(x)$y==max(density(x)$y)])
[1] 374.5053


text:
Q: How to add more than one comment box in PHP using PHPMyAdmin? I am using PHPMyAdmin to construct a table like a comment box. The file I used is in PHP Script and I set up the 'id', 'name', and 'comment' values for the feedback/comment form using PHPMyAdmin. I was thrilled to see when I input the name and comment, it worked. Afterwards, it showed up on the bottom. Then, when I tried adding a second comment, it isn't stored anywhere on the page or the database table. It only keeps the first comment I put in and the second comment is no where to be found. I assume it has something to do with the limit of rows, but I looked in PHPMyAdmin and saw the LIMIT 0,30 which means it can take 30 comments. What am I missing here?

PHPMyAdmin settings for 'commenttable':
 SELECT *
 FROM `commenttable`
 LIMIT 0 , 30!

PHP Code:

Feedback

                <?php
                mysql_connect("localhost","username","password");
                mysql_select_db("database");
                $name=$_POST['name'];
                $comment=$_POST['comment'];
                $submit=$_POST['submit'];

                $dbLink = mysql_connect("localhost", "username", "password");
                    mysql_query("SET character_set_client=utf8", $dbLink);
                    mysql_query("SET character_set_connection=utf8", $dbLink);

                if($submit)
                {
                    if($name&&$comment)
                    {
                        $insert=mysql_query("INSERT INTO commenttable (name,comment) VALUES ('$name','$comment') ");
                    }
                    else
                    {
                        echo "please fill out all fields";
                    }
                }
                ?>

                    <form action="feedbacktest.php" method="POST">

Name: <input type="text" name="name"/>

Comment:

<textarea name="comment" rows="6" cols="30"></textarea>

<input type="submit" name="submit" value="Comment" style="cursor:pointer;">

                    </form>

                <?php
                $dbLink = mysql_connect("localhost", "username", "password");
                    mysql_query("SET character_set_results=utf8", $dbLink);
                    mb_language('uni');
                    mb_internal_encoding('UTF-8');

                $getquery=mysql_query("SELECT * FROM commenttable ORDER BY id DESC");
                while($rows=mysql_fetch_assoc($getquery))
                {
                    $id=$rows['id'];
                    $name=$rows['name'];
                    $comment=$rows['comment'];
                    echo $name . '
' . '
' . $comment . '
' . '
' . '
';
                }
                ?>

A: You need to add the attribute auto_increment to the field id. Otherwise, all entries will get the same identifier and your script will not retrieve it from the database as you are using
$getquery=mysql_query("SELECT * FROM commenttable ORDER BY id DESC");

Check out
$getquery=mysql_query("SELECT * FROM commenttable");

Does your new entry show up?
Question regarding LIMIT 0 , 30
This part of the query is only used to limit the number of returned rows to 30. This has nothing to do with how many entries your database can store. For more information see http://dev.mysql.com/doc/refman/5.0/en/select.html.


text:
Q: Seeking 2 values from a 3 value equation I have been searching for a compression method that can be expressed as a math formula. I decided that since $0-127$ is the range, and $3$ is a nominal prime number, that I would perhaps get some easily reverse engineered numbers back. So by taking off at $0$ (or $1$), I might get that compression utility I've been dreaming of. It works like a charm going into compressed format, but the trick is not quite working as it should to decompress.
So I Strictly State: This is not about coding, this is about math and if there is any construct like this in mathematics. If someone knows of one, I'd like to know.
My equation goes from 0 and starts to iteratively add and multiply from that point. They do this with initial problem being $x = 3(0 + n_0 + 3)$ Then it would take that, and iterate over it.. hence if $n_0=27$ than the answer would be $x=90$ so I would then go forth with $x = 3(90 + n_1 + 3)$ where $n_1$ is equal to the next number I wish to insert. I do this till my next data point would be over $2^{32}-1$. My question is:
Are the only answers to this going to be parabolic when I reverse engineer it with $$a = (x - 9)/3-j; j = \{ n_{y-1}, n_{y-2}, \ldots n_0 \}$$
I'm trying to use a multi-check method of 3 separate equations to find if it is the correct number from a parabola equation.
$$a == assrt$$ $$assrt*3 + j*3 + 9 - x == 0$$ $$0 == a/3 - (assrt + j + 3)$$
$assrt$ is the previous $x$ point from the initial equation, it must be divisible by 3.
$$assrt=(x−j)/3−3$$
So far, I understand that it may be parabolic which may be very difficult to get around in order to find one specific number, if possible.
Each $x$ is actually a number being hid inside a larger (of $x=3(x + n_y +3)$) number. My understanding (misunderstanding perhaps) is if I use to get the number that is the next $x$ down. However, I get one chance at this. Let's say that my $n_y$s all are between 0-127?
How do I get the right one? It seems that nearly anything will fit into the formulas I gave.
If I take away conditions I get some answers. A condition out like $(assrt*3 + j*3 + 9 - a)$, once removed, returns answers hardly close to valid. It barely varies, even when I just take the first number that works.
So, To conclude:
Is this just a parabola?
And if Not, then how do I get the answers I want?

A: So - if I understand - to code up say $(n_0,n_1,n_2,n_3,n_4)$, you generate
\begin{align}
x_0 &=3(0+n_0+3), \\
\text{ then }x_1 &=3(x_0+n_1+3), \\
x_2 &=3(x_1+n_2+3), \\
x_3 &=3(x_2+n_3+3), \\
\text{ and }x_4 &=3(x_3+n_4+3)
\end{align}
which is your final retained value.
Unfortunately this won't result in a unique coding. For example, $(n_0,n_1) = (32,120)$ produces the same $x_1=684$ as $(48,72)$. So unfortunately there is no way to reverse that process and get unique values back - if that is what you want.


text:
Q: Batch normalization in tensorflow: variables and performance I would like to add conditional operations on the variables of a batch normalization layer. Specifically, train in float, then quantize in a fine-tuning secondary training phase. For this, I want to add a tf.cond operation on the variables (scale, shift and exp moving averages of mean and var).
I replaced the tf.layers.batch_normalization  with a batchnorm layer I wrote (see below).
This function works perfectly (i.e. I get the same metrics with both functions), and I can add whatever pipeline to the variables (before the batchnorm operation). The problem is that the performance (runtime) dropped dramatically (i.e. there's a x2 factor by simply replacing the layers.batchnorm with my own function, as written below).
def batchnorm(self, x, name, epsilon=0.001, decay=0.99):
    epsilon = tf.to_float(epsilon)
    decay = tf.to_float(decay)
    with tf.variable_scope(name):
        shape = x.get_shape().as_list()
        channels_num = shape[3]
        # scale factor
        gamma = tf.get_variable("gamma", shape=[channels_num], initializer=tf.constant_initializer(1.0), trainable=True)
        # shift value
        beta = tf.get_variable("beta", shape=[channels_num], initializer=tf.constant_initializer(0.0), trainable=True)
        moving_mean = tf.get_variable("moving_mean", channels_num, initializer=tf.constant_initializer(0.0), trainable=False)
        moving_var = tf.get_variable("moving_var", channels_num, initializer=tf.constant_initializer(1.0), trainable=False)
        batch_mean, batch_var = tf.nn.moments(x, axes=[0, 1, 2]) # per channel

        update_mean = moving_mean.assign((decay * moving_mean) + ((1. - decay) * batch_mean))
        update_var = moving_var.assign((decay * moving_var) + ((1. - decay) * batch_var))

        tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mean)
        tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_var)

        bn_mean = tf.cond(self.is_training, lambda: tf.identity(batch_mean), lambda: tf.identity(moving_mean))
        bn_var = tf.cond(self.is_training, lambda: tf.identity(batch_var), lambda: tf.identity(moving_var))

        with tf.variable_scope(name + "_batchnorm_op"):
            inv = tf.math.rsqrt(bn_var + epsilon)
            inv *= gamma
            output = ((x*inv) - (bn_mean*inv)) + beta

    return output

I would appreciate help in any of the following questions:

*

*Any ideas on how to improve the performance (reduce runtime) of my solution?

*Is it possible to add my own operators to the variables pipeline of layers.batchnorm before the batchnorm operation?

*Any other solution to the same problem?

A: tf.nn.fused_batch_norm is optimized and did the trick.
I had to create two subgraphs, one per mode, since fused_batch_norm's interface does not take a conditional training/test mode (is_training is bool and not a tensor, so it's graph is not conditional). I added the condition after (see below). However, even with the two subgraphs, this has about the same runtime of tf.layers.batch_normalization.
Here's the final solution (I'd still appreciate any comment or advice for improvements):
def batchnorm(self, x, name, epsilon=0.001, decay=0.99):
    with tf.variable_scope(name):
        shape = x.get_shape().as_list()
        channels_num = shape[3]
        # scale factor
        gamma = tf.get_variable("gamma", shape=[channels_num], initializer=tf.constant_initializer(1.0), trainable=True)
        # shift value
        beta = tf.get_variable("beta", shape=[channels_num], initializer=tf.constant_initializer(0.0), trainable=True)
        moving_mean = tf.get_variable("moving_mean", channels_num, initializer=tf.constant_initializer(0.0), trainable=False)
        moving_var = tf.get_variable("moving_var", channels_num, initializer=tf.constant_initializer(1.0), trainable=False)

        (output_train, batch_mean, batch_var) = tf.nn.fused_batch_norm(x,
                                                                 gamma,
                                                                 beta,  # pylint: disable=invalid-name
                                                                 mean=None,
                                                                 variance=None,
                                                                 epsilon=epsilon,
                                                                 data_format="NHWC",
                                                                 is_training=True,
                                                                 name="_batchnorm_op")
        (output_test, _, _) = tf.nn.fused_batch_norm(x,
                                                     gamma,
                                                     beta,  # pylint: disable=invalid-name
                                                     mean=moving_mean,
                                                     variance=moving_var,
                                                     epsilon=epsilon,
                                                     data_format="NHWC",
                                                     is_training=False,
                                                     name="_batchnorm_op")

        output = tf.cond(self.is_training, lambda: tf.identity(output_train), lambda: tf.identity(output_test))

        update_mean = moving_mean.assign((decay * moving_mean) + ((1. - decay) * batch_mean))
        update_var = moving_var.assign((decay * moving_var) + ((1. - decay) * batch_var))
        tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mean)
        tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_var)

    return output